{"text": "#' km\n#' \n#' k-means via Lloyd's Algorithm.\n#' \n#' Note that the function does not respect \\code{set.seed()} or\n#' \\code{comm.set.seed()}. For managing random seeds, use the \\code{seed}\n#' parameter.\n#' \n#' @details\n#' The iterations stop either when the maximum number of iterations have been\n#' achieved, or when the centers in the current iteration are basically the same\n#' (within \\code{1e-8} for double precision and \\code{1e-4} single precision)\n#' as the centers from the previous iteration.\n#' \n#' For best performance, the data should be as balanced as possible across all\n#' MPI ranks.\n#' \n#' @section Communication:\n#' Most of the computation is local. However, at each iteration there is a\n#' length \\code{n*k} and a length \\code{k} allreduce call to update the centers.\n#' There is also a check at the beginning of the call to find out how many\n#' observations come before the current process's data, which is an allgather\n#' operation.\n#' \n#' @param x\n#' A shaq.\n#' @param k\n#' The 'k' in k-means.\n#' @param maxiter\n#' The maximum number of iterations possible.\n#' @param seed\n#' A seed for determining the (random) initial centroids. Each process has to\n#' use the same seed or very strange things may happen. If you do not provide\n#' a seed, a good initial seed will be chosen.\n#' \n#' @return\n#' A list containing the cluster centers (global), the observation labels i.e.\n#' the assignments to clusters (distributed shaq), and the total number of\n#' iterations (global).\n#'\n#' @references\n#' Phillips, J.. Data Mining: Algorithms, Geometry, and Probability.\n#' https://www.cs.utah.edu/~jeffp/DMBook/DM-AGP.html\n#' \n#' @useDynLib clustrgame R_kmeans\n#' @export\nkm_game = function(x, k=2, maxiter=100, seed=1234)\n{\n kazaam:::check.is.shaq(x)\n kazaam:::check.is.posint(k)\n kazaam:::check.is.posint(maxiter)\n kazaam:::check.is.posint(seed)\n \n k = as.integer(k)\n maxiter = as.integer(maxiter)\n comm_ptr = pbdMPI::get.mpi.comm.ptr(.pbd_env$SPMD.CT$comm)\n \n pbdMPI::comm.set.seed(seed, diff=FALSE)\n \n if (is.float(DATA(x)))\n data = DATA(x)@Data\n else\n {\n data = DATA(x)\n if (!is.double(data))\n storage.mode(data) = \"double\"\n }\n \n m = nrow(x)\n m = as.integer(m) # FIXME\n \n out = .Call(R_kmeans, data, m, k, maxiter, comm_ptr)\n \n if (is.float(DATA(x)))\n out$centers = float32(out$centers)\n \n labels.shaq = shaq(matrix(out$labels), ncols=1L, checks=FALSE)\n list(centers=out$centers, labels=labels.shaq, iterations=out$niters)\n}\n", "meta": {"hexsha": "98750749433c61c1639c7adc6a5e77b68ef60217", "size": 2480, "ext": "r", "lang": "R", "max_stars_repo_path": "R/kmeans.r", "max_stars_repo_name": "RBigData/clustrgame", "max_stars_repo_head_hexsha": "9ce336d467a953e31c6ba9a53b0795e72ca46d86", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-21T14:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-21T14:30:11.000Z", "max_issues_repo_path": "R/kmeans.r", "max_issues_repo_name": "RBigData/clustrgame", "max_issues_repo_head_hexsha": "9ce336d467a953e31c6ba9a53b0795e72ca46d86", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/kmeans.r", "max_forks_repo_name": "RBigData/clustrgame", "max_forks_repo_head_hexsha": "9ce336d467a953e31c6ba9a53b0795e72ca46d86", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 80, "alphanum_fraction": 0.6883064516, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49976403436128547}} {"text": "# 4. faza: Analiza podatkov\n\n\n#NAPOVED ŠTEVILA POROK\n\ntabela1$Vrsta <- \"Podatki\"\nmodel <- lm(Stevilo_sklenjenih_zakonskih_zvez~Leto, data=tabela1)\npr <- predict(model, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_porok <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Stevilo_sklenjenih_zakonskih_zvez = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_porok$Vrsta <- \"Napoved\"\nskupna_tabela <- rbind(tabela1, napoved_porok)\n\ngraf_napoved <- ggplot(skupna_tabela, aes(x=Leto, y=Stevilo_sklenjenih_zakonskih_zvez, shape=Vrsta)) +\n geom_smooth(method=lm, se=FALSE, fullrange = TRUE) +\n geom_point(data=tabela1, aes(x=Leto, y=Stevilo_sklenjenih_zakonskih_zvez), color=\"red\", size=3) +\n labs(title=\"Napoved števila porok\", y=\"Število porok\", x=\"Leto\") + geom_point(color=\"red\")\n\n\n#NAPOVED POVPREČNE STAROSTI PRI VSTOPU V ZAKONSKO ZVEZO\n\n#za ženske\n\nslovenija = c('Slovenija')\nsprememba_starosti_a <- tabela7 %>% filter(Drzava==\"Slovenija\", Meritev==\"povprečna starost žensk\" )\nsprememba_starosti_a$Vrsta <- \"Podatki\"\nsprememba_starosti_a$Meritev <- NULL\nmodel_a <- lm(Povprecna_starost~Leto, data=sprememba_starosti_a)\npr <- predict(model_a, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_a <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_a$Drzava <- slovenija\nnapoved_spremembe_starosti_a$Vrsta <- \"Napoved\"\nskupna_tabela_a <- rbind(sprememba_starosti_a, napoved_spremembe_starosti_a)\n\n\nŠpanija = c('Španija')\nsprememba_starosti_b <- tabela7 %>% filter(Drzava==\"Španija\", Meritev==\"povprečna starost žensk\" )\nsprememba_starosti_b$Vrsta <- \"Podatki\"\nsprememba_starosti_b$Meritev <- NULL\nmodel_b <- lm(Povprecna_starost~Leto, data=sprememba_starosti_b)\npr <- predict(model_b, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_b <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_b$Drzava <- Španija\nnapoved_spremembe_starosti_b$Vrsta <- \"Napoved\"\nskupna_tabela_b <- rbind(sprememba_starosti_b, napoved_spremembe_starosti_b)\n\nDanska = c('Danska')\nsprememba_starosti_c <- tabela7 %>% filter(Drzava==\"Danska\", Meritev==\"povprečna starost žensk\" )\nsprememba_starosti_c$Vrsta <- \"Podatki\"\nsprememba_starosti_c$Meritev <- NULL\nmodel_c <- lm(Povprecna_starost~Leto, data=sprememba_starosti_c)\npr <- predict(model_c, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_c <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_c$Drzava <- Danska\nnapoved_spremembe_starosti_c$Vrsta <- \"Napoved\"\nskupna_tabela_c <- rbind(sprememba_starosti_c, napoved_spremembe_starosti_c)\n\nnapoved_starosti <- rbind(skupna_tabela_a, skupna_tabela_b, skupna_tabela_c)\n\ngraf_napoved2 <- ggplot(napoved_starosti , aes(x=Leto, y=Povprecna_starost, col=Drzava, shape=Vrsta)) +\n geom_point() + ggtitle(\"Napoved povprečne starosti žensk ob vstopu v zakonsko zvezo\") + \n xlab(\"Leto\") + ylab(\"Povprečna starost\") + facet_grid(. ~ Drzava) + stat_smooth(method=\"lm\") + theme(axis.text.x=element_text(angle=90))\n\n\n#za moške\n\nslovenija = c('Slovenija')\nsprememba_starosti_s <- tabela7 %>% filter(Drzava==\"Slovenija\", Meritev== \"povprečna starost moških\" )\nsprememba_starosti_s$Vrsta <- \"Podatki\"\nsprememba_starosti_s$Meritev <- NULL\nmodel_s <- lm(Povprecna_starost~Leto, data=sprememba_starosti_s)\npr <- predict(model_s, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_s <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_s$Drzava <- slovenija\nnapoved_spremembe_starosti_s$Vrsta <- \"Napoved\"\nskupna_tabela_s <- rbind(sprememba_starosti_s, napoved_spremembe_starosti_s)\n\n\nDanska = c('Danska')\nsprememba_starosti_d <- tabela7 %>% filter(Drzava==\"Danska\", Meritev== \"povprečna starost moških\" )\nsprememba_starosti_d$Vrsta <- \"Podatki\"\nsprememba_starosti_d$Meritev <- NULL\nmodel_d <- lm(Povprecna_starost~Leto, data=sprememba_starosti_d)\npr <- predict(model_d, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_d <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_d$Drzava <- Danska\nnapoved_spremembe_starosti_d$Vrsta <- \"Napoved\"\nskupna_tabela_d <- rbind(sprememba_starosti_d, napoved_spremembe_starosti_d)\n\n\nŠpanija = c('Španija')\nsprememba_starosti_sp <- tabela7 %>% filter(Drzava==\"Španija\", Meritev== \"povprečna starost moških\" )\nsprememba_starosti_sp$Vrsta <- \"Podatki\"\nsprememba_starosti_sp$Meritev <- NULL\nmodel_sp <- lm(Povprecna_starost~Leto, data=sprememba_starosti_sp)\npr <- predict(model_sp, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_spremembe_starosti_sp <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Povprecna_starost = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_spremembe_starosti_sp$Drzava <- Španija\nnapoved_spremembe_starosti_sp$Vrsta <- \"Napoved\"\nskupna_tabela_sp <- rbind(sprememba_starosti_sp, napoved_spremembe_starosti_sp)\n\n\nnapoved_starosti_moski <- rbind(skupna_tabela_s, skupna_tabela_d, skupna_tabela_sp)\n\ngraf_napoved3 <- ggplot(napoved_starosti_moski , aes(x=Leto, y=Povprecna_starost, col=Drzava, shape=Vrsta)) +\n geom_point() + ggtitle(\"Napoved povprečne starosti moških ob vstopu v zakonsko zvezo\") + \n xlab(\"Leto\") + ylab(\"Povprečna starost\") + facet_grid(. ~ Drzava) + stat_smooth(method=\"lm\") + \n theme(axis.text.x=element_text(angle=90))\n\n \n", "meta": {"hexsha": "fdd4cac6a035cec2a42242680c5322f721e5a282", "size": 5685, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "Nina2809/APPR-2020-21", "max_stars_repo_head_hexsha": "b2d15c7ed27f948633de51be72c0bfc4cc1d9c8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "Nina2809/APPR-2020-21", "max_issues_repo_head_hexsha": "b2d15c7ed27f948633de51be72c0bfc4cc1d9c8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-30T12:58:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T12:38:21.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "Nina2809/APPR-2020-21", "max_forks_repo_head_hexsha": "b2d15c7ed27f948633de51be72c0bfc4cc1d9c8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6818181818, "max_line_length": 154, "alphanum_fraction": 0.7577836412, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.49965541211574693}} {"text": "#simple occupancy model with data in long format (one line per visit) \n#this version has List Length as a covariate and Site effect\noccDetBUGScode <- function(){ \n # Priors \n # state model priors\n for(t in 1:nyear){\n a[t] ~ dunif(-10,10) \n } \n \n # RANDOM EFFECT for SITE\n for (i in 1:nsite) {\n eta[i] ~ dnorm(0, tau2) # extra random site-effect op occ. (previously it was mu2: changed Jan 2014)\n } \n \n tau2 <- 1/(sigma2 * sigma2) # NOT NEEDED IN SIMPLE MODEL\n sigma2 ~ dunif(0, 5)\n \n \n # observation model priors \n for (t in 1:nyear) {\n alpha.p[t] ~ dnorm(mu.lp, tau.lp) # p random year\n }\n \n mu.lp ~ dnorm(0, 0.01) \n tau.lp <- 1 / (sd.lp * sd.lp) \n sd.lp ~ dunif(0, 5) \n \n LL.p ~ dunif(dtype2p_min, dtype2p_max)\n \n # State model\n for (i in 1:nsite){ \n for (t in 1:nyear){ \n z[i,t] ~ dbern(muZ[i,t]) # True occupancy z at site i\n logit(muZ[i,t])<- a[t] + eta[i] # plus random site effect\n }} \n \n # Observation model \n # go through the visits and find the matching year and site identity\n for(j in 1:nvisit) {\n #for each visit, find the matching site and year identities\n Py[j]<- z[Site[j],Year[j]]*p[j] \n logit(p[j]) <- alpha.p[Year[j]] + LL.p*logL[j]\n y[j] ~ dbern(Py[j]) \n Presi[j] <- abs(y[j]-p[j])\n y.new[j] ~ dbern(Py[j]) \n Presi.new[j] <- abs(y.new[j]-p[j])\n }\n \n # Bayesian Goodness-of-Fit\n fit <- sum(Presi[])\n fit.new <- sum(Presi.new[])\n \n # Derived parameters state model\n \n # Finite sample occupancy\n for (t in 1:nyear) { \n psi.fs[t] <- sum(z[1:nsite,t])/nsite\n } \n \n # Overall trend in occpuancy\n sumY <- sum(psi.fs[1:nyear])\n for (t in 1:nyear) {\n sumxy[t] <- psi.fs[t]*t\n }\n sumXY <- sum(sumxy[1:nyear])\n regres.psi <- (sumXY - ((sumX*sumY)/nyear))/(sumX2 - ((sumX*sumX)/nyear))\n \n # Derived parameters observation model\n for (t in 1:nyear) { \n pdet.alpha[t] <- exp(alpha.p[t])/(1 + exp(alpha.p[t])) \n }\n \n # overall trend in pdet.alpha\n sumYpdet <- sum(pdet.alpha[1:nyear]) \n for (t in 1:nyear) { \n sumxypdet[t] <- pdet.alpha[t]*t\n }\n sumXYpdet <- sum(sumxypdet[1:nyear])\n regres.pdet <- (sumXYpdet - ((sumX*sumYpdet)/nyear))/(sumX2 - ((sumX*sumX)/nyear))\n \n # end of model formulation\n}", "meta": {"hexsha": "f98a039f3a71f093dde0feab13612c24f1e2f1a0", "size": 2329, "ext": "r", "lang": "R", "max_stars_repo_path": "R/occDetBUGScode.r", "max_stars_repo_name": "03rcooke/sparta", "max_stars_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-06-08T14:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:16:30.000Z", "max_issues_repo_path": "R/occDetBUGScode.r", "max_issues_repo_name": "03rcooke/sparta", "max_issues_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 200, "max_issues_repo_issues_event_min_datetime": "2015-10-26T16:17:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T12:04:59.000Z", "max_forks_repo_path": "R/occDetBUGScode.r", "max_forks_repo_name": "AugustT/sparta", "max_forks_repo_head_hexsha": "84594eeaaca02954ac05d058e5cc6eedb2fb3918", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-10-26T16:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T13:50:07.000Z", "avg_line_length": 28.4024390244, "max_line_length": 110, "alphanum_fraction": 0.5641906398, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4996393036877908}} {"text": "#' Pairwise SERE for two samples\n#'\n#' Compute the SERE coefficient for two samples\n#'\n#' @param observed \\code{matrix} with two columns containing observed counts of two samples\n#' @return The SERE coefficient for the two samples\n#' @references Schulze, Kanwar, Golzenleuchter et al, SERE: Single-parameter quality control and sample comparison for RNA-Seq, BMC Genomics, 2012\n#' @author See paper published\n\nSERE <- function(observed){\n #calculate lambda and expected values\n observed = as.matrix(observed)\n laneTotals <- colSums(observed)\n total <- sum(laneTotals)\n fullObserved <- observed[rowSums(observed)>0,]\n fullLambda <- rowSums(fullObserved)/total\n fullLhat <- fullLambda > 0\n fullExpected<- outer(fullLambda, laneTotals)\n\n #keep values\n fullKeep <- which(fullExpected > 0)\n\n #calculate degrees of freedom (nrow*(ncol -1) >> number of parameters - calculated (just lamda is calculated >> thats why minus 1)\n #calculate pearson and deviance for all values\n oeFull <- (fullObserved[fullKeep] - fullExpected[fullKeep])^2/ fullExpected[fullKeep] # pearson chisq test\n dfFull <- length(fullKeep) - sum(fullLhat!=0)\n\n sqrt(sum(oeFull)/dfFull)\n}", "meta": {"hexsha": "4709c08112ac65693d9092e4f033fc3086aa21ec", "size": 1164, "ext": "r", "lang": "R", "max_stars_repo_path": "SERE.r", "max_stars_repo_name": "jianjinxu/normSet", "max_stars_repo_head_hexsha": "a940290f37175022a2e376e105edcf129945590a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SERE.r", "max_issues_repo_name": "jianjinxu/normSet", "max_issues_repo_head_hexsha": "a940290f37175022a2e376e105edcf129945590a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SERE.r", "max_forks_repo_name": "jianjinxu/normSet", "max_forks_repo_head_hexsha": "a940290f37175022a2e376e105edcf129945590a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1379310345, "max_line_length": 146, "alphanum_fraction": 0.7448453608, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49958430043437574}} {"text": "bound <- function(x, p = 0.0001) {\r\n pmax(pmin(x, 1 - p), p)\r\n}\r\n\r\ntruncate <- function(x, p = 0.01) {\r\n pmin(pmax(x, p), 1 - p)\r\n}\r\n\r\ngfun <- function(a, w) {\r\n pscore <- plogis(2 - 1 / (- rowSums(w) / 4 + 1))\r\n return(a * pscore + (1 - a) * (1 - pscore))\r\n}\r\n\r\ngdeltafun <- function(a, w, delta){\r\n pscore <- delta * gfun(1, w) / (delta * gfun(1, w) + 1 - gfun(1, w))\r\n return(a * pscore + (1 - a) * (1 - pscore))\r\n}\r\n\r\ngdelta1 <- function(g, delta){\r\n delta * g / (delta * g + 1 - g)\r\n}\r\n\r\npl <- function(l, a, w) {\r\n prob1 <- plogis(rowMeans(w) - a - log(2) + 0.2)\r\n return(l * prob1 + (1 - l) * (1 - prob1))\r\n}\r\n\r\npz <- function(z, l, a, w) {\r\n prob1 <- plogis(rowSums(log(3) * w[, -3]) + a - l)\r\n return(z * prob1 + (1 - z) * (1 - prob1))\r\n}\r\n\r\nmy <- function(z, l, a, w) {\r\n plogis(1 - 3 / (2 + rowSums(w) / 3 - l - 3 * a + z))\r\n ## plogis((rowSums(w) - l + 3 * a * z))\r\n}\r\n\r\npzaw <- function(z, a, w) pz(z, 1, a, w) * pl(1, a, w) + pz(z, 0, a, w) * pl(0, a, w)\r\npzw <- function(z, w) pzaw(z, 1, w) * gfun(1, w) + pzaw(z, 0, w) * gfun(0, w)\r\n\r\nu <- function(z, a, w) my(z, 1, a, w) * pl(1, a, w) + my(z, 0, a, w) * pl(0, a, w)\r\nv <- function(l, a, w) my(1, l, a, w) * pzaw(1, a, w) + my(0, l, a, w) * pzaw(0, a, w)\r\ns <- function(l, a, w) my(1, l, a, w) * pzw(1, w) + my(0, l, a, w) * pzw(0, w)\r\n\r\nubar <- function(a, w) u(1, a, w) * pzaw(1, a, w) + u(0, a, w) * pzaw(0, a, w)\r\nsbar <- function(a, w) s(1, a, w) * pl(1, a, w) + s(0, a, w) * pl(0, a, w)\r\nvbar <- ubar\r\nq <- function(a, w) u(1, a, w) * pzw(1, w) + u(0, a, w) * pzw(0, w)\r\n\r\nsimdata <- function(n_obs = 1000) {\r\n ## helper functions for nuisance parameter estimation\r\n ## baseline covariate -- simple, binary\r\n w_1 <- rbinom(n_obs, 1, prob = 0.6)\r\n w_2 <- rbinom(n_obs, 1, prob = 0.3)\r\n w_3 <- rbinom(n_obs, 1, prob = pmin(0.2 + (w_1 + w_2) / 3, 1))\r\n w <- cbind(w_1, w_2, w_3)\r\n w_names <- paste(\"W\", seq_len(ncol(w)), sep = \"\")\r\n\r\n ## exposure/treatment\r\n a <- as.numeric(rbinom(n_obs, 1, prob = gfun(1, w)))\r\n\r\n ## mediator-outcome confounder affected by treatment\r\n l <- rbinom(n_obs, 1, pl(1, a, w))\r\n\r\n ## mediator (possibly multivariate)\r\n z <- rbinom(n_obs, 1, pz(1, l, a, w))\r\n z_names <- \"Z\"\r\n\r\n ## outcome\r\n y <- rbinom(n_obs, 1, my(z, l, a, w))\r\n\r\n colnames(w) <- w_names\r\n ## construct data for output\r\n dat <- as.data.frame(cbind(W = w, A = a, Z = z, L = l, Y = y))\r\n return(dat)\r\n}\r\n\r\n\r\ntruth <- function(n_obs = 1e7, delta = 2){\r\n\r\n w_1 <- rbinom(n_obs, 1, prob = 0.6)\r\n w_2 <- rbinom(n_obs, 1, prob = 0.3)\r\n w_3 <- rbinom(n_obs, 1, prob = pmin(0.2 + (w_1 + w_2) / 3, 1))\r\n w <- cbind(w_1, w_2, w_3)\r\n w_names <- paste(\"W\", seq_len(ncol(w)), sep = \"\")\r\n\r\n ## exposure/treatment\r\n a <- as.numeric(rbinom(n_obs, 1, prob = gfun(1, w)))\r\n\r\n ## mediator-outcome confounder affected by treatment\r\n l <- rbinom(n_obs, 1, pl(1, a, w))\r\n\r\n ## mediator (possibly multivariate)\r\n z <- rbinom(n_obs, 1, pz(1, l, a, w))\r\n z_names <- \"Z\"\r\n\r\n ## outcome\r\n y <- rbinom(n_obs, 1, my(z, l, a, w))\r\n\r\n eif10 <- pzaw(z, a, w) / pz(z, l, a, w) * (y - my(z, l, a, w)) +\r\n v(l, a, w) - vbar(a, w) + u(z, a, w)\r\n\r\n eif1d <- gdeltafun(a, w, delta) / gfun(a, w) * pzaw(z, a, w) / pz(z, l, a, w) *\r\n (y - my(z, l, a, w)) +\r\n gdeltafun(a, w, delta) / gfun(a, w) * (v(l, a, w) - vbar(a, w) + u(z, a, w)) +\r\n (1 - gdeltafun(a, w, delta) / gfun(a, w)) *\r\n (ubar(1, w) * gdeltafun(1, w, delta) + ubar(0, w) * gdeltafun(0, w, delta))\r\n\r\n eif2d <- gdeltafun(a, w, delta) / gfun(a, w) * pzw(z, w) / pz(z, l, a, w) *\r\n (y - my(z, l, a, w)) +\r\n gdeltafun(a, w, delta) / gfun(a, w) * (s(l, a, w) - sbar(a, w)) +\r\n u(z, 1, w) * gdeltafun(1, w, delta) + u(z, 0, w) * gdeltafun(0, w, delta) +\r\n gdeltafun(a, w, delta) / gfun(a, w) * (q(a, w) - (q(1, w) * gdeltafun(1, w, delta) +\r\n q(0, w) * gdeltafun(0, w, delta)))\r\n\r\n efbde <- var(eif10 - eif2d)\r\n efbie <- var(eif2d - eif1d)\r\n\r\n de <- mean(eif10 - eif2d)\r\n ie <- mean(eif2d - eif1d)\r\n\r\n return(data.frame(parameter = c('DE', 'IE'),\r\n truth = c(de, ie),\r\n eff_bound = c(efbde, efbie)))\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ec204fb3c607f2152ae1c18910f2edd2d49af679", "size": 4323, "ext": "r", "lang": "R", "max_stars_repo_path": "sandbox/intmedlite/sandbox/utils.r", "max_stars_repo_name": "nhejazi/medshift", "max_stars_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-01-11T17:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T01:12:08.000Z", "max_issues_repo_path": "sandbox/intmedlite/sandbox/utils.r", "max_issues_repo_name": "nhejazi/medshift", "max_issues_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-01-15T19:11:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T06:54:52.000Z", "max_forks_repo_path": "sandbox/intmedlite/sandbox/utils.r", "max_forks_repo_name": "nhejazi/medshift", "max_forks_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-02T15:56:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T21:35:25.000Z", "avg_line_length": 33.511627907, "max_line_length": 93, "alphanum_fraction": 0.46703678, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.49944285447301356}} {"text": "#' Function to convert SST data to d18O\n#' \n#' Takes a matrix of SST data (in degrees C) against time (in days), information\n#' about the d18O value (in permille VSMOW) of the water and how it changes\n#' through the year and the transfer function used for of the record (e.g.\n#' Kim and O'Neil, 1997 or Grossman and Ku, 1986). Converts the SST data to d18O\n#' data using the supplied empirical transfer function.\n#' \n#' @param SST Matrix with a time column (values in days) and an SST column\n#' (values in degrees C)\n#' @param d18Ow Either a single value (constant d18Ow) or a vector of length\n#' equal to the period in SST data (365 days by default) containing information\n#' about seasonality in d18Ow. Defaults to constant d18Ow of 0 permille VSMOW\n#' (the modern mean ocean value)\n#' @param transfer_function String containing the name of the transfer function\n#' (for example: \\code{\"KimONeil97\"} or \\code{\"GrossmanKu86\"}). Defaults to\n#' Kim and O'Neil (1997).\n#' @return A vector containing d18O values for each SST value in \\code{\"SST\"}\n#' @references Grossman, E.L., Ku, T., Oxygen and carbon isotope fractionation in biogenic\n#' aragonite: temperature effects, _Chemical Geology_ **1986**, _59.1_, 59-74.\n#' \\doi{10.1016/0168-9622(86)90057-6}\n#' Kim, S., O'Niel, J.R., Equilibrium and nonequilibrium oxygen\n#' isotope effects in synthetic carbonates, _Geochimica et Cosmochimica Acta_\n#' **1997**, _61.16_, 3461-3475.\n#' \\doi{10.1016/S0016-7037(97)00169-5}\n#' Dettman, D.L., Reische, A.K., Lohmann, K.C., Controls on the stable isotope\n#' composition of seasonal growth bands in aragonitic fresh-water bivalves\n#' (Unionidae), _Geochimica et Cosmochimica Acta_ **1999**, _63.7-8_, 1049-1057.\n#' \\doi{10.1016/S0016-7037(99)00020-4}\n#' Brand, W.A., Coplen, T.B., Vogl, J., Rosner, M., Prohaska, T., Assessment of\n#' international reference materials for isotope-ratio analysis (IUPAC Technical\n#' Report), _Pure and Applied Chemistry_ **2014**, _86.3_, 425-467.\n#' \\doi{10.1515/pac-2013-1023}\n#' Kim, S.-T., Coplen, T. B., and Horita, J.: Normalization of stable\n#' isotope data for carbonate minerals: Implementation of IUPAC\n#' guidelines, Geochim. Cosmochim. Ac. **2015** 158, 276-289.\n#' \\doi{10.1016/j.gca.2015.02.011}\n#' @examples\n#' # Create dummy SST data\n#' t <- seq(1, 40, 1)\n#' T <- sin((2 * pi * (seq(1, 40, 1) - 8 + 10 / 4)) / 10)\n#' SST <- cbind(t, T)\n#' # Run d18O model function\n#' d18O <- d18O_model(SST, 0, \"KimONeil97\")\n#' @export\nd18O_model <- function(SST, # Function that converts SST values into d18O \n d18Ow = 0, # Information on the d18O of seawater (d18Ow), should be either one single number (constant) or a vector of length 365 (value for every day of the year)\n transfer_function = \"KimONeil97\" # Supply transfer function. Current options are: Kim and O'Neil (calcite calibration; 1997; \"KimONeil97\") or Grossman and Ku (aragonite calibration; 1986; \"GrossmanKu86\")\n ){\n\n if(!is.numeric(d18Ow)){\n d18Ow <- rep(0, length(SST[,1])) # Set default d18Ow vector to constant at d18Ow = 0\n }else if(length(d18Ow) == 1){\n d18Ow <- rep(d18Ow, length(SST[,1])) # Create constant d18Ow vector if only one number is given\n }else{\n d18Ow <- c(0, rep(d18Ow, length(SST[,1])/length(d18Ow))) # If d18Ow is a vector with more than one value, multiply it to reach the same length of SST (multiply by \"years\")\n }\n if(transfer_function == \"KimONeil97\"){\n d18Oc <- cbind(SST[,1], (exp((18.03 * 1000 / (SST[,2] + 273.15) - 32.42) / 1000) - 1) * 1000 + (0.97001 * d18Ow - 29.99)) # Use Kim and O'Neil (1997) with conversion between VSMOW and VPDB by Brand et al. (2014) and Kim et al. (2015)\n }else if(transfer_function == \"GrossmanKu86\"){\n d18Oc <- cbind(SST[,1], (20.6 - SST[,2]) / 4.34 + d18Ow + 0.2) # Use Grossmann and Ku (1986) modified by Dettmann et al. (1999)\n }else{\n return(\"ERROR: Supplied transfer function is not recognized\")\n }\n return(d18Oc)\n}", "meta": {"hexsha": "eb2741fe088552af1da2c6a6cd2962d4de798f9c", "size": 3971, "ext": "r", "lang": "R", "max_stars_repo_path": "R/d18O_model.r", "max_stars_repo_name": "nhoeche/ShellChron.jl", "max_stars_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/d18O_model.r", "max_issues_repo_name": "nhoeche/ShellChron.jl", "max_issues_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/d18O_model.r", "max_forks_repo_name": "nhoeche/ShellChron.jl", "max_forks_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.1666666667, "max_line_length": 241, "alphanum_fraction": 0.6824477462, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4994428467686039}} {"text": "subroutine master(x,y,rw,npd,ntot,nadj,madj,eps,delsgs,ndel,delsum,\n dirsgs,ndir,dirsum,collinchk,nerror)\n\n# Master subroutine:\n# One subroutine to rule them all,\n# One subroutine to find them.\n# One subroutine to bring them all in,\n# And in the darkness bind them.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot)\ndimension nadj(-3:ntot,0:madj)\ndimension rw(4)\ndimension delsgs(6,ndel), dirsgs(10,ndir)\ndimension delsum(npd,4), dirsum(npd,3)\ninteger collinchk\n\n# Define one.\none = 1.d0\n\n# Initialize the adjacency list; counts to 0, other entries to -99.\ndo i = -3,ntot {\n\tnadj(i,0) = 0\n\tdo j = 1,madj {\n\t\tnadj(i,j) = -99\n\t}\n}\n\n# Put the four ideal points into x and y and the adjacency list.\n# The ideal points are given pseudo-coordinates\n# (-1,-1), (1,-1), (1,1), and (-1,1). They are numbered as\n# 0 -1 -2 -3\n# i.e. the numbers decrease anticlockwise from the\n# `bottom left corner'.\nx(-3) = -one\ny(-3) = one\nx(-2) = one\ny(-2) = one\nx(-1) = one\ny(-1) = -one\nx(0) = -one\ny(0) = -one\n\ndo i = 1,4 {\n j = i-4\n k = j+1\n if(k>0) k = -3\n\tcall insrt(j,k,nadj,madj,x,y,ntot,nerror,eps)\n if(nerror>0) return\n}\n\n# Put in the first of the point set into the adjacency list.\ndo i = 1,4 {\n j = i-4\n\tcall insrt(1,j,nadj,madj,x,y,ntot,nerror,eps)\n if(nerror>0) return\n}\nntri = 4\n\n# Now add the rest of the point set\ndo j = 2,npd {\n\tcall addpt(j,nadj,madj,x,y,ntot,eps,ntri,nerror)\n if(collinchk==1) call collincheck(nadj,j,madj,x,y,ntot,eps)\n if(nerror>0) {\n return\n }\n ntri = ntri + 3\n}\n\n# Obtain the description of the triangulation.\ncall delseg(delsgs,ndel,nadj,madj,npd,x,y,ntot,nerror)\nif(nerror>0) return\n\ncall delout(delsum,nadj,madj,x,y,ntot,npd,nerror)\nif(nerror>0) return\n\ncall dirseg(dirsgs,ndir,nadj,madj,npd,x,y,ntot,rw,eps,ntri,nerror)\nif(nerror>0) return\ncall dirout(dirsum,nadj,madj,x,y,ntot,npd,rw,eps,nerror)\nreturn\nend\n", "meta": {"hexsha": "0a5db5496da2d1dfbe8774fbae9fd4d4dbf4f858", "size": 1974, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/SavedRatfor/master.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/SavedRatfor/master.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/SavedRatfor/master.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 24.0731707317, "max_line_length": 67, "alphanum_fraction": 0.6377912867, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4990836954869576}} {"text": "# --------------------------------------------\r\n# COMMANDS FOR FITTING CONSTANT MODEL FOR EX1\r\n# SECTION 4.1.1\r\n# --------------------------------------------\r\n\r\nlibrary(bivpois) # load bivpois library\r\ndata(ex1.sim) # load data of example 1\r\n# -------------------------------------------------------------------------------\r\n\r\nxtemp<-readline(prompt = \"Press Enter to Continue\")\r\n\r\n# Simple Bivariate Poisson Model\r\nex1.simple<-simple.bp( ex1.sim$x, ex1.sim$y ) # fit simple model of section 4.1.1\r\n\r\nnames(ex1.simple) # monitor output variables\r\nex1.simple$lambda # view lambda1 \r\nex1.simple$BIC # view BIC\r\nex1.simple # view all results of the model\r\nxtemp<-readline(prompt = \"Press Enter to Continue\")\r\n#\r\n# plot of loglikelihood vs. iterations\r\nwin.graph()\r\nplot( 1:ex1.simple$iterations, ex1.simple$loglikelihood, xlab='Iterations',ylab='Log-likelihood', type='l' )\r\n\r\n# -------------------------------------\r\n# COMMANDS FOR FITTING MODELS FOR EX1\r\n# SECTION 4.1.2\r\n# -------------------------------------\r\nex1.m2<-lm.bp(x~1 , y~1 , data=ex1.sim, zeroL3=TRUE)\t\t\t# Model 2: DblPoisson(l1, l2)\r\nex1.m3<-lm.bp(x~1 , y~1 , data=ex1.sim)\t\t\t\t\t# Model 3: BivPoisson(l1, l2, l3)\r\nex1.m4<-lm.bp(x~. , y~. , data=ex1.sim, zeroL3=TRUE)\t\t\t# Model 4: DblPoisson (l1=Full, l2=Full) \r\nex1.m5<-lm.bp(x~. , y~. , data=ex1.sim)\t\t\t\t\t# Model 5: BivPoisson(l1=full, l2=full, l3=constant)\r\nex1.m6<-lm.bp(x~z1 , y~z1+z5 , l1l2=~z3, data=ex1.sim, zeroL3=TRUE)\t# Model 6: DblPois(l1,l2)\r\nex1.m7<-lm.bp(x~z1 , y~z1+z5 , l1l2=~z3, data=ex1.sim)\t\t\t# Model 7: BivPois(l1,l2,l3=constant)\r\nex1.m8<-lm.bp(x~. , y~. , l3=~., data=ex1.sim)\t\t\t\t# Model 8: BivPoisson(l1=full, l2=full, l3=full)\r\nex1.m9<-lm.bp(x~. , y~. , l3=~.-z5, data=ex1.sim)\t\t\t# Model 9: BivPoisson(l1=full, l2=full, l3=z1+z2+z3+z4)\r\nex1.m10<-lm.bp(x~z1 , y~z1+z5 , l1l2=~z3, l3=~., data=ex1.sim)\t\t# Model 10: BivPoisson(l1, l2, l3=full)\r\nex1.m11<-lm.bp(x~z1 , y~z1+z5 , l1l2=~z3, l3=~.-z5, data=ex1.sim)\t# Model 11: BivPoisson(l1, l2, l3= z1+z2+z3+z4)\r\nex1.m11$coef # monitor all beta parameters of model 11\r\n#\r\nex1.m11$beta1 # monitor all beta parameters of lambda1 of model 11\r\nex1.m11$beta2 # monitor all beta parameters of lambda2 of model 11\r\nex1.m11$beta3 # monitor all beta parameters of lambda3 of model 11\r\n\r\n\r\n", "meta": {"hexsha": "09cbe30cc2f8972c9999b694ed441d43a6db9e73", "size": 2307, "ext": "r", "lang": "R", "max_stars_repo_path": "bivpois/demo/ex1.r", "max_stars_repo_name": "Louagyd/FootballScorelineForecasting", "max_stars_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bivpois/demo/ex1.r", "max_issues_repo_name": "Louagyd/FootballScorelineForecasting", "max_issues_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bivpois/demo/ex1.r", "max_forks_repo_name": "Louagyd/FootballScorelineForecasting", "max_forks_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.152173913, "max_line_length": 114, "alphanum_fraction": 0.5782401387, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4990776564080287}} {"text": "\nlibrary(binom)\nlibrary(bbmle)\n\ncompute.gamma.stat = function (x, p.lower, p.upper) {\n gamma.mean.variance.loglik = function (mu, sigma.2) {\n alpha = mu * mu / sigma.2;\n beta = mu / sigma.2;\n loglik = -sum(dgamma(x, alpha, beta, log=TRUE));\n return(loglik);\n }\n \n if (sum(!is.na(x)) > 1 && sd(x) > 1e-5) {\n stat = mle2(gamma.mean.variance.loglik,\n start = list(mu = mean(x), sigma.2 = var(x)),\n method = 'L-BFGS-B',\n lower = p.lower, upper = p.upper);\n \n ci = confint(stat, 'mu', quitely=T)\n while (is(ci, 'mle2')) {\n stat = mle2(gamma.mean.variance.loglik,\n start = list(\n mu = unname(coef(ci)['mu.mu']),\n sigma.2 = unname(coef(ci)['sigma.2'])\n ),\n method = 'L-BFGS-B',\n lower = p.lower, upper = p.upper);\n \n ci = confint(stat, 'mu', quitely=T)\n }\n\n return(list(\n mean = unname(coef(stat)['mu']),\n sigma.2 = unname(coef(stat)['sigma.2']),\n lower = unname(ci[1]),\n upper = unname(ci[2])\n ));\n } else {\n return(compute.normal.stat(x, p.lower, p.upper, sigma.2 = var(x)));\n }\n}\n\ncompute.beta.stat = function (x, p.lower, p.upper) {\n x = pmin(0.5 - 1e-16, pmax(1e-16, x))\n\n beta.mean.v.loglik = function (mu, v) {\n mu.2x = mu * 2;\n alpha = mu.2x * v;\n beta = (1 - mu.2x) * v;\n loglik = -sum(pmin(1e6, pmax(-1e6, dbeta(x, alpha, beta, log=TRUE))));\n return(loglik);\n }\n \n v.init = (mean(x) * (0.5 - mean(x))) / var(x) - 1\n \n if (sum(!is.na(x)) > 1 && sd(x) > 1e-10) {\n stat = mle2(beta.mean.v.loglik,\n start = list(\n mu = mean(x),\n v = v.init\n ),\n method = 'L-BFGS-B',\n lower = c(mu=0, v=1e-5), upper = c(mu=0.5, v=Inf));\n \n if (any(is.na(unname(summary(stat)@coef[, \"Std. Error\"])) &\n is.na(sqrt(1/diag(stat@details$hessian))))) {\n return(compute.normal.stat(x, p.lower, p.upper, v = v.init));\n }\n ci = confint(stat, 'mu', quitely=T)\n \n while (is(ci, 'mle2')) {\n stat = mle2(beta.mean.v.loglik,\n start = list(\n mu = unname(coef(ci)['mu.mu']),\n v = unname(coef(ci)['v'])\n ),\n method = 'L-BFGS-B',\n lower = c(mu=0, v=1e-5), upper = c(mu=0.5, v=Inf));\n \n if (any(is.na(unname(summary(stat)@coef[, \"Std. Error\"])) &\n is.na(sqrt(1/diag(stat@details$hessian))))) {\n return(compute.normal.stat(x, p.lower, p.upper, v = v.init));\n }\n ci = confint(stat, 'mu', quitely=T)\n }\n \n return(list(\n mean = unname(coef(stat)['mu']),\n v = unname(coef(stat)['v']),\n lower = unname(ci[1]),\n upper = unname(ci[2])\n ));\n } else {\n return(compute.normal.stat(x, p.lower, p.upper, v = v.init));\n }\n}\n\ncompute.normal.stat = function (x, p.lower, p.upper, ...) {\n mu = mean(x);\n alpha = 0.95;\n\n if (length(x) > 1) {\n ci = abs(qt((1 - alpha) / 2, length(x) - 1)) * (sd(x) / sqrt(length(x)));\n \n return(list(\n mean = mu,\n lower = min(p.upper['mu'], max(p.lower['mu'], mu - ci)),\n upper = min(p.upper['mu'], max(p.lower['mu'], mu + ci)),\n ...\n ));\n } else {\n return(list(mean = mu, lower = NA, upper = NA, ...));\n }\n}\n\ncompute.summary = function (df.group, vars, assume.normal = FALSE) {\n solved = with(df.group, solved);\n converged.at = with(df.group, extrapolation.step.solved[solved]);\n sparse.error = with(df.group, sparse.error.max[solved]);\n \n success.rate.stat = binom.confint(\n sum(solved), length(solved),\n conf.level = 0.95, method = 'wilson'\n );\n \n if (assume.normal) {\n sparse.error.stat = compute.normal.stat(\n sparse.error,\n c(mu=0, sigma.2=1e-5),\n c(mu=0.5, sigma.2=Inf),\n v = (mean(x) * (0.5 - mean(x))) / var(x) - 1\n );\n } else {\n sparse.error.stat = compute.beta.stat(\n sparse.error,\n c(mu=0, sigma.2=1e-5),\n c(mu=0.5, sigma.2=Inf)\n );\n }\n \n if (assume.normal) {\n converged.at.stat = compute.normal.stat(\n converged.at,\n c(mu=0, sigma.2=1e-5),\n c(mu=Inf, sigma.2=Inf),\n sigma.2 = var(x)\n );\n } else {\n converged.at.stat = compute.gamma.stat(\n converged.at,\n c(mu=0, sigma.2=1e-5),\n c(mu=Inf, sigma.2=Inf)\n );\n }\n \n return(data.frame(\n success.rate.mean = success.rate.stat$mean,\n success.rate.lower = success.rate.stat$lower,\n success.rate.upper = success.rate.stat$upper,\n success.rate.max = NA,\n \n converged.at.median = ifelse(length(converged.at) > 0, median(converged.at), NA),\n converged.at.sigma.2 = converged.at.stat$sigma.2,\n converged.at.mean = converged.at.stat$mean,\n converged.at.lower = converged.at.stat$lower,\n converged.at.upper = converged.at.stat$upper,\n converged.at.max = ifelse(length(converged.at) > 0, max(converged.at), NA),\n \n sparse.error.v = sparse.error.stat$v,\n sparse.error.mean = sparse.error.stat$mean,\n sparse.error.lower = sparse.error.stat$lower,\n sparse.error.upper = sparse.error.stat$upper,\n sparse.error.max = NA\n ));\n}\n", "meta": {"hexsha": "6a82a5c6c447131ed364ed082e2da87c1addb042", "size": 5213, "ext": "r", "lang": "R", "max_stars_repo_path": "export/_compute_summary.r", "max_stars_repo_name": "bmistry4/nalm-benchmark", "max_stars_repo_head_hexsha": "273c95cc75241f56e48bcd0b18b043969ef82004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "export/_compute_summary.r", "max_issues_repo_name": "bmistry4/nalm-benchmark", "max_issues_repo_head_hexsha": "273c95cc75241f56e48bcd0b18b043969ef82004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "export/_compute_summary.r", "max_forks_repo_name": "bmistry4/nalm-benchmark", "max_forks_repo_head_hexsha": "273c95cc75241f56e48bcd0b18b043969ef82004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6193181818, "max_line_length": 85, "alphanum_fraction": 0.5215806637, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4984184480335287}} {"text": "## Functions for scaling the bootstrapped matrices\n\n\n## These functions a helper functions that feed into scale_factor_R\n## scale_factor_R takes the matrices elements of two contact matrices\n## from the social mixR package, the matrices need to be bootstrapped ones\n## as social mixr calls the element matrices when bootstrapped and matrix \n## when just one value is created. \n\n## mat1 and mat2 are the matrices objects\n\n\n\n# Split contact matrix to only the required rows and columns\n## This is because we do not have data for participants <18\nsplit_cm <- function(mat, i = 1, row = 3:8, col = 3:8, ...){\n mat[[i]]$matrix[row,col]\n}\nsplit_cm_single <- function(mat, i = 1, row = 3:8, col = 3:8, ...){\n mat[row,col]\n}\n\n## Make the matrix symmetric\nsymm_mat <- function(x){\n (x + t(x))/ 2 \n}\n\n## Calculate ratio of max eigen values \n# This gives a sense of different magnitudes of the matrices\nmax_eigen_ratio <- function(x, y){\n max(eigen(x, only.values = TRUE)$values)/max(eigen(y, only.values = TRUE)$values)\n \n}\n\n\n# Take two matrices and calculate the scale factor for them\n## Repeats the above functions to get the ratio of the max eigen values\n## Of each matrix\nscale_factor <- function(mat1, mat2, ... ){\n #x1 <- split_cm(mat1, ...)\n x2 <- split_cm(mat2, ...)\n x1 <- symm_mat(mat1)\n x2 <- symm_mat(x2)\n max_eigen_ratio(x1, x2)\n}\n\n# Take a full matrix and scale it based on ratio of mat1 and mat2\nscale_matrix <- function(fullmat, mat1, mat2, i = 1, ...){\n mat1 <- mat1[[i]]$matrix\n \n fullmat[[i]]$matrix * scale_factor(mat1, mat2, i = i, ...)\n \n}\n\n## Specific for this analysis get imputed values for H2020 matrix\nimpute_values <- function(i = 1, school = FALSE, ...){\n imputed_values <- scale_matrix(\n polymod_boot_cm_home, \n h2020_boot_cm_home, \n polymod_boot_cm_home, \n i = i,\n ...\n ) +\n scale_matrix(\n polymod_boot_cm_work, \n h2020_boot_cm_work, \n polymod_boot_cm_work, \n i = i,\n ...\n ) +\n scale_matrix(\n polymod_boot_cm_other, \n h2020_boot_cm_other, \n polymod_boot_cm_other, \n i = i,\n ...\n ) \n \n if(school){\n ## Schools were closed so can not scale by this so just add\n imputed_values <- imputed_values +\n polymod_boot_cm_school[[i]]$matrix \n }\n return(imputed_values)\n \n}\n\n\nupdate_cm <- function(\n mat1, mat2, \n impute_rows = 1:2, impute_cols = 1:8, \n i = 1, \n observed_rows = 2:8, \n observed_col = 1:8,\n school = FALSE,\n ...\n){\n \n mat1 <- mat1[[i]]$matrix\n mat2 <- mat2[[i]]$matrix\n \n update_mat <- matrix(0, nrow = nrow(mat1), ncol = ncol(mat1))\n row.names(update_mat) <- colnames(mat1)\n colnames(update_mat) <- colnames(mat1)\n \n #non_imputed_values <- mat1[row, col]\n update_mat <- mat1\n \n imputed_values <- impute_values(i = i, school = school, ... )[impute_rows, impute_cols]\n update_mat[impute_rows, impute_cols] <- imputed_values\n \n symm_mat(update_mat)\n}\n\n\n### Final function which calcualte the scaling factors for R.\n\nscale_factor_R <- function(mat1, mat2, i = 1, ...){\n x1 <- update_cm(mat1, mat2, i = i, ...)\n x2 <- mat2[[i]]$matrix\n x1 <- symm_mat(x1)\n x2 <- symm_mat(x2)\n max_eigen_ratio(x1, x2)\n}\n\n\n\n\n### Repeat these for a single matrix objects. \n\n##################\n\n\n\nscale_factor_single <- function(mat1, mat2, ... ){\n x1 <- split_cm_single(mat1, ...)\n x2 <- split_cm_single(mat2, ...)\n x1 <- symm_mat(x1)\n x2 <- symm_mat(x2)\n max_eigen_ratio(x1, x2)\n}\n\n# Take a full matrix and scale it based on ratio of mat1 and mat2\nscale_matrix_single <- function(fullmat, mat1, mat2, i = 1, ...){\n mat1 <- mat1\n \n fullmat * scale_factor_single(mat1, mat2, i = i, ...)\n \n}\n\n## Specific for this analysis get imputed values for H2020 matrix\nimpute_values_single <- function(i = 1, school = FALSE, ...){\n imputed_values <- scale_matrix_single(\n polymod_cm_home, \n h2020_cm_home, \n polymod_cm_home, \n i = i,\n ...\n ) +\n scale_matrix_single(\n polymod_cm_work, \n h2020_cm_work, \n polymod_cm_work, \n i = i,\n ...\n ) +\n scale_matrix_single(\n polymod_cm_other, \n h2020_cm_other, \n polymod_cm_other, \n i = i,\n ...\n ) \n \n if(school){\n ## Schools were closed so can not scale by this so just add\n imputed_values <- imputed_values +\n polymod_cm_schoolmatrix \n }\n return(imputed_values)\n \n}", "meta": {"hexsha": "2c2c583bca95a32822a46902ccffd036ee427f94", "size": 4336, "ext": "r", "lang": "R", "max_stars_repo_path": "r/functions/matrix_scaling.r", "max_stars_repo_name": "jarvisc1/comix_covid-19-first_wave", "max_stars_repo_head_hexsha": "5cb79c5043c605f41f8d1297af17e9ba5b3ed1a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-04-08T13:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T01:12:48.000Z", "max_issues_repo_path": "r/functions/matrix_scaling.r", "max_issues_repo_name": "jarvisc1/comix_covid-19-first_wave", "max_issues_repo_head_hexsha": "5cb79c5043c605f41f8d1297af17e9ba5b3ed1a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r/functions/matrix_scaling.r", "max_forks_repo_name": "jarvisc1/comix_covid-19-first_wave", "max_forks_repo_head_hexsha": "5cb79c5043c605f41f8d1297af17e9ba5b3ed1a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-04-08T14:26:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T18:07:17.000Z", "avg_line_length": 23.8241758242, "max_line_length": 89, "alphanum_fraction": 0.6455258303, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4982189834260831}} {"text": "# Winnings/losses each game per day\r\npoker <- c(-11, 42, -49, 63, 74)\r\nroulette <- c(-19, -8, -75, 92, 39)\r\ndays <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")\r\n\r\n# Days assigned to each numerical value\r\nnames(poker) <- days\r\nnames(roulette) <- days\r\n\r\n# Calculating total winnings/losses each day\r\ntotal <- poker + roulette\r\n\r\n# Show only profitable days\r\nprofit_check <- total > 0\r\nprofitable_days <- total[profit_check]\r\n\r\n# Calculating profit/loss at end of week\r\nfinal_amount <- sum(total)\r\n\r\n# Comparing performance between games\r\ntotal_poker <- sum(poker)\r\ntotal_roulette <- sum(roulette)\r\nif (total_poker > total_roulette) {\r\n print(\"Poker is better.\")\r\n} else {\r\n print(\"Roulette is better.\")\r\n}", "meta": {"hexsha": "95abed2612fd062e65e91070c210161a518c0e4c", "size": 724, "ext": "r", "lang": "R", "max_stars_repo_path": "gambling.r", "max_stars_repo_name": "JamieVic/r-exercises", "max_stars_repo_head_hexsha": "73add495790173e3e7a39b124ff13b6cd2e462c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gambling.r", "max_issues_repo_name": "JamieVic/r-exercises", "max_issues_repo_head_hexsha": "73add495790173e3e7a39b124ff13b6cd2e462c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gambling.r", "max_forks_repo_name": "JamieVic/r-exercises", "max_forks_repo_head_hexsha": "73add495790173e3e7a39b124ff13b6cd2e462c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8148148148, "max_line_length": 66, "alphanum_fraction": 0.6781767956, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4982088106381413}} {"text": "#' Create object of class 'cover'.\n#'\n#' @param rho_1 A single numerical value between 0 and 1. Total vegetation cover, i.e. the probability of a cell to be vegetated.\n#' @param rho_11 A single numerical value between 0 and 1. Vegetation cover of pairs of vegetated cells. It defaults to \\code{rho_11 = rho_1^2}, which leads to an assumption of random clustering.\n#' @param q_11 A single numerical value between 0 and 1. Average vegetation cover of vegetated cells, i.e. the conditional probability of finding vegetated cells in the 4-cell neighborhood given that the focal cell is vegetated. It defaults to NULL which leads to an assumption of neutral clustering, i.e. \\code{q_11 == rho_1}.\n#' @param cc A single numerical value greater than 0. Clustering coefficient,\n#' describing the ratio between average local cover \\code{rho_11}, and global cover \\code{rho_1}. A value greater 1 denotes strong clustering. It defaults to NULL which leads to an assumption of neutral clustering, i.e. \\code{rho_11 == rho_1}.\n#'\n#' @return A named vector of two numerical values for the global cover of vegetation (rho_1) and the cover of vegetated pairs (rho_11).\n#' @export\n#'\n#' @examples\n#'\n#' ini_rho(0.9, cc = 1.2)\n#'\n#'\n\nini_rho <- function(rho_1, rho_11 = NULL, q_11 = NULL, cc = NULL) {\n if(is.null(rho_11[1]) & is.null(cc) & is.null(q_11)) {rho_11 <- rho_1^2}\n if(is.null(rho_11[1]) & !is.null(cc) & is.null(q_11)) {rho_11 <- cc*rho_1^2}\n if(is.null(rho_11[1]) & is.null(cc) & !is.null(q_11)) {rho_11 <- q_11*rho_1}\n rho_11[rho_11 > rho_1] <- rho_1[rho_11 > rho_1]\n\n out <- list(\n rho_1 = rho_1,\n rho_11 = rho_11#,\n #rho_10 = rho_1-rho_11,\n #rho_00 = 1-2*rho_1+rho_11,\n #rho_0 = 1-rho_1\n )\n\n if(any(unlist(out) < 0)) {\n out <- list(\n rho_1 = NA,\n rho_11 = NA#,\n #rho_10 = NA,\n #rho_00 = NA,\n #rho_0 = NA\n )\n warning(\"The value of requested clustering is not compatible with the requested total vegetation cover: please provide a lower local cover or clustering value.\")\n }\n\n class(out) <- \"cover\"\n return(out)\n}\n\n\n#' @export\ncheck_rho <- ini_rho\n", "meta": {"hexsha": "6ff63f44e65152d166be6430bb986738f0b0a5c0", "size": 2128, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ini_rho.r", "max_stars_repo_name": "fdschneider/livestock", "max_stars_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-01T02:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:59:02.000Z", "max_issues_repo_path": "R/ini_rho.r", "max_issues_repo_name": "fdschneider/livestock", "max_issues_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ini_rho.r", "max_forks_repo_name": "fdschneider/livestock", "max_forks_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.56, "max_line_length": 328, "alphanum_fraction": 0.6785714286, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.49709042091083294}} {"text": "################################################################################\n#\n# Script that presents and tests a function that performs an LRT to two\n# models that are fitted to datasets generated by multiple imputation\n# and provides a test statistic per Meng and Rubin (1992)\n#\n# The parallel version will not work on Windows machines because of the use of\n# Unix-alike specific parallel code.\n#\n# Andrew Robinson 15-April-2015\n#\n################################################################################\n\nlibrary(lme4) # For mixed-effects models\n\nlibrary(Amelia) # For imputation\n\nlibrary(equivalence) # For data that I know\n\nlibrary(parallel) # Speed things up\n\nlibrary(compiler) # A different speed-up\n\ndata(ufc)\n\nstr(ufc)\n\nufc <- subset(ufc, !is.na(Dbh))\nufc$Species[ufc$Species %in% c(\"F\",\"FG\")] <- \"GF\"\nufc$Species <- factor(ufc$Species)\nufc$ht.measured <- is.na(ufc$Height)\n\nufc <- subset(ufc,\n Species %in% names(sort(-table(Species)))[1:6],\n select = c(\"ht.measured\",\"Plot\",\"Dbh.in\",\"Species\"))\n\n## Fit a pair of models to compare using LRT\n\nufc.whole <- ufc\n\nisna.1.w <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc.whole, family = binomial)\nisna.0.w <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc.whole, family = binomial)\n\nanova(isna.0.w, isna.1.w)\n\n## Make some data missing - 5% each of Dbh, Species, and the response.\n\nmake.missing <- sample(1:nrow(ufc), size = 90, replace = FALSE)\n\nis.na(ufc$Species[make.missing[1:30]]) <- TRUE\nis.na(ufc$Dbh.in[make.missing[31:60]]) <- TRUE\nis.na(ufc$ht.measured[make.missing[61:90]]) <- TRUE\n\n## Impute datasets using Amelia\n\nufc.imputes <- amelia(ufc,\n m = 5,\n cs = \"Plot\",\n noms = \"Species\")\n\nnames(ufc.imputes)\n\nstr(ufc.imputes$imputations)\n\n## Fit models to each instance\n\nufc.models <- mclapply(ufc.imputes$imputations,\n function (dataset) {\n glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = dataset, family = binomial)\n },\n mc.cores = 4)\n\n## Obtain average model parameters\n\nufc.par.hat <-\n do.call(rbind, lapply(ufc.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n }))\n\nufc.par.hat <- colMeans(ufc.par.hat)\n\n## Create deviance functions for each imputation\n\nufc.dev.funs <- mclapply(ufc.imputes$imputations,\n function (dataset) {\n glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = dataset, family = binomial,\n devFunOnly = TRUE)\n },\n mc.cores = 4)\n\n## Evaluate the deviance for each refitted model at these estimates\n\n(ufc.dev <- sapply(ufc.dev.funs, function(devfun) devfun(ufc.par.hat)))\n\n################################################################################\n\n### Ok, now develop an LRT function using these pieces.\n\nimputeLRT.p <- function(h0, h1, imputed.data.list, mc.cores = 4) {\n m <- length(imputed.data.list)\n h0.models <- mclapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset)\n },\n mc.cores = mc.cores)\n h0.dev.funs <- mclapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset,\n devFunOnly = TRUE)\n },\n mc.cores = mc.cores)\n Q.bar.0 <-\n colMeans(do.call(rbind,\n lapply(h0.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n h1.models <- mclapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset)\n },\n mc.cores = mc.cores)\n h1.dev.funs <- mclapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset,\n devFunOnly = TRUE)\n },\n mc.cores = mc.cores)\n Q.bar.1 <-\n colMeans(do.call(rbind,\n lapply(h1.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n d.prime.m.bar <- mean(unlist(mclapply(1:m,\n function(i) {\n anova(h0.models[[i]],\n h1.models[[i]])$Chisq[2]\n },\n mc.cores = mc.cores)))\n d.L.bar <- mean(unlist(mclapply(1:m,\n function(i) {\n h0.dev.funs[[i]](Q.bar.0) -\n h1.dev.funs[[i]](Q.bar.1)\n },\n mc.cores = mc.cores)))\n p0 <- length(Q.bar.0)\n p1 <- length(Q.bar.1)\n k <- p1 - p0\n rL <- (m + 1) / ((m - 1) * k) * (d.prime.m.bar - d.L.bar) # 3.8\n D.L <- d.L.bar / ((1 + rL) * k) # 3.7\n v <- k * (m - 1)\n w <- ifelse(v > 4, # 2.7\n 4 + (v - 4) * (1 + (1 - v/2) / rL)^2,\n v / 2 * (1 + 1/k) * (1 + 1/rL)^2)\n Pval <- 1 - pf(D.L, k, w)\n return(list(\n D.L = D.L,\n Pval = Pval,\n rL = rL,\n d.L.bar = d.L.bar,\n d.prime.m.bar = d.prime.m.bar,\n Q.bar.0 = Q.bar.0,\n Q.bar.1 = Q.bar.1,\n k = k,\n w = w,\n p0 = p0,\n p1 = p1,\n m = m))\n}\n\n\n## Here's a test\n\nisna.1 <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc, family = binomial)\nisna.0 <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc, family = binomial)\n\nimputeLRT.p(isna.0, isna.1,\n list(ufc.whole, ufc.whole, ufc.whole, ufc.whole, ufc.whole))\n\n## P-value should be comparable to\n\nanova(isna.0.w, isna.1.w)\n\n## Now apply to missing data cases\n\nufc.imputes.V <- amelia(ufc,\n m = 5,\n cs = \"Plot\",\n noms = \"Species\")\n\nimputeLRT.p(isna.0, isna.1, ufc.imputes.V$imputations)\n\n\n\nufc.imputes.X <- amelia(ufc,\n m = 10,\n cs = \"Plot\",\n noms = \"Species\")\n\nimputeLRT.p(isna.0, isna.1, ufc.imputes.X$imputations)\n\n\n\nufc.imputes.XX <- amelia(ufc,\n m = 20,\n cs = \"Plot\",\n noms = \"Species\")\n\nimputeLRT.p(isna.0, isna.1, ufc.imputes.XX$imputations)\n\n\n\nufc.imputes.L <- amelia(ufc,\n m = 50,\n cs = \"Plot\",\n noms = \"Species\")\n\nimputeLRT.p(isna.0, isna.1, ufc.imputes.L$imputations)\n\n\n## A version that should work more broadly\n\nimputeLRT <- function(h0, h1, imputed.data.list) {\n m <- length(imputed.data.list)\n h0.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset)\n })\n h0.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.0 <-\n colMeans(do.call(rbind,\n lapply(h0.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n h1.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset)\n })\n h1.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.1 <-\n colMeans(do.call(rbind,\n lapply(h1.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n d.prime.m.bar <- mean(unlist(lapply(1:m,\n function(i) {\n anova(h0.models[[i]],\n h1.models[[i]])$Chisq[2]\n })))\n d.L.bar <- mean(unlist(lapply(1:m,\n function(i) {\n h0.dev.funs[[i]](Q.bar.0) -\n h1.dev.funs[[i]](Q.bar.1)\n })))\n p0 <- length(Q.bar.0)\n p1 <- length(Q.bar.1)\n k <- p1 - p0\n rL <- (m + 1) / ((m - 1) * k) * (d.prime.m.bar - d.L.bar) # 3.8\n D.L <- d.L.bar / ((1 + rL) * k) # 3.7\n v <- k * (m - 1)\n w <- ifelse(v > 4, # 2.7\n 4 + (v - 4) * (1 + (1 - v/2) / rL)^2,\n v / 2 * (1 + 1/k) * (1 + 1/rL)^2)\n Pval <- 1 - pf(D.L, k, w)\n return(list(\n D.L = D.L,\n Pval = Pval,\n rL = rL,\n d.L.bar = d.L.bar,\n d.prime.m.bar = d.prime.m.bar,\n Q.bar.0 = Q.bar.0,\n Q.bar.1 = Q.bar.1,\n k = k,\n w = w,\n p0 = p0,\n p1 = p1,\n m = m))\n}\n\nimputeLRT(isna.0, isna.1,\n list(ufc.whole, ufc.whole, ufc.whole, ufc.whole, ufc.whole))\n\nimputeLRT(isna.0, isna.1, ufc.imputes.X$imputations)\n\n\n\n\nimputeLRT.pw <- function(h0, h1, imputed.data.list, mc.cores = 4) {\n# browser()\n my.cluster <- makeCluster(mc.cores)\n clusterExport(my.cluster,\n c(\"h0\",\"h1\",\"imputed.data.list\"),\n environment())\n m <- length(imputed.data.list)\n h0.models <- clusterApplyLB(my.cluster,\n imputed.data.list,\n function (dataset) {\n require(lme4)\n update(h0, data = dataset)\n })\n h0.dev.funs <- clusterApplyLB(my.cluster,\n imputed.data.list,\n function (dataset) {\n update(h0, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.0 <-\n colMeans(do.call(rbind,\n lapply(h0.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n h1.models <- clusterApplyLB(my.cluster,\n imputed.data.list,\n function (dataset) {\n update(h1, data = dataset)\n })\n h1.dev.funs <- clusterApplyLB(my.cluster,\n imputed.data.list,\n function (dataset) {\n update(h1, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.1 <-\n colMeans(do.call(rbind,\n lapply(h1.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n d.prime.m.bar <- mean(unlist(clusterApplyLB(my.cluster,\n 1:m,\n function(i) {\n anova(h0.models[[i]],\n h1.models[[i]])$Chisq[2]\n })))\n d.L.bar <- mean(unlist(clusterApplyLB(my.cluster,\n 1:m,\n function(i) {\n h0.dev.funs[[i]](Q.bar.0) -\n h1.dev.funs[[i]](Q.bar.1)\n })))\n stopCluster(my.cluster)\n p0 <- length(Q.bar.0)\n p1 <- length(Q.bar.1)\n k <- p1 - p0\n rL <- (m + 1) / ((m - 1) * k) * (d.prime.m.bar - d.L.bar) # 3.8\n D.L <- d.L.bar / ((1 + rL) * k) # 3.7\n v <- k * (m - 1)\n w <- ifelse(v > 4, # 2.7\n 4 + (v - 4) * (1 + (1 - v/2) / rL)^2,\n v / 2 * (1 + 1/k) * (1 + 1/rL)^2)\n Pval <- 1 - pf(D.L, k, w)\n return(list(\n D.L = D.L,\n Pval = Pval,\n rL = rL,\n d.L.bar = d.L.bar,\n d.prime.m.bar = d.prime.m.bar,\n Q.bar.0 = Q.bar.0,\n Q.bar.1 = Q.bar.1,\n k = k,\n w = w,\n p0 = p0,\n p1 = p1,\n m = m))\n}\n\nimputeLRT.pw(isna.0, isna.1,\n list(ufc.whole, ufc.whole, ufc.whole, ufc.whole, ufc.whole))\n\nimputeLRT.pw(isna.0, isna.1, ufc.imputes.X$imputations)\n\n########\n\n## Timing test\n\nsystem.time(imputeLRT(isna.0, isna.1, ufc.imputes.XX$imputations))\n\nsystem.time(imputeLRT.p(isna.0, isna.1, ufc.imputes.XX$imputations))\n\n# system.time(imputeLRT.pw(isna.0, isna.1, ufc.imputes.XX$imputations))\n\nimputeLRT.c <- cmpfun(imputeLRT)\n\nsystem.time(imputeLRT.c(isna.0, isna.1, ufc.imputes.XX$imputations))\n\n", "meta": {"hexsha": "051f323b0df31024165c516e242651b8022f9ff5", "size": 13739, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/mi_mlm.r", "max_stars_repo_name": "SteveLane/blistering-barnacles", "max_stars_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/mi_mlm.r", "max_issues_repo_name": "SteveLane/blistering-barnacles", "max_issues_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-09-12T05:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T22:37:45.000Z", "max_forks_repo_path": "scripts/mi_mlm.r", "max_forks_repo_name": "SteveLane/blistering-barnacles", "max_forks_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-08-28T04:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T04:09:34.000Z", "avg_line_length": 33.9234567901, "max_line_length": 82, "alphanum_fraction": 0.4022126792, "num_tokens": 3520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4970492286700649}} {"text": "## Berechnung der Bachelor-Gesamtnote\n# Setting up virtual environment\nprint(\"Starting R virtual environment...\")\nprint(\"Executing script!\")\noptions(digits=3)\n\n# Input einlesen\ncurrent_gpa <- readline(prompt=\"Derzeitiger gesamt-GPA: \")\ncurrent_gpa <-gsub(\",\", \".\", current_gpa)\ncurrent_gpa <- as.numeric(current_gpa)\nprint(\"Eingabe der Berechnungsgrundlage in CP\")\nprint(\"ACHTUNG! Wenn die finale Note berechnet werden soll, mit der Standardanzahl der CP bei Beendigung rechnen\")\nprint(\"Normalerweise 180 CP - Bachelorthesis CP\")\nbase_cp <- readline(prompt=\"Berechnungsgrundlage in CP: \")\nbase_cp <- as.numeric(base_cp)\ncurrent_ba <- readline(prompt=\"(Voraussichtliche) Bachelor-Thesis-Note: \")\ncurrent_ba <-gsub(\",\", \".\", current_ba)\ncurrent_ba <- as.numeric(current_ba)\nbase_bacp <- readline(prompt=\"CP für Thesis: \")\nbase_bacp <- as.numeric(base_bacp)\n\n# Berechnung der Noten\nweighted_grade_sum <- current_gpa * base_cp\nprint(paste0(\"Summe der gewichteten Noten: \", weighted_grade_sum), quote = FALSE)\nprint(paste0(\"Summe der zur Berechnung verwendeten CP: \", base_cp), quote = FALSE)\nweighted_grade <- weighted_grade_sum / base_cp\nprint(paste0(\"Gewichtete Modulnote: \", weighted_grade_sum), quote = FALSE)\n\nweighted_ba_grade_sum <- current_ba * base_bacp\nfull_cp <- base_cp + base_bacp\nprint(paste0(\"Bachelornote: \", current_ba), quote = FALSE)\nprint(paste0(\"Bachelor-CP: \", base_bacp), quote = FALSE)\nprint(paste0(\"Gewichtete Bachelornote: \", weighted_ba_grade_sum), quote = FALSE)\n\nweighted_full_grade <- weighted_ba_grade_sum + weighted_grade_sum\nfinal_grade <- weighted_full_grade / full_cp\nprint(paste0(\"Gewichtete Gesamtnote: \", weighted_full_grade), quote = FALSE)\nprint(paste0(\"Gesamte CP: \", full_cp), quote = FALSE)\nprint(\"\", quote = FALSE)\nprint(paste0(\"Voraussichtliche finale Note: \", round(final_grade, digits = 3)), quote = FALSE)\n\n", "meta": {"hexsha": "e390b2d06661e14e7729d180a184bbafb9c4aef9", "size": 1851, "ext": "r", "lang": "R", "max_stars_repo_path": "R_Berechnung_Bachelornote.r", "max_stars_repo_name": "ephidrineon/Bachelornote", "max_stars_repo_head_hexsha": "2223c2a1edfcccb9daa8b8693d7784ac16df875c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R_Berechnung_Bachelornote.r", "max_issues_repo_name": "ephidrineon/Bachelornote", "max_issues_repo_head_hexsha": "2223c2a1edfcccb9daa8b8693d7784ac16df875c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R_Berechnung_Bachelornote.r", "max_forks_repo_name": "ephidrineon/Bachelornote", "max_forks_repo_head_hexsha": "2223c2a1edfcccb9daa8b8693d7784ac16df875c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0714285714, "max_line_length": 114, "alphanum_fraction": 0.7633711507, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4970224151793786}} {"text": "\n# S1; S2; X; r; metric = \"rec\"; method = \"supt\"; type = \"band\"; plus = T; alpha = .05; h = NULL; mc.rep = 100000\n\n#' Perform a hypothesis test for the difference between two performance curves.\n#' \n#' \\code{PerfCurveTest} takes score vectors for two scoring algorithms and an activity vector.\n#' A performance curve is created for the two scoring algorithms and hypothesis tests are performed\n#' at the selected testing fractions. \n#' \n#' @param S1 a vector of scores for scoring algorithm 1.\n#' @param S2 a vector of scores for scoring algorithm 2.\n#' @param X a vector of activities.\n#' @param r a vector of testing fractions.\n#' @param metric the performance curve to use. Options are recall (\"rec\") and precision (\"prec\").\n#' @param method the method to use. Recall options are \n#' c(\"EmProc\", \"binomial\", \"JZ ind\", \"mcnemar\", \"binomial ind\"). Precision options are\n#' c(\"EmProc\", \"binomial\", \"JZ ind\", \"stouffer\", \"binomial ind\").\n#' @param plus should plus correction be used or not?\n#' @param alpha the significance level.\n#' \n#' @export\nPerfCurveTest <- function(S1, S2, X, r, metric = \"rec\", type = \"pointwise\", method = \"EmProc\",\n plus = T, alpha = .05, h = NULL, seed = 111, mc.rep = 100000){\n \n set.seed(seed)\n m <- length(S1) #total sample size\n r.all <- (1:m)/m\n idx <- which(r.all %in% r)\n \n # Convert fractions in r to thresholds, for both sets of scores\n # Also accumulate the number of actives, for each score and jointly\n F1cdf <- ecdf(S1); yyobs <- sort(unique(S1))\n F1inv <- stepfun(x = F1cdf(yyobs), y = c(yyobs, max(yyobs)), right=TRUE, f=1)\n F2cdf <- ecdf(S2); yyobs <- sort(unique(S2))\n F2inv <- stepfun(x = F2cdf(yyobs), y = c(yyobs, max(yyobs)), right=TRUE, f=1)\n hits1 <- hits2 <- hits12 <- ntest12 <- vector(length = length(r))\n for(i in 1:length(r)) {\n t1 <- F1inv(1-r[i])\n t2 <- F2inv(1-r[i])\n hits1[i] <- sum(X*(S1 > t1))\n hits2[i] <- sum(X*(S2 > t2))\n hits12[i] <- sum(X*(S1 > t1 & S2 > t2))\n ntest12[i] <- sum(S1 > t1 & S2 > t2)\n }\n nact <- sum(X) #total number of actives\n ntest <- (m*r) #number of compounds tested\n \n # Uncorrected parameters\n r <- ntest/m\n pi.0 <- nact/m\n k1 <- (hits1)/nact\n k2 <- (hits2)/nact\n k12 <- (hits12)/nact\n pi1 <- pi.0/r*k1\n pi2 <- pi.0/r*k2\n r12 <- ntest12/m\n pi12 <- hits12/ntest12\n pi12 <- ifelse(is.na(pi12), 0, pi12)\n # pooled estimates\n pi <- (pi1 + pi2)/2\n k <- (k1 + k2)/2\n \n if(plus) {\n hits1.c <- hits1 + 1\n hits2.c <- hits2 + 1\n nact.c <- nact + 2 \n ntest.c <- ntest + 1\n m.c <- m + 2\n } else {\n hits1.c <- hits1\n hits2.c <- hits2\n nact.c <- nact \n ntest.c <- ntest\n m.c <- m\n }\n \n # Corrected parameters\n r.c <- ntest.c/m.c\n pi.0.c <- nact.c/m.c\n k1.c <- (hits1.c)/nact.c\n k2.c <- (hits2.c)/nact.c\n k12.c <- (hits12)/nact.c\n pi1.c <- (hits1.c)/(ntest.c)\n pi2.c <- (hits2.c)/(ntest.c)\n r12.c <- ntest12/m.c\n pi12.c <- hits12/ntest12\n pi12.c <- ifelse(is.na(pi12.c), 0, pi12.c)\n \n \n Lam1.vec <- vector(length = length(k1))\n Lam2.vec <- vector(length = length(k1))\n for(j in seq_along(k1)){\n Lam1.vec[j] <- EstLambda(S1, X, t = F1inv(1-r[j]), idx = idx[j], h)\n Lam2.vec[j] <- EstLambda(S2, X, t = F2inv(1-r[j]), idx = idx[j], h)\n }\n \n CI.int <- matrix(ncol = 2, nrow = length(k1))\n se.p <- se.np <- p.val <- vector(length = length(k1))\n if(metric == \"rec\") {\n if(type == \"pointwise\") {\n quant <- qnorm(1-alpha/2)\n \n if(method %in% c(\"JZ ind\", \"EmProc\")){\n for(j in seq_along(k1)) {\n Lam1 <- Lam1.vec[j]\n Lam2 <- Lam2.vec[j]\n \n # unpooled variances\n var1.k.np <- ((k1.c[j]*(1-k1.c[j]))/(m.c*pi.0.c))*(1-2*Lam1) +\n (Lam1^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n # Check to see if var.k.np is negative due to m.cachine precision problem.c\n var1.k.np <- ifelse(var1.k.np < 0, 0, var1.k.np)\n var2.k.np <- ((k2.c[j]*(1-k2.c[j]))/(m.c*pi.0.c))*(1-2*Lam2) +\n (Lam2^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n var2.k.np <- ifelse(var2.k.np < 0, 0, var2.k.np)\n cov.k.np <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.c[j]-k1.c[j]*k2.c[j])*(1-Lam1-Lam2) +\n (r12.c[j]-r.c[j]^2)*Lam1*Lam2)\n \n # pooled variances \n var1.k.p <- ((k[j]*(1-k[j]))/(m*pi.0))*(1-2*Lam1) +\n (Lam1^2*(1-r[j])*r[j])/(m*pi.0^2)\n var1.k.p <- ifelse(var1.k.p < 0, 0, var1.k.p)\n var2.k.p <- ((k[j]*(1-k[j]))/(m*pi.0))*(1-2*Lam2) +\n (Lam2^2*(1-r[j])*r[j])/(m*pi.0^2)\n var2.k.p <- ifelse(var2.k.p < 0, 0, var2.k.p)\n cov.k.p <- (m^-1*pi.0^-2)*(pi.0*(k12[j]-k[j]*k[j])*(1-Lam1-Lam2) +\n (r12[j]-r[j]^2)*Lam1*Lam2)\n \n if(method == \"JZ ind\"){\n # assuming independence of k\n var.k.p <- var1.k.p + var2.k.p\n var.k.np <- var1.k.np + var2.k.np\n } else if(method == \"EmProc\") {\n var.k.p <- var1.k.p + var2.k.p - 2*cov.k.p\n var.k.np <- var1.k.np + var2.k.np - 2*cov.k.np\n }\n var.k.p <- ifelse(var.k.p < 0, 0, var.k.p)\n var.k.np <- ifelse(var.k.np < 0, 0, var.k.np)\n se.p[j] <- sqrt(var.k.p)\n se.np[j] <- sqrt(var.k.np)\n \n # Use pooled variance for tests, and unpooled for CIs\n CI.int[j, ] <- c( (k1[j]-k2[j]) - quant*se.np[j],\n (k1[j]-k2[j]) + quant*se.np[j])\n zscore <- ( (k1[j]-k2[j]) )/se.p[j]\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method %in% c(\"binomial ind\", \"binomial\")) {\n for(j in seq_along(k1.c)) {\n \n # unpooled variances\n var1.k.np <- (m.c*pi.0.c)^-1*(k1.c[j])*(1-k1.c[j])\n var2.k.np <- (m.c*pi.0.c)^-1*(k2.c[j])*(1-k2.c[j])\n cov.k.np <- (m.c*pi.0.c)^-1*(k12.c[j] - k1.c[j]*k2.c[j])\n \n # pooled variances\n var1.k.p <- (m*pi.0)^-1*(k[j])*(1-k[j])\n var2.k.p <- (m*pi.0)^-1*(k[j])*(1-k[j])\n cov.k.p <- (m*pi.0)^-1*(k12[j] - k[j]*k[j])\n \n if(method == \"binomial\") {\n var.k.p <- var1.k.p + var2.k.p - 2*cov.k.p\n var.k.np <- var1.k.np + var2.k.np - 2*cov.k.np\n } else if(method == \"binomial ind\") {\n var.k.p <- var1.k.p + var2.k.p\n var.k.np <- var1.k.np + var2.k.np\n }\n var.k.p <- ifelse(var.k.p < 0, 0, var.k.p)\n var.k.np <- ifelse(var.k.np < 0, 0, var.k.np)\n se.p[j] <- sqrt(var.k.p)\n se.np[j] <- sqrt(var.k.np)\n CI.int[j, ] <- c( (k1[j]-k2[j]) - quant*se.np[j],\n (k1[j]-k2[j]) + quant*se.np[j])\n zscore <- ( (k1[j]-k2[j]) )/se.p[j]\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n } \n } else if(method == \"mcnemar\") {\n for(j in seq_along(k1.c)) {\n BminusC <- hits1[j] - hits2[j]\n BplusC <- hits1[j] + hits2[j] - 2*hits12[j]\n BminusC.c <- hits1.c[j] - hits2.c[j]\n BplusC.c <- hits1.c[j] + hits2.c[j] - 2*hits12[j]\n zscore <- ifelse(BplusC>0, BminusC/sqrt(BplusC), 0)\n p.val[j] <- 2*pnorm(-abs(zscore))\n se.np[j] <- sqrt(BplusC.c - BminusC.c^2/nact.c) / nact.c\n # TODO use the actual difference as the center point for the CI?\n # No, use actual BP corrected McNemar for a fair comparison\n CI.int[j,] <- c( BminusC.c/nact.c - quant*se.np[j], BminusC.c/nact.c + quant*se.np[j])\n }\n }\n } else if (type == \"band\") {\n if(method == \"sup-t\") {\n cor.C <- matrix(NA, ncol = length(k1), nrow = length(k1))\n for(f in seq_along(k1)) {\n for(e in 1:f) {\n \n # Alg 1 unpooled variance\n Lam11 <- Lam1.vec[e]; Lam21 <- Lam2.vec[e];\n var1.k.r1 <- ((k1.c[e]*(1-k1.c[e]))/(m.c*pi.0.c))*(1-2*Lam11) +\n (Lam11^2*(1-r.c[e])*r.c[e])/(m.c*pi.0.c^2)\n var1.k.r1 <- ifelse(var1.k.r1 < 0, 0, var1.k.r1)\n var2.k.r1 <- ((k2.c[e]*(1-k2.c[e]))/(m.c*pi.0.c))*(1-2*Lam21) +\n (Lam21^2*(1-r.c[e])*r.c[e])/(m.c*pi.0.c^2)\n var2.k.r1 <- ifelse(var2.k.r1 < 0, 0, var2.k.r1)\n cov.k.r1 <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.c[e]-k1.c[e]*k2.c[e])*(1-Lam11-Lam21) +\n (r12.c[e]-r.c[e]^2)*Lam11*Lam21)\n var.difk.r1 <- var1.k.r1 + var2.k.r1 - 2*cov.k.r1\n \n # Alg 2 unpooled variances\n Lam12 <- Lam1.vec[f]; Lam22 <- Lam2.vec[f];\n var1.k.r2 <- ((k1.c[f]*(1-k1.c[f]))/(m.c*pi.0.c))*(1-2*Lam12) +\n (Lam12^2*(1-r.c[f])*r.c[f])/(m.c*pi.0.c^2)\n var1.k.r2 <- ifelse(var1.k.r2 < 0, 0, var1.k.r2)\n var2.k.r2 <- ((k2.c[f]*(1-k2.c[f]))/(m.c*pi.0.c))*(1-2*Lam22) +\n (Lam22^2*(1-r.c[f])*r.c[f])/(m.c*pi.0.c^2)\n var2.k.r2 <- ifelse(var2.k.r2 < 0, 0, var2.k.r2)\n cov.k.r2 <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.c[f]-k1.c[f]*k2.c[f])*(1-Lam12-Lam22) +\n (r12.c[f]-r.c[f]^2)*Lam12*Lam22)\n var.difk.r2 <- var1.k.r2 + var2.k.r2 - 2*cov.k.r2\n \n # Covariance\n cov.k11.k12 <- ((m.c^-1*pi.0.c^-2)*(pi.0.c*(k1.c[e]-k1.c[e]*k1.c[f])*(1-Lam11-Lam12) +\n (r.c[e]-r.c[e]*r.c[f])*Lam11*Lam12))\n cov.k21.k22 <- ((m.c^-1*pi.0.c^-2)*(pi.0.c*(k2.c[e]-k2.c[e]*k2.c[f])*(1-Lam21-Lam22) +\n (r.c[e]-r.c[e]*r.c[f])*Lam21*Lam22))\n \n t1 <- F1inv(1-r[e])\n t2 <- F2inv(1-r[f])\n hits11.22 <- sum(X*(S1 > t1 & S2 > t2))\n ntest11.22 <- sum(S1 > t1 & S2 > t2)\n k11.22.c <- (hits11.22)/nact.c\n r11.22.c <- ntest11.22/m.c\n \n cov.k11.k22 <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k11.22.c-k1.c[e]*k2.c[f])*(1-Lam11-Lam22) +\n (r11.22.c-r.c[e]*r.c[f])*Lam11*Lam22)\n \n t1 <- F1inv(1-r[f])\n t2 <- F2inv(1-r[e])\n hits12.21 <- sum(X*(S1 > t1 & S2 > t2))\n ntest12.21 <- sum(S1 > t1 & S2 > t2)\n k12.21.c <- (hits12.21)/nact.c\n r12.21.c <- ntest12.21/m.c\n \n cov.k12.k21 <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.21.c-k1.c[f]*k2.c[e])*(1-Lam21-Lam12) +\n (r12.21.c-r.c[f]*r.c[e])*Lam21*Lam12)\n \n cov.difk <- cov.k11.k12 + cov.k21.k22 - cov.k11.k22 - cov.k12.k21\n \n if(e == f) {\n # If the covariance serves as a variance then it cant be non-negative\n # otherwise, it can be negative\n cov.difk <- ifelse(cov.difk < 0, 0, cov.difk)\n }\n cor.difk <- cov.difk/(sqrt(var.difk.r1)*sqrt(var.difk.r2))\n cor.difk <- ifelse(var.difk.r1 == 0 | var.difk.r2 == 0, ifelse(e == f, 1, 0), cor.difk)\n cor.C[e, f] <- cor.difk\n cor.C[f, e] <- cor.difk\n }\n }\n mc.samples <- MASS::mvrnorm(n = mc.rep, rep(0, length = length(k)), cor.C, tol = 1)\n max.q <- vector(length = mc.rep)\n for(j in 1:mc.rep) {\n max.q[j] <- max(abs(mc.samples[j, ]))\n }\n # This should be divided by two because standard normal dist and not the chi-square\n # in Montiel Olea and Plagborg-Møller\n quant <- quantile(max.q, probs = 1-alpha/2)\n } else if(method == \"theta-proj\") {\n quant <- sqrt(qchisq(1-alpha, length(k1)))\n } else if(method == \"bonf\") {\n quant <- qnorm(1-alpha/(2*length(k1)))\n }\n for(j in seq_along(k)) {\n Lam1 <- Lam1.vec[j]\n Lam2 <- Lam2.vec[j]\n \n print(quant)\n # unpooled variances\n var1.k.np <- ((k1.c[j]*(1-k1.c[j]))/(m.c*pi.0.c))*(1-2*Lam1) +\n (Lam1^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n # Check to see if var.k.np is negative due to machine precision problem\n var1.k.np <- ifelse(var1.k.np < 0, 0, var1.k.np)\n var2.k.np <- ((k2.c[j]*(1-k2.c[j]))/(m.c*pi.0.c))*(1-2*Lam2) +\n (Lam2^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n var2.k.np <- ifelse(var2.k.np < 0, 0, var2.k.np)\n cov.k.np <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.c[j]-k1.c[j]*k2.c[j])*(1-Lam1-Lam2) +\n (r12.c[j]-r.c[j]^2)*Lam1*Lam2)\n var.k.np <- var1.k.np + var2.k.np - 2*cov.k.np\n var.k.np <- ifelse(var.k.np < 0, 0, var.k.np)\n se.np[j] <- sqrt(var.k.np)\n CI.int[j, ] <- c( (k1[j]-k2[j]) - quant*se.np[j],\n (k1[j]-k2[j]) + quant*se.np[j])\n p.val[j] <- NA\n }\n }\n # difference estimates\n est <- (k1 - k2)\n } else if(metric == \"prec\") {\n # TODO implement pooled and unpooled variances here\n if(method %in% c(\"JZ ind\", \"EmProc\")) {\n for(j in seq_along(pi1.c)) {\n Lam1 <- Lam1.vec[j]\n var1.pi <- (pi1.c[j]*(1-pi1.c[j]))/(m*r[j]) + (1-r[j])*(pi1.c[j]-Lam1)^2/(m*r[j])\n var1.pi <- ifelse(var1.pi < 0, 0, var1.pi)\n Lam2 <- Lam2.vec[j]\n var2.pi <- (pi2.c[j]*(1-pi2.c[j]))/(m*r[j]) + (1-r[j])*(pi2.c[j]-Lam2)^2/(m*r[j])\n var2.pi <- ifelse(var2.pi < 0, 0, var2.pi)\n cov.pi <- ((m^-1*r[j]^-2))*(r12[j]*pi12.c[j]*(1 - pi12.c[j]) + \n (pi12.c[j]-Lam1)*(pi12.c[j]-Lam2)*(r12[j] - r[j]^2))\n \n if(method == \"JZ ind\") {\n var.pi <- var1.pi + var2.pi\n } else if(method == \"EmProc\") {\n var.pi <- var1.pi + var2.pi - 2*cov.pi\n }\n \n # Check to see if var.k is negative due to machine precision problem\n var.pi <- ifelse(var.pi < 0, 0, var.pi)\n se <- sqrt(var.pi)\n CI.int[j, ] <- cbind((pi1[j] - pi2[j]) - quant*se, (pi1[j] - pi2[j]) + quant*se)\n zscore <- (pi1[j] - pi2[j])/se\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method %in% c(\"binomial ind\", \"binomial\")) {\n for(j in seq_along(k1.c)) {\n var1.pi <- (pi.c[j]*(1-pi.c[j]))/(m*r[j])\n var2.pi <- (pi.c[j]*(1-pi.c[j]))/(m*r[j])\n cov.pi <- (r12[j]/(m*r[j]^2))*(pi12.c[j]*(1 - pi12.c[j]))\n \n if(method == \"binomial\") {\n var.pi <- var1.pi + var1.pi - 2*cov.pi\n } else if(method == \"binomial ind\") {\n var.pi <- var1.pi + var1.pi\n }\n \n # Check to see if var.k is negative due to machine precision problem\n var.pi <- ifelse(var.pi < 0, 0, var.pi)\n se <- sqrt(var.pi)\n CI.int[j, ] <- cbind((pi1.c[j] - pi2.c[j]) - quant*se, (pi1.c[j] - pi2.c[j]) + quant*se)\n zscore <- (pi1.c[j] - pi2.c[j])/se\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method == \"stouffer\") {\n # TODO check that stouffer implemented correctly after changes\n for(j in seq_along(pi1.c)) {\n Sorder1 <- order(S1,decreasing=TRUE)\n Sorder2 <- order(S2,decreasing=TRUE)\n overlap.idx <- Sorder1[which(Sorder1[1:idx[j]] %in% Sorder2[1:idx[j]])]\n S1.unique.idx <- Sorder1[which(!Sorder1[1:idx[j]] %in% Sorder2[1:idx[j]])]\n S2.unique.idx <- Sorder2[which(!Sorder2[1:idx[j]] %in% Sorder1[1:idx[j]])]\n n12 <- length(overlap.idx)\n a <- sum(X[overlap.idx])\n d <- n12 - a\n n1 <- m*r[j] - n12 \n e <- sum(X[S1.unique.idx])\n g <- sum(X[S2.unique.idx])\n p.1 <- e/n1\n p.2 <- g/n1\n p.bar <- (e + g)/(2*n1)\n if(correction == \"plus\") {\n n1 <- n1 + 4\n e <- e + 2\n g <- g + 2\n }\n z1 <- (p.1 - p.2)/sqrt((2*p.bar*(1-p.bar))/n1)\n z1 <- ifelse(is.na(z1), 0, z1)\n z3 <- 0\n w <- (n1 + n1)/(2*n12 + n1 + n1)\n z5 <- (w*z1 + (1-w)*z3)/(sqrt(w^2 + (1-w)^2))\n p.val[j] <- 2*(1 - pnorm(abs(z5)))\n }\n }\n # difference estimates\n est <- pi1 - pi2\n }\n list(diff_estimate = est, std_err = se.np, ci_interval = CI.int, p_value = p.val)\n}", "meta": {"hexsha": "ca24a56b7296df42fab137e7b02c1ace60deca02", "size": 16264, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation_files/difference_bands/hypothesis_test_new.r", "max_stars_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_stars_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation_files/difference_bands/hypothesis_test_new.r", "max_issues_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_issues_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_files/difference_bands/hypothesis_test_new.r", "max_forks_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_forks_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.687664042, "max_line_length": 112, "alphanum_fraction": 0.4655066404, "num_tokens": 5942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49702240036617956}} {"text": "#' Estimating the isodensity (ISO) environmental contours\r\n#'\r\n#' @description\r\n#' This function estimates the isodensity (ISO) environmental contours for a fitted joint distribution of\r\n#' class \\code{ht} or \\code{wln}.\r\n#' \r\n#' @param object the fitted joint distribution object as generated by function \\code{\\link{fit_ht}}\r\n#' or \\code{\\link{fit_wln}}. See details.\r\n#' \r\n#' @param output_rp the required return periods (in years) for the estimated contours.\r\n#' \r\n#' @param n_point the number of points to output around each contour. The default value is 100.\r\n#' \r\n#' @details\r\n#' The estimated isodensity contour for is a set of points with constant joint\r\n#' probability density, equal to that at the anchor point. The anchor point for the \\eqn{T}-year contour\r\n#' is the \\eqn{K}-year return level on wave height \\code{hs}, and the conditional median of\r\n#' the wave period \\code{tp}. See the guidance by DNV-GL section 3.7.2.\r\n#' \r\n#' Due to the challenge of the non-parametric estimation of a joint denisty, the current version only\r\n#' supports joint probability density estimation based on\r\n#' the parametric form of the Weibull-log-normal model or the parametric part of the Heffernan-Tawn\r\n#' model. The residual distribution in the Heffernan-Tawn is approximted by a normal\r\n#' distribution, rather than estimated using the kernel density.\r\n#' \r\n#' For this same reason, this function does not support sample data as the input \\code{object}, unlike\r\n#' the other contour estimation functions in this package. When applied\r\n#' to a fitted \\code{ht} object, the quadrant below the dependence thresholds is ignored.\r\n#' \r\n#' @return\r\n#' A set of estimated ISO contours with the specified return periods in the format\r\n#' of a \\code{data.table} with \\code{rp}, \\code{hs}, and \\code{tp} as columns.\r\n#'\r\n#' @examples\r\n#' # Estimating ISO contours based on a fitted ht object\r\n#' data(ww3_pk)\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 50, dep_thresh_count = 500)\r\n#' ec_ht = estimate_iso(object = ht, output_rp = c(10,100,1000,10000))\r\n#' plot_ec(ec = ec_ht, raw_data = ww3_pk)\r\n#' \r\n#' # Estimating ISO contours based on a fitted wln object\r\n#' data(ww3_ts)\r\n#' wln = fit_wln(data = ww3_ts, npy = nrow(ww3_ts)/10)\r\n#' ec_wln = estimate_iso(object = wln, output_rp = c(10,100,1000,10000))\r\n#' plot_ec(ec = ec_wln, raw_data = ww3_ts)\r\n#' \r\n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}, \\code{\\link{plot_ec}}\r\n#' \r\n#' @references \r\n#' DNVGL-RP-C205, Recommended Practice - Environmental conditions and environmental loads,\r\n#' Edition August 2017, https://rules.dnvgl.com/docs/pdf/DNVGL/RP/2017-08/DNVGL-RP-C205.pdf\r\n#' \r\n#' Heffernan, Janet & A. Tawn, Jonathan. (2004). A Conditional Approach for Multivariate Extreme Values.\r\n#' Journal of the Royal Statistical Society Series B. 66. 497-546. 10.1111/j.1467-9868.2004.02050.x. \r\n#' \r\n#' \r\n#' @export\r\nestimate_iso = function(object, output_rp, n_point=100){\r\n \r\n if(\"ht\" %in% class(object)){\r\n \r\n res = .estimate_iso_from_ht(\r\n ht = object, output_rp = output_rp,\r\n n_point = n_point)\r\n \r\n }else if(\"wln\" %in% class(object)){\r\n \r\n res = .estimate_iso_from_wln(\r\n wln = object, output_rp = output_rp,\r\n n_point = n_point)\r\n \r\n }else if(\"data.table\" %in% class(object)){\r\n \r\n stop(\"Estimation of the isodensity contours based on sample data is not currently supported. Please consider\r\n the alternative types of contours or fitting a Weibull-log-normal or Heffernan-Tawn distribtuion to \r\n the data set first.\")\r\n \r\n }else{\r\n \r\n stop(\"The input object must be of class ht or wln.\")\r\n }\r\n return(res)\r\n}\r\n\r\n\r\n\r\n# Estimate the contour based on a formulated wln --------------------------\r\n\r\n.estimate_iso_from_wln = function(wln, output_rp, n_point, ...){\r\n \r\n ## Anchor point log-density\r\n hs_par = wln$hs$par\r\n tp_par = wln$tp$par\r\n prob_hs = 1-1/(output_rp*wln$npy)\r\n hs0 = qweibull(p = prob_hs, shape = hs_par[[\"shape\"]], scale = hs_par[[\"scale\"]])+hs_par[[\"loc\"]]\r\n tp0 = exp(tp_par[1] + tp_par[2] * hs0^tp_par[3])\r\n ld0 = .ldwln(hs0, tp0, hs_par, tp_par)\r\n\r\n ## Main loop\r\n res_list = list()\r\n for(i in 1:length(output_rp)){\r\n \r\n ### Identify ranges of hs\r\n this_hs_range = .find_hs_range_given_ldwln(\r\n target_ldwln = ld0[i], hs_par = hs_par, tp_par = tp_par, hs_rl = hs0[i])\r\n this_calc = data.table(hs = seq(this_hs_range[1], this_hs_range[2], length.out = round(n_point/2)+1))\r\n \r\n ### Find the corresponding tp\r\n this_calc[, mean_log:=tp_par[1] + tp_par[2] * (hs^tp_par[3])]\r\n # this_calc[, sd_log:=tp_par[4] + tp_par[5] * exp(tp_par[6] * hs)]\r\n this_calc[, sd_log:=pmax(.limit_zero, tp_par[4] + tp_par[5] * exp(tp_par[6] * hs))]\r\n this_calc[, ld_hs:=log(dweibull(hs-hs_par[[\"loc\"]], shape=hs_par[[\"shape\"]], scale=hs_par[[\"scale\"]]))]\r\n this_calc[, ld_tp:=ld0[i]-ld_hs]\r\n for(i_row in 1:this_calc[,.N]){\r\n i_tp_range = this_calc[i_row, .find_tp_given_ldtp(ld_tp, mean_log, sd_log)]\r\n this_calc[i_row, tp_lb:=i_tp_range[1]]\r\n this_calc[i_row, tp_ub:=i_tp_range[2]]\r\n }\r\n \r\n ### Return\r\n res_list[[i]] = this_calc[, .(\r\n rp = output_rp[i],\r\n hs = hs[c(1:(.N-1), .N:1)],\r\n tp = c(tp_lb[1:(.N-1)], tp_ub[.N]/2+tp_lb[.N]/2, tp_ub[(.N-1):1]))]\r\n }\r\n \r\n ## Return\r\n res = rbindlist(res_list)\r\n return(res)\r\n}\r\n\r\n.ldwln = function(hs, tp, hs_par, tp_par){\r\n f_hs = dweibull(hs-hs_par[[\"loc\"]], shape=hs_par[[\"shape\"]], scale=hs_par[[\"scale\"]])\r\n mean_log = tp_par[1] + tp_par[2] * (hs^tp_par[3])\r\n sd_log = pmax(.limit_zero, tp_par[4] + tp_par[5] * exp(tp_par[6] * hs))\r\n f_tp_hs = dlnorm(tp, meanlog = mean_log, sdlog = sd_log)\r\n return(log(f_hs)+log(f_tp_hs))\r\n}\r\n\r\n.find_max_ldwln_given_hs = function(hs, hs_par, tp_par){\r\n mean_log = tp_par[1] + tp_par[2] * (hs^tp_par[3])\r\n sd_log = pmax(.limit_zero, tp_par[4] + tp_par[5] * exp(tp_par[6] * hs))\r\n tp_mode = exp(mean_log-sd_log^2)\r\n return(.ldwln(hs, tp_mode, hs_par, tp_par))\r\n}\r\n\r\n.find_hs_range_given_ldwln = function(target_ldwln, hs_par, tp_par, hs_rl){\r\n op_fn = function(hs, hs_par, tp_par)(.find_max_ldwln_given_hs(hs, hs_par, tp_par)-target_ldwln-.limit_zero)^2\r\n # op1 = optim(\r\n # par = hs_rl/4, fn = op_fn, hs_par=hs_par, tp_par=tp_par, method = \"Brent\",\r\n # lower = hs_par[\"loc\"], upper = hs_rl/1.1)\r\n op2 = optim(\r\n par = hs_rl, fn = op_fn, hs_par=hs_par, tp_par=tp_par, method = \"Brent\",\r\n lower = hs_rl/2, upper = hs_rl*2)\r\n # c(op1$par, op2$par)\r\n c(hs_par[\"loc\"]+.limit_zero, op2$par)\r\n}\r\n\r\n.find_tp_given_ldtp = function(target_ldtp, mean_log, sd_log){\r\n op_fn = function(tp, target_ldtp, mean_log, sd_log)\r\n (log(dlnorm(tp, meanlog = mean_log, sdlog = sd_log))-target_ldtp)^2\r\n \r\n op1 = optim(\r\n par = .limit_zero, fn = op_fn,\r\n mean_log=mean_log, sd_log=sd_log, target_ldtp = target_ldtp,\r\n method = \"Brent\", lower = .limit_zero, upper = exp(mean_log-sd_log^2))\r\n op2 = optim(\r\n par = exp(mean_log-sd_log^2), fn = op_fn,\r\n mean_log=mean_log, sd_log=sd_log, target_ldtp = target_ldtp,\r\n method = \"Brent\", lower = exp(mean_log-sd_log^2), upper = exp(mean_log-sd_log^2)*10)\r\n return(c(op1$par, op2$par))\r\n}\r\n\r\n\r\n\r\n# Esimate the contour based on a formulated ht ----------------------------\r\n\r\n.estimate_iso_from_ht = function(ht, output_rp, n_point){\r\n \r\n ## Find anchro points\r\n ap = .find_ht_iso_anchor_points(ht, output_rp)\r\n\r\n ## Calculate density on lap_grid exceedance area only\r\n lap_thresh = -log(2-2*ht$dep$p_dep_thresh)\r\n max_lap = -2*log(2-2*(1-1/max(output_rp)/ht$npy))\r\n dlap = (max_lap-lap_thresh)/max(100,n_point)\r\n range_lap = seq(max_lap, by = -dlap, to = -max_lap)\r\n grid_lap = data.table(\r\n lap_hs = range_lap, lap_tp = rep(range_lap, each=length(range_lap)))\r\n setkey(grid_lap, lap_hs, lap_tp)\r\n ld_calc = .ld_ht(dt_lap = grid_lap[, .(lap_hs, lap_tp)], ht = ht)\r\n grid_lap = merge(grid_lap, ld_calc, by = c(\"lap_hs\", \"lap_tp\"))\r\n \r\n ## Draw contours\r\n mat = as.matrix(dcast.data.table(grid_lap, lap_hs~lap_tp, value.var = \"ld\")[,-1,with=F])\r\n cl = contourLines(\r\n x = sort(range_lap), y = sort(range_lap),\r\n z = mat, levels = ap$ld)\r\n res = rbindlist(lapply(cl, function(x)data.table(ld=x$level, lap_hs=x$x, lap_tp=x$y)))\r\n \r\n ## Convert contour to original scale\r\n res[, u_hs:=.convert_lap_to_unif(lap_hs)]\r\n res[, hs:=.convert_unif_to_origin(\r\n unif = u_hs, p_thresh = ht$margin$p_margin_thresh, gpd_par = ht$margin$hs$par, emp = ht$margin$hs$emp)]\r\n \r\n res[, u_tp:=.convert_lap_to_unif(lap_tp)]\r\n res[, tp:=.convert_unif_to_origin(\r\n unif = u_tp, p_thresh = ht$margin$p_margin_thresh, gpd_par = ht$margin$tp$par, emp = ht$margin$tp$emp)]\r\n\r\n res[, angle:=atan2(y = lap_tp, x = lap_hs)/pi*180]\r\n \r\n ## Refine output contour\r\n contour = merge(res[, .(ld, hs, tp, angle)], ap[, .(ld, rp)], by = \"ld\")[, .(rp, hs, tp, angle)]\r\n setkey(contour, rp, angle)\r\n out = contour[, .SD[round(seq(1, .N, length.out = n_point))], .(rp)]\r\n \r\n ## Return\r\n return(out[, .(rp, hs, tp)])\r\n}\r\n\r\n.find_ht_iso_anchor_points = function(ht, output_rp){\r\n \r\n ## Find lap_hs0\r\n npy = ht$npy\r\n p_dep_thresh = ht$dep$p_dep_thresh\r\n p_hs0 = 1-(1/(output_rp*npy))\r\n if(any(p_hs0=p_dep_thresh)\r\n lap_hs0 = -log(2*(1-p_hs0))[keep_idx]\r\n p_hs0 = p_hs0[keep_idx]\r\n output_rp = output_rp[keep_idx]\r\n \r\n ## Find median lap_tp0 given lap_hs0\r\n dep_par = ht$dep$hs$par\r\n dep_median_resid = median(ht$dep$hs$resid)\r\n lap_tp0 = lap_hs0*dep_par[[\"a\"]]+dep_median_resid*lap_hs0^dep_par[[\"b\"]]\r\n p_tp0 = 1-exp(-abs(lap_tp0))/2\r\n \r\n ## Find hs0\r\n hs0_calc = data.table(p = p_hs0, p_gpd = (p_hs0-ht$margin$p_margin_thresh)/(1-ht$margin$p_margin_thresh))\r\n hs_par = ht$margin$hs$par\r\n hs0_calc[p_gpd<1 & p_gpd>0, hs0:= qgpd(\r\n p_gpd, loc=hs_par[[\"loc\"]], scale = hs_par[[\"scale\"]], shape = hs_par[[\"shape\"]])]\r\n \r\n ## Find tp0\r\n tp0_calc = data.table(p = p_tp0, p_gpd = (p_tp0-ht$margin$p_margin_thresh)/(1-ht$margin$p_margin_thresh))\r\n tp0_calc[, tp0:=quantile(ht$dep$dep_data$tp, p)]\r\n if(tp0_calc[p_gpd<1 & p_gpd>0, .N]>0){\r\n tp_par = ht$margin$tp$par\r\n tp0_calc[p_gpd<1 & p_gpd>0, tp0:= qgpd(\r\n p_gpd, loc=tp_par[[\"loc\"]], scale = tp_par[[\"scale\"]], shape = tp_par[[\"shape\"]])]\r\n }\r\n \r\n ## Estimate density\r\n out = data.table(rp=output_rp, hs0=hs0_calc$hs0, tp0=tp0_calc$tp0, lap_hs0 = lap_hs0, lap_tp0 = lap_tp0)\r\n setkey(out, lap_hs0, lap_tp0)\r\n ld_calc = .ld_ht(dt_lap = out[, .(lap_hs=lap_hs0, lap_tp=lap_tp0)], ht = ht)\r\n out[, ld:=ld_calc$ld]\r\n \r\n ## Return\r\n return(out[, .(rp, hs0, tp0, ld)])\r\n}\r\n\r\n\r\n.ld_ht = function(dt_lap, ht){\r\n calc = copy(dt_lap)\r\n lap_thresh = -log(2-2*ht$dep$p_dep_thresh)\r\n out = list()\r\n for(cond_var in c(\"hs\",\"tp\")){\r\n dep_var = setdiff(c(\"hs\", \"tp\"), cond_var)\r\n this_resid = ht$dep[[cond_var]]$resid\r\n this_mu = mean(this_resid)\r\n this_sigma = sd(this_resid)\r\n setnames(calc, paste0(\"lap_\", cond_var), \"cond_var\")\r\n setnames(calc, paste0(\"lap_\", dep_var), \"dep_var\")\r\n \r\n this_par = ht$dep[[cond_var]]$par\r\n calc[cond_var>=lap_thresh, resid:=(dep_var-this_par[[\"a\"]]*dep_var)/(cond_var^this_par[[\"b\"]])]\r\n calc[cond_var>=lap_thresh, ld_resid:=dnorm(resid, mean=this_mu, sd = this_sigma, log = T), .(resid)]\r\n calc[cond_var>=lap_thresh, ld_dep:=ld_resid-log(cond_var)*this_par[[\"b\"]]]\r\n calc[cond_var>=lap_thresh, ld_cond:=log(.5)-abs(cond_var)]\r\n calc[cond_var>=lap_thresh, ld:=ld_cond+ld_dep]\r\n setnames(calc, \"cond_var\", paste0(\"lap_\", cond_var))\r\n setnames(calc, \"dep_var\", paste0(\"lap_\", dep_var))\r\n setnames(calc, \"ld\", paste0(\"ld_\", cond_var))\r\n out[[cond_var]] = calc[, c(\"lap_hs\", \"lap_tp\", paste0(\"ld_\", cond_var)), with=F]\r\n }\r\n \r\n calc = merge(out[[1]], out[[2]], by=c(\"lap_hs\", \"lap_tp\"))\r\n calc[lap_hs=lap_thresh & lap_tp>=lap_thresh, w_hs:= (lap_hs-lap_thresh)/(lap_hs+lap_tp-2*lap_thresh)]\r\n calc[lap_hs>=lap_thresh & lap_tp>=lap_thresh, w_tp:= 1-w_hs]\r\n calc[lap_hs>=lap_thresh & lap_tp>=lap_thresh, ld:=ld_hs*w_hs+ld_tp*w_tp]\r\n calc[lap_hs>=lap_thresh & lap_tp=lap_thresh, ld:=ld_tp]\r\n return(calc[, .(lap_hs, lap_tp, ld)])\r\n}\r\n", "meta": {"hexsha": "3c18a6a00243663424ca4464d97afe6a2f6905ee", "size": 12587, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/estimate_iso.r", "max_stars_repo_name": "ECSADES/ecsades-r", "max_stars_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-17T00:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:13:22.000Z", "max_issues_repo_path": "ecsades/R/estimate_iso.r", "max_issues_repo_name": "ECSADES/ecsades-r", "max_issues_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-22T13:00:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-04T16:45:59.000Z", "max_forks_repo_path": "ecsades/R/estimate_iso.r", "max_forks_repo_name": "ECSADES/ecsades-r", "max_forks_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5412541254, "max_line_length": 113, "alphanum_fraction": 0.6528163979, "num_tokens": 4095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49698823591196273}} {"text": "# Based on the paper by Dos Reis & al, 2004\n\nnaive_s = c(0, 0, 0, 0, 0.5, 0.5, 0.75, 0.5)\n\nfind_optimal_s = function (codon_usage, expression, lengths, trna) {\n f = function (s)\n cor(tai(codon_usage, w(trna, c(0, 0, 0, 0, exp(s))), lengths),\n expression,\n method = 'spearman')\n\n # Fix first four values, optimize rest.\n # Optimize `log(s)` to avoid getting negative values into `s`.\n par = log(naive_s[-(1 : 4)])\n within(optim(par, f, control = list(fnscale = -1)),\n {par = c(0, 0, 0, 0, exp(par))})\n}\n\n# Reverse complement of the anticodons, in the order of anticodons as given in\n# Figure 1 of dos Reis & al.\nrc_anticodons = c('TTT', 'TTC', 'TTA', 'TTG',\n 'TCT', 'TCC', 'TCA', 'TCG',\n 'TAT', 'TAC', 'TAA', 'TAG',\n 'TGT', 'TGC', 'TGA', 'TGG',\n\n 'CTT', 'CTC', 'CTA', 'CTG',\n 'CCT', 'CCC', 'CCA', 'CCG',\n 'CAT', 'CAC', 'CAA', 'CAG',\n 'CGT', 'CGC', 'CGA', 'CGG',\n\n 'ATT', 'ATC', 'ATA', 'ATG',\n 'ACT', 'ACC', 'ACA', 'ACG',\n 'AAT', 'AAC', 'AAA', 'AAG',\n 'AGT', 'AGC', 'AGA', 'AGG',\n\n 'GTT', 'GTC', 'GTA', 'GTG',\n 'GCT', 'GCC', 'GCA', 'GCG',\n 'GAT', 'GAC', 'GAA', 'GAG',\n 'GGT', 'GGC', 'GGA', 'GGG')\n\nmet_codon = match('ATG', rc_anticodons)\nstop_codons = match(c('TAA', 'TAG', 'TGA'), rc_anticodons)\n\nw = function (counts, s = naive_s) {\n counts = counts[rc_anticodons]\n counts[is.na(counts)] = 0\n p = 1 - s\n w = vector('numeric', length(counts))\n\n for (i in seq(1, length(counts), by = 4)) {\n w[i] = p[1] * counts[i] + p[5] * counts[i + 1]\n w[i + 1] = p[2] * counts[i + 1] + p[6] * counts[i]\n w[i + 2] = p[3] * counts[i + 2] + p[7] * counts[i]\n w[i + 3] = p[4] * counts[i + 3] + p[8] * counts[i + 2]\n }\n\n w[met_codon] = p[4] * counts[met_codon]\n w = w[-stop_codons]\n w_rel = w / max(w)\n nonzero_w = w_rel[w != 0]\n if (length(nonzero_w) != length(w_rel))\n w_rel[w_rel == 0] = exp(sum(log(nonzero_w)) / length(nonzero_w))\n\n w_rel\n}\n\ntai = function (codon_counts, w, lengths) {\n codons = rc_anticodons[-stop_codons]\n exp(colSums(apply(codon_counts[, codons], 1, `*`, log(w))) / lengths)\n}\n", "meta": {"hexsha": "bd1d3eeeda0d944d4e3491872c58f4669e5e26ec", "size": 2376, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/tai.r", "max_stars_repo_name": "klmr/codons", "max_stars_repo_head_hexsha": "7e5efe08ba91c4891b0820c3e30ebfa5afbf26bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-12-19T00:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-19T00:54:46.000Z", "max_issues_repo_path": "scripts/tai.r", "max_issues_repo_name": "klmr/codons", "max_issues_repo_head_hexsha": "7e5efe08ba91c4891b0820c3e30ebfa5afbf26bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-03-06T14:47:12.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-06T14:47:12.000Z", "max_forks_repo_path": "scripts/tai.r", "max_forks_repo_name": "klmr/codons", "max_forks_repo_head_hexsha": "7e5efe08ba91c4891b0820c3e30ebfa5afbf26bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9428571429, "max_line_length": 78, "alphanum_fraction": 0.4743265993, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49683880784596796}} {"text": "mcmc_performR <- function(data, period_start, init_state_num, init_pars, fix_pars,\n niter = 1e5, BurnIn = 5e3, model = \"Multinomial\", trace_num = 100,\n step_pars = init_pars/1000, ... ){\n Prior_func <- function(pars){\n if(any(pars < 0) || any(pars[(length(pars)/2 + 1):length(pars)] > 1)){\n return (0)\n }else{\n return (1) ## Set a non-informative prior\n }\n }\n \n ftime <- 1:dim(data)[1]\n \n Log_Likelihood_calculateR <- function(pars, period_start = parent.frame()$period_start, init_state_num = parent.frame()$init_state_num, \n ftime = parent.frame()$ftime, fix_pars = parent.frame()$fix_pars){\n ypred <- model_deterministic_simulateR(init_obs = init_state_num, period_start = parent.frame()$period_start, \n times = ftime, pars = pars, fix_pars = parent.frame()$fix_pars)\n p_new_pred_n <- round(ypred[, 11])\n p_new_pred_prob <- ypred[, 12]\n rd_new_pred_n <- round(ypred[, 13])\n r_new_pred_prob <- ypred[, 14]\n d_new_pred_prob <- ypred[, 15]\n p <- c()\n if(model==\"Poisson\"){\n ypred <- p_new_pred_n * p_new_pred_prob \n p<-try(dpois(data$Confirmed, round(ypred),log=T),silent=T)\n if(any(is.nan(p))||any(p==-Inf)){\n logL <- -Inf\n }\n else{\n logL <- sum(p)\n }\n }\n else if(model==\"Binomial\"){\n p <- try(dbinom(data$Confirmed,round( p_new_pred_n), p_new_pred_prob, log = T),silent = T)\n if(any(p == -Inf) || any(is.nan(p))){\n logL <- -Inf\n }else{\n logL <- sum(p)\n }\n }\n else if(model==\"Multinomial\"){\n for(i in 1:dim(ypred)[1]){\n p[i] = try(dbinom(data$Confirmed[i], round(p_new_pred_n[i]) , p_new_pred_prob[i], log = T),silent =T)\n obs_size = data$Confirmed[max(i - 1, 1)]\n pred_size = round(ypred[max(i - 1, 1),\"P\"])\n if((data$Recovered[i] + data$Deceased[i]) > pred_size){\n p[i] = -Inf\n }\n else{\n p[i] = p[i] + try(dmultinom(c(round(c(data$Recovered[i], data$Deceased[i])), pred_size - (data$Recovered[i] + data$Deceased[i])),\n pred_size, c(r_new_pred_prob[i], d_new_pred_prob[i], 1-r_new_pred_prob[i]-d_new_pred_prob[i]),\n log = T),silent=T)\n }\n }\n if(any(p == -Inf) || any(is.nan(p))){\n logL <- -Inf\n }else{\n logL <- sum(p)\n }\n }\n return(logL)\n }\n\n if(period_start[1] != 1){\n period_start = c(1, period_start)\n }\n if(length(period_start) != length(init_pars)/2) \n stop(\"Number of period is not equal to number of initial parameters\")\n \n ## build the matrix to store the results\n \n n_period = length(init_pars)/2 # number of periods\n pmat <- matrix(0, ((niter + BurnIn) / trace_num) + 1, 3*n_period) ## parameters + R0 for n_period periods\n colnames(pmat) <- unlist(lapply(c(\"b\",\"r\",\"R0\") , function(y) lapply(1:n_period, function(x) paste(y,x, sep = \"\"))))\n pmat[1, 1:(2*n_period)] <- init_pars\n R0_est <- R0_calculateR(estpar = init_pars, fix_pars = fix_pars)\n pmat[1, ((2*n_period)+1):(3*n_period)] <- R0_est\n \n ## Start MCMC\n pars_now <- init_pars\n \n cat(\"MCMC:\", fill = T) \n for(i in 2:(niter + BurnIn)){\n pars_new <- rep(0, 2*n_period)\n for(j in 1:(2*n_period)){\n pars_new[j] <- rnorm(1, mean = pars_now[j], sd = step_pars[j])\n }\n A <- 0\n if(Prior_func(pars_new) > 0){ \n ll_pars_new <- Log_Likelihood_calculateR(pars = pars_new)\n if(ll_pars_new != -Inf) {\n ll_pars_now <- Log_Likelihood_calculateR(pars = pars_now)\n A <- exp(1)^(ll_pars_new - ll_pars_now) # Prior_func(pars_new) / Prior_func(pars_now) * 10^(ll_pars_new - ll_pars_now)\n }\n }\n \n if(runif(1) < A){\n pars_now <- pars_new\n }\n if(i %% trace_num == 0) {\n R0_est <- R0_calculateR(estpar = pars_now, fix_pars = fix_pars)\n pmat[(i / trace_num) + 1, 1:(2*n_period)] <- pars_now\n pmat[(i / trace_num) + 1, ((2*n_period)+1):(3*n_period)] <- R0_est\n \n }\n if(i%%(niter/10) == 0) cat(\"Iter\", i, \" A =\", round(A, digits=4), \" : \", round(pars_now, digits=4), fill = T)\n \n }\n mcmc_estimates = pmat[-c(1:(BurnIn / trace_num + 1)), ]\n return(mcmc_estimates)\n \n}", "meta": {"hexsha": "481e73755c9a47ed3f5045c8c23644a65810f082", "size": 4249, "ext": "r", "lang": "R", "max_stars_repo_path": "model/seirfansy_f=0/mcmc_performR.r", "max_stars_repo_name": "umich-cphds/covid_india_wave2", "max_stars_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/seirfansy_f=0/mcmc_performR.r", "max_issues_repo_name": "umich-cphds/covid_india_wave2", "max_issues_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/seirfansy_f=0/mcmc_performR.r", "max_forks_repo_name": "umich-cphds/covid_india_wave2", "max_forks_repo_head_hexsha": "32124bf9d51908d007d409d9bcc160eaebd2c74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6017699115, "max_line_length": 138, "alphanum_fraction": 0.5690750765, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4962190766201866}} {"text": "LISP Interpreter Run\n\n[[[[ Omega in the limit from below! ]]]]\n \ndefine (count-halt prefix bits-left-to-extend)\n if = bits-left-to-extend 0\n if = success car try t 'eval read-exp prefix\n 1 0\n + (count-halt append prefix '(0) - bits-left-to-extend 1)\n (count-halt append prefix '(1) - bits-left-to-extend 1)\n\ndefine count-halt\nvalue (lambda (prefix bits-left-to-extend) (if (= bits-l\n eft-to-extend 0) (if (= success (car (try t (' (ev\n al (read-exp))) prefix))) 1 0) (+ (count-halt (app\n end prefix (' (0))) (- bits-left-to-extend 1)) (co\n unt-halt (append prefix (' (1))) (- bits-left-to-e\n xtend 1)))))\n\ndefine (omega t) cons (count-halt nil t)\n cons /\n cons ^ 2 t\n nil\n\ndefine omega\nvalue (lambda (t) (cons (count-halt nil t) (cons / (cons\n (^ 2 t) nil))))\n\n(omega 0)\n\nexpression (omega 0)\nvalue (0 / 1)\n\n(omega 1)\n\nexpression (omega 1)\nvalue (0 / 2)\n\n(omega 2)\n\nexpression (omega 2)\nvalue (0 / 4)\n\n(omega 3)\n\nexpression (omega 3)\nvalue (0 / 8)\n\n(omega 8)\n\nexpression (omega 8)\nvalue (1 / 256)\n\nEnd of LISP Run\n\nElapsed time is 1 seconds.\n", "meta": {"hexsha": "3775d68d2d7c1bb71915573df46d3ed360cde56c", "size": 1239, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/omega2.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/omega2.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/omega2.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 21.7368421053, "max_line_length": 62, "alphanum_fraction": 0.5375302663, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49574645258047384}} {"text": "## (c) Simon N Wood\n## occupancy likelihood corrected\n## Version allowing the generation time to be manipulated while keeping the\n## disease progression times fixed. \n\n\nlfun <- function(theta,link) {\n## applies link to theta...\n if (is.matrix(link)) {\n a1 <- link[,2];a2 <- link[,3];link <- link[,1]\n } else {\n a1 <- rep(0,length(theta));a2 <- rep(1,length(theta))\n }\n ii <- link==1\n if (length(ii)) theta[ii] <- log(theta[ii])\n ii <- link==2\n if (length(ii)) theta[ii] <- binomial()$linkfun((theta[ii]-a1[ii])/(a2[ii]-a1[ii]))\n theta\n}\n\nilink <- function(eta,link) {\n## apply link inverse and compute dtheta/deta - eta is the unconstrained parameter\n if (is.matrix(link)) {\n a1 <- link[,2];a2 <- link[,3];link <- round(link[,1])\n } else {\n a1 <- rep(0,length(eta));a2 <- rep(1,length(eta))\n }\n theta <- eta\n dtheta <- eta*0+1\n ii <- link==1\n if (length(ii)) {\n dtheta[ii] <- theta[ii] <- exp(eta[ii])\n } \n ii <- link==2\n if (length(ii)) {\n theta[ii] <- binomial()$linkinv(eta[ii])*(a2[ii]-a1[ii]) + a1[ii]\n dtheta[ii] <- binomial()$mu.eta(eta[ii])*(a2[ii]-a1[ii])\n } \n list(theta=theta,dtheta=dtheta)\n}\n\nll <- function(theta,gamma,S0,iaux,daux,dat,Sb=NULL,link=rep(0,length(theta)),plot=FALSE,\n step=1,nbk=rep(2,5),getR=FALSE,lab=\"\",xlab=\"day\") {\n## log likelihood for the rep41 covid SEIR+hospital model. nbk is a vector of overdispersion parameters.\n## rep41 uses neg bin kappa = 2 for all - this is very hard to justify for deaths.\n nb <- iaux[1];np <- iaux[2];nc <- iaux[3];ns <- iaux[4]\n nx <- ns*nc*(1+np);\n nyo <- 14\n ny <- nyo*(1+np)\n x <- rep(0,nx)\n for (i in 1:nc) x[(i-1)*ns+1] <- S0[i]\n ii <- 1:length(gamma)+(nc-1)^2\n daux[ii] <- gamma\n n <- max(dat$day)\n th <- ilink(theta,link)\n thetaw <- theta ## original scale\n theta <- th$theta ## parameters on dynamic model specification scale\n if (any(!is.finite(theta))) return(list(l=NA,dl=NA))\n vm <- .C(\"RK4\",yout = as.double(rep(0,ny*n)),xout=as.double(rep(0,nx*n)),x=as.double(x),\n theta=as.double(theta),h=as.double(1/step),t0=as.double(0),n=as.integer(n),nx=as.integer(nx),ny=as.integer(ny),\n ostep =as.integer(step),work=as.double(rep(0,5*nx)),iaux=as.integer(iaux),daux=as.double(daux))\n yout <- matrix(vm$yout,ny,n)\n\n ## hospital deaths...\n \n k <- nbk[4]\n y <- dat$death3;\n ynb <- matrix(NA,max(dat$day),7);munb <- matrix(NA,max(dat$day),9)\n ii <- !is.na(y); y<- y[ii];ii <- dat$day[ii]\n mu <- yout[4,ii]\n ynb[ii,4] <- y;munb[ii,4] <- mu\n n.death <- sum(mu)\n ld <- sum(k*log(k/(k+mu)) + y*log(mu/(mu+k)) + lgamma(k+y) - lgamma(k) - lgamma(y+1))\n dld.dmu <- y/mu - (y+k)/(mu+k)\n dld <- drop(yout[1:np*nyo+4,ii]%*%dld.dmu)\n if (plot&&length(y)) {\n ylim=c(range(y,mu));xlim <- range(ii)\n maj <- 2.2;mas <- .7\n pch=19;pex=.4\n plot(ii,y,ylab=\"\",col=\"grey\",ylim=ylim,xlim=xlim,xlab=\"\",pch=pch,cex=pex);\n mtext(\"deaths\",2,maj,cex=mas);mtext(xlab,1,maj,cex=mas)\n lines(ii,mu)\n text(220,ylim[2]*.86,lab)\n }\n \n ## care home deaths...\n\n k <- nbk[5]\n y <- dat$death2-dat$death3;ii <- !is.na(y); y<- y[ii];ii <- dat$day[ii]\n mu <- yout[5,ii];n.death <- n.death+ sum(mu)\n ynb[ii,5] <- y;munb[ii,5] <- mu\n lg <- sum(k*log(k/(k+mu)) + y*log(mu/(mu+k)) + lgamma(k+y) - lgamma(k) - lgamma(y+1))\n dlg.dmu <- y/mu - (y+k)/(mu+k)\n dlg <- drop(yout[1:np*nyo+5,ii]%*%dlg.dmu)\n if (plot&&length(y)) {\n points(ii,y,col=2,pch=pch,cex=pex);lines(ii,mu,col=4)\n }\n \n ## occupancy...\n\n k <- 100000\n\n ## total occupancy... \n y0 <- dat$phe_patients;i0 <- dat$day\n ii <- !is.na(y0);y <- sum(y0[ii]);i0 <- i0[ii]\n mu <- sum(yout[2,i0])\n\n ## log likelihood total occupancy....\n lot <- sum(k*log(k/(k+mu)) + y*log(mu/(mu+k)) + lgamma(k+y) - lgamma(k) - lgamma(y+1))\n dlot.dmu <- y/mu - (y+k)/(mu+k)\n dlot <- rowSums(yout[1:np*nyo+2,i0]) * dlot.dmu \n \n ## get change in occupancy over the day - difference between in and outflow\n k <- nbk[2] ## overdispersion parameter\n y <- diff(dat$phe_patients);ii <- !is.na(y); y <- y[ii];ii <- dat$day[ii]\n mu1 <- yout[11,ii] # general ward inflow\n mu2 <- yout[12,ii] # general ward outflow\n wi <- rep(1:ceiling(length(y)/7),each=7)[1:length(y)]\n y <- tapply(y,wi,sum) ## aggregate differences by week to avoid unmodelled weekly discharge cycle\n mu1 <- tapply(mu1,wi,sum);mu2 <- tapply(mu2,wi,sum)\n \n iw <- ii[1]+1:length(y)*7 - 4 ## output to allow over-dispersion update\n ynb[iw,6] <- y;munb[iw,6] <- mu1;munb[iw,7] <- mu2; \n alpha <- y-mu1+mu2;sig <- mu1+mu2\n\n lo <- sum(-alpha^2/(2*k*sig) - log(k*sig)/2) ## log likelihood occupancy change\n dlo.dmu1 <- alpha/(k*sig) + alpha^2/(2*k*sig^2) - .5/sig\n dlo.dmu2 <- -alpha/(k*sig) + alpha^2/(2*k*sig^2) -.5/sig\n dlo <- t(apply(yout[1:np*nyo+11,ii],1,function(y,wi) tapply(y,wi,sum),wi=wi))%*%dlo.dmu1 +\n\t t(apply(yout[1:np*nyo+12,ii],1,function(y,wi) tapply(y,wi,sum),wi=wi))%*%dlo.dmu2 \n lo <- lo + lot;\n dlo <- drop(dlo) + dlot\n \n ## occupancy itself for plotting and return..\n y <- dat$phe_patients;ii <- !is.na(y); y<- y[ii];ii <- dat$day[ii]\n mu <- yout[2,ii]\n ynb[ii,2] <- y;munb[ii,2] <- mu\n\n if (plot&&length(y)) { \n plot(ii,y,col=\"grey\",ylim=range(c(y,mu)),xlim=xlim,ylab=\"\",xlab=\"\",pch=pch,cex=pex)\n mtext(\"occupancy\",2,maj,cex=mas);mtext(xlab,1,maj,cex=mas)\n lines(ii,mu)\n }\n \n ## ICU occupancy...\n k <- 20000\n\n y0 <- dat$phe_occupied_mv_beds;i0 <- dat$day\n ii <- !is.na(y0);y <- sum(y0[ii]);i0 <- i0[ii]\n mu <- sum(yout[3,i0])\n ## log likelihood total icu occupancy\n lut <- sum(k*log(k/(k+mu)) + y*log(mu/(mu+k)) + lgamma(k+y) - lgamma(k) - lgamma(y+1))\n dlut.dmu <- y/mu - (y+k)/(mu+k)\n dlut <- rowSums(yout[1:np*nyo+3,i0]) * dlut.dmu\n\n ## get likelihood for icu occupancy changes...\n k <- nbk[3] ## overdispersion parameter\n y <- diff(dat$phe_occupied_mv_beds);ii <- !is.na(y); y<- y[ii];ii <- dat$day[ii]\n mu1 <- yout[13,ii] # ICU inflow\n mu2 <- yout[14,ii] # ICU outflow\n wi <- rep(1:ceiling(length(y)/7),each=7)[1:length(y)]\n y <- tapply(y,wi,sum) ## aggregate differences by week to avoid unmodelled weekly discharge cycle\n mu1 <- tapply(mu1,wi,sum);mu2 <- tapply(mu2,wi,sum)\n \n iw <- ii[1]+1:length(y)*7 - 4\n ynb[iw,7] <- y;munb[iw,8] <- mu1;munb[iw,9] <- mu2;\n\n alpha <- y-mu1+mu2;sig <- mu1+mu2\n lu <- sum(-alpha^2/(2*k*sig) - log(k*sig)/2) ## log likelihood - icu occupancy change\n dlu.dmu1 <- alpha/(k*sig) + alpha^2/(2*k*sig^2) - .5/sig\n dlu.dmu2 <- -alpha/(k*sig) + alpha^2/(2*k*sig^2) -.5/sig\n dlu <- t(apply(yout[1:np*nyo+13,ii],1,function(y,wi) tapply(y,wi,sum),wi=wi))%*%dlu.dmu1 +\n\t t(apply(yout[1:np*nyo+14,ii],1,function(y,wi) tapply(y,wi,sum),wi=wi))%*%dlu.dmu2 \n #dlu <- drop(yout[1:np*nyo+13,ii]%*%dlu.dmu1)+drop(yout[1:np*nyo+14,ii]%*%dlu.dmu2)\n lu <- lu + lut\n dlu <- dlu + dlut\n # ICU occupancy itself for plotting and return\n y <- dat$phe_occupied_mv_beds;ii <- !is.na(y); y<- y[ii];ii <- dat$day[ii]\n mu <- yout[3,ii]\n ynb[ii,3] <- y;munb[ii,3] <- mu\n if (plot&&length(y)) {\n points(ii,y,col=2,pch=pch,cex=pex)#xlab=\"day\",ylab=\"ICU\",col=\"grey\",ylim=range(c(y,mu)));\n lines(ii,mu,col=4)\n }\n \n ## hospitalization...\n\n y <- dat$phe_admissions; ii <- !is.na(y); y<- y[ii]\n ii <- dat$day[ii] ## cols of yout corresponding to observed data\n k <- nbk[1] ## theta parameter\n mu <- yout[1,ii]\n ynb[ii,1] <- y;munb[ii,1] <- mu\n lh <- sum(k*log(k/(k+mu)) + y*log(mu/(mu+k)) + lgamma(k+y) - lgamma(k) - lgamma(y+1))\n dlh.dmu <- y/mu - (y+k)/(mu+k)\n dlh <- drop(yout[1:np*nyo+1,ii]%*%dlh.dmu)\n #if (plot) par(mfrow=c(2,3));\n if (plot&&length(y)) {\n plot(ii,y,col=\"grey\",ylim=range(c(y,mu)),xlim=xlim,ylab=\"\",xlab=\"\",pch=pch,cex=pex);\n mtext(\"admissions\",2,maj,cex=mas);mtext(xlab,1,maj,cex=mas)\n lines(ii,mu)\n }\n \n ## serology samples...\n \n N <- sum(S0[4:13])\n y <- dat$n_positive;ii <- !is.na(y); y<- y[ii];\n n <- dat$total_samples[ii]\n ii <- dat$day[ii]\n mu <- yout[6,ii]/N\n ls <- sum(dbinom(y,n,mu,log=TRUE))\n dls.dmu <- y/mu - (n-y)/(1-mu)\n dls <- drop(yout[1:np*nyo+6,ii]%*%dls.dmu)/N\n if (plot&&length(y)) {\n plot(ii,y/n,ylab=\"\",ylim=range(c(y/n,mu)),col=\"grey\",xlim=xlim,xlab=\"\",pch=pch,cex=pex)\n mtext(\"P(sero)\",2,maj,cex=mas);mtext(xlab,1,maj,cex=mas)\n lines(ii,mu,col=1)\n }\n \n ## REACT PCR samples...\n\n N <- sum(S0[2:18]) \n y <- dat$react_pos;ii <- !is.na(y); y<- y[ii];\n n <- dat$react_samples[ii]\n ii <- dat$day[ii]\n mu <- yout[7,ii]/N\n lr <- sum(dbinom(y,n,mu,log=TRUE))\n dlr.dmu <- y/mu - (n-y)/(1-mu)\n dlr <- drop(yout[1:np*nyo+7,ii]%*%dlr.dmu)/N\n if (plot&&length(y)) {\n plot(ii,y/n,ylab=\"\",col=\"grey\",xlim=xlim,xlab=\"\",pch=pch,cex=pex);lines(ii,mu,col=1)\n mtext(\"P(pcr)\",2,maj,cex=mas);mtext(xlab,1,maj,cex=mas)\n }\n \n l=lh+lo+lu+ld+lg+lr+ls ## total log likelihood\n dl=dlh+dlo+dlu+dld+dlg+dlr+dls ## corresponding derivative vector\n\n if (!is.null(Sb)) { ## add smoothing penalty\n Sb <- drop(Sb %*% theta[1:nb])\n l <- l - sum(theta[1:nb]*Sb)/2\n dl[1:nb] <- dl[1:nb] - Sb\n }\n R <- yout[9,]; R[R<0] <- NA; Rd <- NULL\n if (plot||getR) { ## get the Diekmann version of R...\n gamma_A <- gamma[2];gamma_C <- gamma[3];p_c <- gamma[4]\n Rd <- R\n beta <- yout[10,]\n C <- matrix(daux[1:(nc-1)^2],nc-1,nc-1)[-(nc-1),-(nc-1)]\n n <- max(dat$day)\n xout <- matrix(vm$xout,nx,n)[1:(nc*ns),]\n S <- xout[0:(nc-3)*ns+1,]\n for (i in 1:n) {\n C0 <- S[,i]*C\n K <- beta[i]*rbind(cbind((1-p_c)*C0/gamma_A,(1-p_c)*C0/gamma_C),cbind(p_c*C0/gamma_A,p_c*C0/gamma_C))\n Rd[i] <- abs(eigen(K,only.values = TRUE)$values[1])\n }\n } else xout <- NULL\n if (ncol(link)>3) { ## prior on dynamic params too\n ii <- (nb+1):np\n sig.p <- link[ii,5]\n l <- l - sum((thetaw[ii]-link[ii,4])^2/(2*sig.p^2)) \n dprior <- c(rep(0,nb),-(thetaw[ii]-link[ii,4])/sig.p^2)\n } else dprior <- 0\n list(l=l,dl=dl*th$dtheta+dprior,R=R,Rd=Rd,fi=yout[8,],xout=xout,n.death=n.death,munb=munb,ynb=ynb)\n} ## ll\n\n\nthfix <- function(theta,fixi,fixv) {\n## if fixi!=NULL then it indexes parameters that have been dropped from the optimization of\n## theta, while fixv gives their fixed values. This routine inserts the fixed values into\n## theta in the correct place...\n if (!is.null(fixi)) {\n if (length(fixi)!=length(fixv)) stop(\"fixv wrong length\")\n th1 <- rep(0,length(theta)+length(fixi))\n ii <- rep(FALSE,length(th1))\n ii[fixi] <- TRUE\n th1[ii] <- fixv\n th1[!ii] <- theta\n theta <- th1\n }\n theta\n} ## thfix\n\nnll <- function(theta,gamma,S0,iaux,daux,dat,Sb,link,step=1,nbk=rep(2,5),fixi=NULL,fixv=NULL) {\n## if fixi!=NULL then it indexes parameters that have been dropped from the optimization of\n## theta, while fixv gives their fixed values.\n iaux[7] <- 0; ## no derivatives needed\n theta <- thfix(theta,fixi,fixv)\n -ll(theta,gamma,S0,iaux,daux,dat,Sb=Sb,link=link,plot=FALSE,step=step,nbk=nbk)$l\n}\n\nnll0 <- function(theta,gamma,S0,iaux,daux,dat,Sb,link,step=1,nbk=rep(2,5),fixi=NULL,fixv=NULL) {\n## if fixi!=NULL then it indexes parameters that have been dropped from the optimization of\n## theta, while fixv gives their fixed values.\n iaux[7] <- 0; ## no derivatives needed\n theta <- thfix(theta,fixi,fixv)\n ll(theta,gamma,S0,iaux,daux,dat,Sb=Sb,link=link,plot=FALSE,step=step,nbk=nbk)\n}\n\nnllg <- function(theta,gamma,S0,iaux,daux,dat,Sb,link,step=1,nbk=rep(2,5),fixi=NULL,fixv=NULL) {\n## grad function corresponding to nll\n theta <- thfix(theta,fixi,fixv)\n g <- -ll(theta,gamma,S0,iaux,daux,dat,Sb=Sb,link=link,plot=FALSE,step=step,nbk=nbk)$dl\n if (!is.null(fixi)) g <- g[-fixi]\n g\n}\n\nhessian <- function(theta,gamma,S0,iaux,daux,dat,Sb,link,step=1,nbk=rep(2,5),fixi=NULL,fixv=NULL) {\n ## compute Hessian by finite differencing \n nt <- length(theta)\n eps <- 1e-7\n g0 <- nllg(theta,gamma,S0,iaux,daux,dat,Sb,link,step,nbk,fixi,fixv)\n H <- matrix(0,nt,nt)\n for (i in 1:nt) {\n theta1 <- theta;theta1[i] <- theta[i] + eps\n g1 <- nllg(theta1,gamma,S0,iaux,daux,dat,Sb,link,step,nbk,fixi,fixv)\n H[,i] <- (g1-g0)/eps;\n }\n .5*(t(H)+H)\n} ## hessian\n\nnll1 <- function(theta,gamma,S0,iaux,daux,dat,Sb,link,step=1,nbk=rep(2,5),fixi=NULL,fixv=NULL) {\n## unused nlm version\n theta <- thfix(theta,fixi,fixv)\n l0 <- ll(theta,gamma,S0,iaux,daux,dat,Sb=Sb,link=link,plot=FALSE,step=step,nbk=nbk)\n nll <- -l0$l\n attr(nll,\"gradient\") <- -l0$dl\n nll\n}\n\nginv <- function(V,warn=FALSE) { ## generalized inverse\n if (!all(is.finite(V))) return(NULL)\n ev <- eigen(V,symmetric=TRUE)\n d <- ev$values;ii <- d>0\n d[ii] <-1/d[ii];d[!ii] <- 0\n if (warn&&sum(!ii)) warning(\"indefinite V\\n\")\n ev$vectors%*%(d*t(ev$vectors))\n}\n\ntf <- function(x,a1=.00,a2=.1) { ## transform as applied to b(t)\n ii <- x<0\n x[ii] <- exp(x[ii])\n x[!ii] <- exp(-x[!ii])\n x[ii] <- a1 + (a2-a1)*x[ii]/(1+x[ii])\n x[!ii] <- a1 + (a2-a1)*1/(1+x[!ii])\n x\n}\n\nitf <- function(y,a1=.00,a2=.1) { ## transform as applied to b(t)\n y <- (y-a1)/(a2-a1)\n log(y/(1-y)) \n}\n\n\nsetup.model <- function(location=\"london\",Xtype=2,beta.off = .25,rep41C=FALSE) {\n## sets up the information required for a model fit, including fixed parameters,\n## data, initial parameter values and limits.\n \n source(\"params.r\") ## some fixed parameters\n\n region <- c(\"east_of_england\",\"london\",\"midlands\",\"north_east_and_yorkshire\",\n \"north_west\",\"south_east\",\"south_west\")\n\n if (!location %in% region) stop(\"location wrong\")\n\n source(\"data.r\",local=TRUE) ## obtain the fit data and some other parameters\n\n load(paste(\"C_\",location,\".rda\",sep=\"\"))\n ## or use m from sircovid package - problem is that it only matches what is documented\n ## up to age 70 (parameters change but results unchanged)... \n if (rep41C) C <- ch$m[1:18,1:18] \n \n n <- max(rtr$day) ## number of output steps\n step <- 1 ## steps between output\n h <- 1/step ## step length\n hx <- h/2 ## step at which basis evaluation required\n t <- h*0:(2*step*n)/2 ## when basis evaluation required \n nb <- 80 ## number of b(t) coeffs\n if (Xtype==1) {## adaptive\n t0 <- 45 ## constant b(t) before here\n ii <- t >= t0 ## set up adaptive smooth from t0\n smb <- smoothCon(s(t,k=nb,bs=\"ad\"),data=data.frame(t=t[ii]))[[1]]\n ni <- sum(!ii) ## need to pad model matrix to fill in constant prior to t0\n X0 <- matrix(smb$X[1,],ni,ncol(smb$X),byrow=TRUE)\n Xb <- rbind(X0,smb$X) ## b(t) basis matrix\n Sb <- smb$S ## penalty matrix\n attr(Sb,\"rank\") <- smb$rank\n } else if (Xtype==2) { ## force b(t) to be constant at start\n ne <- 5\n smb <- smoothCon(s(t,k=nb+ne,bs=\"bs\"),data=data.frame(t=t))[[1]]\n T <- diag(nb+ne)[,-(1:ne)];T[1:ne,1] <- 1\n Xb <- smb$X%*%T ## b(t) basis matrix \n Sb <- t(T)%*%smb$S[[1]]%*%T ## penalty matrix\n } else { ## rep 41\n nb <- length(bk)\n Xb <- matrix(0,length(t),nb)\n Xb[,1] <- as.numeric(t<=bk[1])\n for (i in 1:nb) {\n yk <- bk*0;yk[i] <- 1\n Xb[,i] <- approx(bk,yk,t,rule=2)$y\n }\n Sb <- NULL\n }\n\n\n b0 <- c(rep(-2.4,5),-2.404542,-2.468239,-2.676757,-3.068759,-3.510927,\n -3.833448,-3.971020,-3.999736,rep(-4,10),-3.999977,-3.987959,-3.920592,\n -3.752347,-3.506797,-3.277703,-3.147313,-3.104178,rep(-3.5,14))\n t0 <- 0:44*7.5+7\n b0 <- exp(approx(t0,b0,t,rule=2)$y)\n a1 <- 0; a2 <- 0.1\n b0[b0>a2] <- a1 + (a2-a1)*.95\n b0[b0 generation time 6.2 (brought down by asymptomatics) \n gamma_ph <- 1/5.3 ## 5.3 is the length of the post I_C pre hospital phase (2.8 without correction)\n gamma_A <- ch$gamma_asympt\n gamma_IC_Wr <- .0641 ## Table S2\n gamma_IC_Wd <- .14 ## Table S2\n gamma_IC_d <- .17 ## Table S2\n gamma_Wr <- .16 ## Table S2\n gamma_Wd <- .12 ## Table S2\n gamma_Hr <- .0935 ## Table S2\n gamma_Hd <- .19 ## Table S2\n gamma_S <- 1/13 ## Table S7\n p_S <- .85 ## Table S7\n\n gamma0 <- c(gamma_E,gamma_A,gamma_C,p_c,inoc_sig,gamma_ph,p_star,\n f_start,f_end,ch$gamma_ICU_D,gamma_U,gamma_IC_Wr,gamma_IC_Wd,gamma_IC_d,\n\t gamma_Wr,gamma_Wd,gamma_Hr,gamma_Hd,ch$gamma_PCR_pre,\n ch$gamma_PCR_pos,gamma_S,p_S)\n\n names(gamma0) <- c(\"gamma_E\",\"gamma_A\",\"gamma_C\",\"p_c\",\"inoc_sig\",\"gamma_ph\",\"p_star\",\n \"f_start\",\"f_end\",\"gamma_IC_pre\",\"gamma_U\",\"gamma_IC_Wr\",\"gamma_IC_Wd\",\"gamma_IC_d\",\n \"gamma_Wr\",\"gamma_Wd\",\"gamma_Hr\",\"gamma_Hd\",\"gamma_P\",\"gamma_Po\",\"gamma_S\",\"p_S\")\n\n gamma <- c(gamma0,psi.h,psi.ic,psi.icd,psi.wd,psi.hd) ## 19 vector\n ng <- length(gamma)\n np <- length(theta)\n nc <- 19 ## classes\n ns <- 37 ## states per class\n nk <- prod(dim(Xb))\n deriv <- 1\n iaux <- c(nb,np,nc,ns,ng,nk,deriv,-1)\n daux <- c(C,gamma,t(Xb),hx,rep(0,nb+2*(nc+nc*np)))\n S0=ch$N_tot\n thetaw <- lfun(theta,link=link);fixi <- fixv <- NULL\n arg <- list(location=location,gamma=gamma,S0=S0,thetaw=thetaw,iaux=iaux,daux=daux,dat=rtr,Sb=Sb,link=link,step=step)\n arg\n} ## setup.model\n\nnlnb <- function(theta,y,mu) {\n## negative log lik for NB\n ii <- is.na(y)|is.na(mu)\n y <- y[!ii];mu <- mu[!ii]\n -sum(theta*log(theta/(theta+mu)) + y*log(mu/(mu+theta)) + lgamma(theta+y) - lgamma(theta))\n}\n\n\nfit.model <- function(arg) {\n## fit model using Fellner Schall sp updates...\n if (is.null(arg$Sb)) { m <- 0; Sb <- NULL} else\n if (is.list(arg$Sb)) {\n lambda <- rep(10,length(arg$Sb))\n Sb <- arg$Sb[[1]]*lambda[1]\n m <- length(arg$Sb)\n if (m>1) for (i in 2:m) Sb <- Sb + arg$Sb[[i]]*lambda[i]\n if (m==1) arg$Sb <- arg$Sb[[1]]\n } else {\n m <- 1\n Sb <- arg$Sb * 10 \n }\n thetaw <- if (is.null(arg$fixi)) arg$thetaw else arg$thetaw[-arg$fixi]\n er <- optim(thetaw,nll,gr=nllg,method=\"BFGS\",control=list(maxit=400),gamma=arg$gamma,S0=arg$S0,\n iaux=arg$iaux,daux=arg$daux,dat=arg$dat,Sb=Sb,link=arg$link,step=arg$step,\n\t nbk=rep(2,5),fixi=arg$fixi,fixv=arg$fixv)\n cat(arg$location,\" \")\n \n er$par -> thetaw -> thetaw0\n\n if (is.null(arg$Sb)) { m <- 0; Sb <- NULL} else\n if (is.list(arg$Sb)) {\n lambda <- rep(10,length(arg$Sb))\n Sb <- arg$Sb[[1]]*lambda[1]\n m <- length(arg$Sb)\n if (m>1) for (i in 2:m) Sb <- Sb + arg$Sb[[i]]*lambda[i]\n } else {\n m <- 1; lambda <- 10\n Sb <- arg$Sb * lambda\n }\n nrep <- if (m>0) 20 else 1 ## based on prelim run\n\n nbk <- c(2,2,2,2000,50) ## admissions, ward and icu occupancy, hospital deaths, care home deaths\n k1 <- c(40,100,100,2000,2000) ## upper limits on overdispersion param\n for (i in 1:nrep) {\n er0 <- er\n er <- optim(thetaw,nll,gr=nllg,method=\"BFGS\",control=list(maxit=400),gamma=arg$gamma,S0=arg$S0,\n iaux=arg$iaux,daux=arg$daux,dat=arg$dat,Sb=Sb,link=arg$link,step=arg$step,\n\t nbk=nbk,fixi=arg$fixi,fixv=arg$fixv,hessian=FALSE)\n ## get Hessian without Sb first - check +ve semidef\t \n H <- hessian(er$par,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,\n step=arg$step,nbk=nbk,arg$fixi,arg$fixv)\n eh <- eigen(H)\n if (any(eh$values<0)) { ## find nearest +ve semi definite\n eh$values[eh$values<0] <- 0\n H <- eh$vectors %*% (eh$values*t(eh$vectors))\n }\n Hp <- H ## penalized version\n if (!is.null(Sb)) {\n nb <- ncol(Sb)\n Hp[1:nb,1:nb] <- Hp[1:nb,1:nb] + Sb\n }\n \n ## update nb theta...\n l0 <- nll0(thetaw,gamma=arg$gamma,S0=arg$S0,iaux=arg$iaux,daux=arg$daux,\n dat=arg$dat,Sb=Sb,link=arg$link,step=arg$step)\n for (i in c(1,5)) { ## optimize log lik\n nbk[i] <- optimize(nlnb,interval=c(2,k1[i]),y=l0$ynb[,i],mu=l0$munb[,i])$minimum \n }\n for (i in 2:3) { ## update occupancy rates overdispersion\n y <- l0$ynb[,i+4];ii <- !is.na(y);y <- y[ii]\n mu1 <- l0$munb[ii,i*2+2]\n mu2 <- l0$munb[ii,i*2+3]\n k.mle <- mean((y-mu1+mu2)^2/(mu1+mu2)) \n k.mle <- if (k.mle < 1) 1 else { if (k.mle>k1[i]) k1[i] else k.mle}\n nbk[i] <- k.mle\n }\n er$par -> thetaw\n thetaw <- thfix(er$par,arg$fixi,arg$fixv)\n Vb <- ginv(Hp,warn=TRUE)\n if (is.null(Vb)) break\n nb <- arg$iaux[1]\n b <- thetaw[1:nb]\n if (m>1) { \n Si <- ginv(Sb)\n if (is.null(Si)) { Vb <- NULL; break}\n for (i in 1:m) {\n fac <- drop((sum(Si*arg$Sb[[i]]) - sum(Vb[1:nb,1:nb]*arg$Sb[[i]]))/t(b)%*%arg$Sb[[i]]%*%b)\n\tif (fac<0.2) fac <- .2\n\tif (fac>5) fac <- 5 \n lambda[i] <- lambda[i]*fac\n }\n \n Sb <- arg$Sb[[1]]*lambda[1]\n for (i in 2:m) Sb <- Sb + arg$Sb[[i]]*lambda[i]\n } else if (m==1) {\n fac <- drop(((nb-2)/lambda - sum(Vb[1:nb,1:nb]*arg$Sb))/t(b)%*%arg$Sb%*%b)\n if (fac<0.2) fac <- .2\n if (fac>5) fac <- 5\n lambda <- lambda*fac\n Sb <- lambda*arg$Sb\n }\n if (m>0) cat(arg$region,\": \",lambda,\"\\n\")\n }\n if (is.null(Vb)) {\n er <- er0\n er$par -> thetaw\n Vb <- ginv(er$hessian)\n }\n list(thetaw=thetaw,theta=ilink(thetaw,arg$link)$theta,Vb=Vb,H=Hp,lambda=lambda,nbk=nbk)\n} ## fit.model\n\n\ncheck.model <- function(arg,plot=TRUE,deriv=FALSE) {\n## checks if initial params gtive something remotely reasonable\n arg$iaux[7] <- as.numeric(deriv) \n l0 <- ll(arg$thetaw,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=plot,step=arg$step)\n}\n\ncheck.derivs <- function(thetaw,arg,eps = 1e-6) {\n## checks derivatives of penalized log likelihood. Note currently not checking with smoothing penalty.\n l0 <- ll(thetaw,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=FALSE,step=arg$step)\n fd <- l0$dl*0\n arg$iaux[7] <- 0\n for (i in 1:length(fd)) {\n theta1 <- thetaw;theta1[i] <- theta1[i] + eps\n l1 <- ll(theta1,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=FALSE,step=arg$step)\n fd[i] <- (l1$l-l0$l)/eps\n cat(\".\")\n }\n cat(\"\\n\")\n plot(l0$dl,fd);abline(0,1)\n list(dl=l0$dl,fd=fd,l=l0$l)\n}\n\ndRfi <- function(arg) {\n## lazy evaluation of derivatives of R and incidence trajectories w.r.t. parameters, assuming thetaw and Vb added to arg\n eps = 1e-5\n thetaw <- arg$thetaw\n l0 <- ll(thetaw,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=FALSE,step=arg$step,getR=TRUE)\n dR <- df <- matrix(0,length(l0$Rd),length(thetaw))\n for (i in 1:length(thetaw)) {\n theta1 <- thetaw;theta1[i] <- theta1[i] + eps\n l1 <- ll(theta1,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=FALSE,step=arg$step,getR=TRUE)\n dR[,i] <- (log(l1$Rd)-log(l0$Rd))/eps\n df[,i] <- (log(l1$fi)-log(l0$fi))/eps\n }\n list(dR=dR,df=df,se.r=rowSums((dR%*%arg$Vb) * dR)^.5,se.f=rowSums((df%*%arg$Vb) * df)^.5,fi=l0$fi,Rd=l0$Rd)\n} ## dRfi\n\nplot.fit <- function(fit,arg) {\n## quick plot of fit to data + R and incidence.\n l0 <- ll(fit$thetaw,arg$gamma,arg$S0,arg$iaux,arg$daux,arg$dat,Sb=NULL,link=arg$link,plot=TRUE,step=arg$step)\n X11()\n par(mfrow=c(2,2))\n plot(log(l0$Rd),xlim=c(50,150));abline(0,0);abline(v=84)\n plot(log(l0$Rd));abline(1,0);abline(v=84)\n plot(l0$Rd,xlim=c(50,150));abline(1,0);abline(v=84)\n\n plot(l0$fi,xlim=c(50,150));abline(v=84)\n \n} ## plot.fit\n\n###############################################################################\nsetwd(\"~sw283/research.notes/covid19/rep41/code/albus\") ## Data & Code location\n###############################################################################\n\nlibrary(mgcv);library(parallel)\ndyn.load(\"albus-gl.so\")\n\nregion <- c(\"east_of_england\",\"london\",\"midlands\",\"north_east_and_yorkshire\",\n \"north_west\",\"south_east\",\"south_west\")\n\nrlab <- c(\"East\",\"London\",\"Midlands\",\"N.E. & Yorkshire\", \"North West\", \"South East\", \"South West\")\n\n## setup regional fits...\narg <- list()\nfor (i in 1:7) arg[[i]] <-setup.model(region[i],Xtype=1,beta.off=.75,rep41C=FALSE)\nnames(arg) <- rlab\nload(\"thetaw0-g.rda\")\nfor (i in 1:7) {\n arg[[i]]$region <- rlab[i]\n arg[[i]]$thetaw <- thetaw0 ## initialize from old fit to midlands to speed up\n}\n\n\n## par(mfrow=c(2,3));check.model(arg[[1]])\n## plot.fit(er,arg[[1]])\n## system.time(fd <- check.derivs(arg[[1]]$thetaw,arg[[1]]));fd$dl[-(1:80)];fd$fd[-(1:80)]\n\nsystem.time(er <- mclapply(arg,fit.model,mc.cores=7))\n\n\nfor (i in 1:7) { ## add fit results to arg list\n arg[[i]]$thetaw <- er[[i]]$thetaw\n arg[[i]]$Vb <- er[[i]]$Vb\n}\n## get derivatives of R and fi (incidence) w.r.t. parameters\nsystem.time(dd <- mclapply(arg,dRfi,mc.cores=7)) \n\n# for (i in 1:7) arg[[i]]$iaux[8] <- 83 ## freeze b(t) at b(83)\n\n## check all fits and compute total incidence and average R -\n## R is number of new infections per existing infection, so\n## must be weighted by existing infectives.\nns <- arg[[1]]$iaux[4]\nnc <- arg[[1]]$iaux[3]\nii <- rep((0:(nc-3))*ns,each=2)+4:5 ## index of all infectives outside care homes\nn.deaths <- 0\n\nps <- FALSE\nif (ps) postscript(\"fits.eps\",horizontal=F,height=9,width=11)\npar(mfrow=c(7,5),mar=c(3.5,4,0,0))# par(mfcol=c(5,7),mar=c(4,4,1,1))\nxlab=\"\"\nfor (k in 1:7) {\n arg[[k]]$iaux[7] <- 0 ## turn off derivatives\n if (k==7) xlab=\"day\"\n l0 <- ll(er[[k]]$thetaw,arg[[k]]$gamma,arg[[k]]$S0,arg[[k]]$iaux,arg[[k]]$daux,arg[[k]]$dat,Sb=NULL,\n link=arg[[k]]$link,plot=TRUE,step=arg[[k]]$step,getR=TRUE,lab=arg[[k]]$region,xlab=xlab)\n n.deaths <- n.deaths + l0$n.death\t\n arg[[k]]$iaux[7] <- 1\n Ik <- colSums(l0$xout[ii,])\n rep <- 1000;n <- length(l0$Rd)\n if (k==1) {\n R <- exp(log(dd[[1]]$Rd) + matrix(rnorm(n*rep),n,rep)*dd[[1]]$se.r)*Ik \n f <- exp(log(dd[[1]]$fi) + matrix(rnorm(n*rep),n,rep)*dd[[1]]$se.f)\n Rd <- dd[[k]]$Rd*Ik \n ftot <- dd[[k]]$fi\n Itot <- Ik\n } else {\n R <- R + exp(log(dd[[k]]$Rd) + matrix(rnorm(n*rep),n,rep)*dd[[k]]$se.r)*Ik\n f <- f + exp(log(dd[[k]]$fi) + matrix(rnorm(n*rep),n,rep)*dd[[k]]$se.f)\n Itot <- Itot + Ik\n Rd <- Rd+ dd[[k]]$Rd*Ik\n ftot <-ftot + dd[[k]]$fi\n }\n #text(200,.01,names(arg)[k])\n #X11()\n}\nif (ps) dev.off()\n\nRd <- Rd/Itot\nRav <- R/Itot \nRci <- apply(Rav,1,quantile,prob=c(.025,.975))\nfci <- apply(f,1,quantile,prob=c(.025,.975))\n\nfor (j in 1:2) {\nif (j==1) {\n xlim <- c(50,150);xpos <- 110\n fn <- \"fw-gc.eps\"\n} else { \n xlim <- c(60,320);xpos <-150\n fn <- \"w2-gc.eps\"\n} \nvt <- c(84,216,245,258,288,310)\n\nif (ps) postscript(fn) else X11()\npar(mfrow=c(2,2),mar=c(5,5,1,1))\nt <- 1:length(Rd)\nc1 <- 1.3\nplot(ftot,xlim=xlim,type=\"l\",ylim=c(0,max(fci[2,50:150])),xlab=\"day\",ylab=\"incidence\",cex.lab=c1)\nlines(t,fci[1,],lty=2);lines(t,fci[2,],lty=2)\nabline(v=vt)\n\nplot(dd[[1]]$fi,xlim=xlim,ylim=c(0,70000),type=\"l\",lwd=3,xlab=\"day\",ylab=\"incidence\",cex.lab=c1)\nlines(t,exp(log(dd[[1]]$fi)+dd[[1]]$se.f*2),lty=2)\nlines(t,exp(log(dd[[1]]$fi)-dd[[1]]$se.f*2),lty=2)\ntext(xpos,20000,arg[[1]]$region)\nfor (k in 2:7) {\n lines(dd[[k]]$fi,col=k,lwd=3)\n text(xpos,10000+k*10000,arg[[k]]$region,col=k)\n lines(t,exp(log(dd[[k]]$fi)+dd[[k]]$se.f*2),lty=2,col=k)\n lines(t,exp(log(dd[[k]]$fi)-dd[[k]]$se.f*2),lty=2,col=k)\n}\nabline(v=vt)\nplot(Rd,xlim=xlim,ylim=c(0,4),type=\"l\",lwd=1,xlab=\"day\",ylab=\"R\",cex.lab=c1)\nlines(t,Rci[1,],lty=2);lines(t,Rci[2,],lty=2)\n\nabline(1,0);abline(v=vt)\n\n\nplot(log(dd[[1]]$Rd),xlim=xlim,ylim=c(-2,2),type=\"l\",lwd=3,xlab=\"day\",ylab=\"log(R)\",cex.lab=c1)\nlines(t,log(dd[[1]]$Rd)+dd[[1]]$se.r*2,lty=2)\nlines(t,log(dd[[1]]$Rd)-dd[[1]]$se.r*2,lty=2)\ntext(xpos,.35,arg[[1]]$region)\nfor (k in 2:7) {\n lines(log(dd[[k]]$Rd),col=k,lwd=3)\n lines(t,log(dd[[k]]$Rd)+dd[[k]]$se.r*2,lty=2,col=k)\n lines(t,log(dd[[k]]$Rd)-dd[[k]]$se.r*2,lty=2,col=k)\n text(xpos,.1+k*.25,arg[[k]]$region,col=k)\n}\nabline(0,0);abline(v=vt)\nif (ps) dev.off()\n}\n", "meta": {"hexsha": "c5c54e1f7f6350a9e0832da725f6cd60d8aa0e4b", "size": 29009, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Wood_CovidODE_2021/albus/albus-gl.r", "max_stars_repo_name": "slwu89/fitexamples", "max_stars_repo_head_hexsha": "368f7ee797d25ebcf105d2f15c3deab7cf5784ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Wood_CovidODE_2021/albus/albus-gl.r", "max_issues_repo_name": "slwu89/fitexamples", "max_issues_repo_head_hexsha": "368f7ee797d25ebcf105d2f15c3deab7cf5784ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Wood_CovidODE_2021/albus/albus-gl.r", "max_forks_repo_name": "slwu89/fitexamples", "max_forks_repo_head_hexsha": "368f7ee797d25ebcf105d2f15c3deab7cf5784ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1434058899, "max_line_length": 121, "alphanum_fraction": 0.59360888, "num_tokens": 11732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49572126801937133}} {"text": " # clear\n cat(\"\\014\")\n rm(list = ls())\n dev.off(dev.list()[\"RStudioGD\"])\n \n # Libraries\n library(seqinr)\n library(MASS)\n library(ggplot2)\n library(ggpubr)\n library(stringr)\n library(combinat)\n \n #--------------------- SELECT DATA ---------------------------------------------\n # 'artificial' and 'artificial-non-uni' for artificial dataset, 'real' for real-world data (biom_data_150bp.rda)\n dataset_type <- \"real\"\n \n #---------------- FUNCTIONS ----------------------------------------------------\n \n # Returns prime numbers up to integer n\n sieve <- function(n) {\n n <- as.integer(n)\n if(n > 1e6) stop(\"n too large\")\n primes <- rep(TRUE, n)\n primes[1] <- FALSE\n last.prime <- 2L\n for(i in last.prime:floor(sqrt(n)))\n {\n primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE\n last.prime <- last.prime + min(which(primes[(last.prime+1):n]))\n }\n which(primes)\n }\n \n # Reads sequence from input file\n seqList <- function(x, type) {\n if (type == \"DNA\") {\n as.list(read.fasta(x,\n as.string = TRUE,\n seqtype=\"DNA\",\n seqonly = TRUE,\n strip.desc = TRUE))\n }\n else {\n if (type == \"AA\") {\n as.list(read.fasta(x,\n as.string = FALSE,\n seqtype=\"AA\",\n seqonly = FALSE,\n strip.desc = TRUE))\n }\n else {\n NULL\n }\n }\n }\n \n # Generates random DNA sequences\n createRandomSequencesBasedOnDistr <- function(count, length, prob=c(0.25,0.25,0.25,0.25), fileNameRandSeqs) {\n \n sink(fileNameRandSeqs)\n for (i in 1:count) {\n cat(\">Seq\", i, \"\\n\", sep = \"\")\n seqX <- sample(c(\"A\",\"C\",\"G\",\"T\"), length, rep=TRUE, prob)\n cat(paste(seqX,collapse=\"\"), \"\\n\", sep = \"\")\n }\n sink()\n }\n \n # Generating random permutations of godel number assignments\n createRandomSequenceValues <- function(seedList, type) {\n \n if ( type == \"DNA\" ) {\n results <- matrix(, nrow = length(seedList), ncol = 4)\n }\n else if ( type == \"AA\" ) {\n results <- matrix(, nrow = length(seedList), ncol = 23)\n }\n \n for (i in 1:length(seedList)) {\n if ( type == \"DNA\" ) {\n results[i,] <- sample(seq(from = 1, to = 4, by = 1), size = 4, replace = FALSE)\n }\n else if ( type == \"AA\" ) {\n results[i,] <- sample(seq(from = 1, to = 23, by = 1), size = 23, replace = FALSE)\n }\n }\n return(results)\n }\n \n assignSets <- function(randSequenceValues, type) {\n \n stringValues <- \"\"\n \n if (type == \"DNA\") {\n #DNA Set\n cat(\"Sequence Values: (\")\n \n for (i in 1:4) {\n stringValues <- paste(stringValues, randSequenceValues[i], \", \")\n }\n cat(stringValues)\n cat(\")\\n\")\n assign(\"A\", randSequenceValues[1], envir = .GlobalEnv)\n assign(\"C\", randSequenceValues[2], envir = .GlobalEnv)\n assign(\"G\", randSequenceValues[3], envir = .GlobalEnv)\n assign(\"T\", randSequenceValues[4], envir = .GlobalEnv)\n }\n else if ( type == \"AA\") {\n # AA Set 1\n cat(\"Sequence Values: (\")\n for (i in 1:23) {\n stringValues <- paste(stringValues, randSequenceValues[i], \", \")\n }\n cat(stringValues)\n cat(\")\\n\")\n assign(\"A\", randSequenceValues[1], envir = .GlobalEnv) # alanine, ala\n assign(\"R\", randSequenceValues[2], envir = .GlobalEnv) # arginine, arg\n assign(\"N\", randSequenceValues[3], envir = .GlobalEnv) # asparagine, asn\n assign(\"D\", randSequenceValues[4], envir = .GlobalEnv) # aspartic acid, asp\n assign(\"B\", randSequenceValues[5], envir = .GlobalEnv) # sparagine or aspartic acid, asx\n assign(\"C\", randSequenceValues[6], envir = .GlobalEnv) # cysteine, cys\n assign(\"E\", randSequenceValues[7], envir = .GlobalEnv) # glutamic acid, glu\n assign(\"Q\", randSequenceValues[8], envir = .GlobalEnv) # glutamine, gln\n assign(\"Z\", randSequenceValues[9], envir = .GlobalEnv) # glutamine or glutamic acid, glx\n assign(\"G\", randSequenceValues[10], envir = .GlobalEnv) # glycine, gly\n assign(\"H\", randSequenceValues[11], envir = .GlobalEnv) # histidine, his\n assign(\"I\", randSequenceValues[12], envir = .GlobalEnv) # isoleucine, ile\n assign(\"L\", randSequenceValues[13], envir = .GlobalEnv) # leucine, leu\n assign(\"K\", randSequenceValues[14], envir = .GlobalEnv) # lysine, lys\n assign(\"M\", randSequenceValues[15], envir = .GlobalEnv) # methionine, met\n assign(\"F\", randSequenceValues[16], envir = .GlobalEnv) # phenylalanine, phe\n assign(\"P\", randSequenceValues[17], envir = .GlobalEnv) # proline, pro\n assign(\"S\", randSequenceValues[18], envir = .GlobalEnv) # serine, ser\n assign(\"T\", randSequenceValues[19], envir = .GlobalEnv) # threonine, thr\n assign(\"W\", randSequenceValues[20], envir = .GlobalEnv) # tryptophan, trp\n assign(\"Y\", randSequenceValues[21], envir = .GlobalEnv) # tyrosine, tyr\n assign(\"V\", randSequenceValues[22], envir = .GlobalEnv) # valine, val\n assign(\"X\", randSequenceValues[23], envir = .GlobalEnv) # undetermined\n }\n \n stringValues\n }\n \n # Statistics function\n godelStatistics <- function(x) {\n \n if (logOutput) {\n cat(paste(\" Min : \", summary(x)[1], \"\\n\"))\n cat(paste(\"1st Qu.: \", summary(x)[2], \"\\n\"))\n cat(paste(\"Median : \", summary(x)[3], \"\\n\"))\n cat(paste(\" Mean : \", summary(x)[4], \"\\n\"))\n cat(paste(\"3rd Qu.: \", summary(x)[5], \"\\n\"))\n cat(paste(\" Max : \", summary(x)[6], \"\\n\"))\n cat(paste(\"St. Dev: \", sd(x), \"\\n\"))\n }\n \n results <- list(minG = summary(x)[1], firstQG = summary(x)[2],\n medianG = summary(x)[3], meanG = summary(x)[4], \n thirdQG = summary(x)[5], maxG = summary(x)[6],\n stdG = sd(x))\n \n return(results)\n }\n \n calculateGodelNumbers <- function(sequences, primes, encoding){\n \n \n chars = str_split(sequences, \"\", simplify = TRUE)\n \n chars.enc = matrix(data = 0, nrow = nrow(chars), ncol = ncol(chars))\n \n chars.enc = chars.enc + (chars == \"A\") * encoding[1]\n chars.enc = chars.enc + (chars == \"C\") * encoding[2]\n chars.enc = chars.enc + (chars == \"G\") * encoding[3]\n chars.enc = chars.enc + (chars == \"T\") * encoding[4]\n \n primes = log(primes)\n \n chars.enc = chars.enc %*% diag(primes)\n godel_nums <- rowSums(chars.enc) # gn_new\n return(godel_nums)\n \n \n }\n \n \n #----------------------------- Main code ---------------------------------------\n primes <- sieve(20000) # length of primes should be >= max sequence length\n logOutput <- FALSE # debug output\n replicate <- TRUE # if we need to set specific seed numbers\n type <- \"DNA\" # type of data\n \n # encodings\n encodings <- permn(c(1,2,3,4))\n numberOfEncodings <- 24; # number of different assignments of letters for Godel numbers (we have DNA data)\n \n # The following values should execute within 6 minutes with a good enough resolution\n seqLengthLimit <- 150\n numberOfArtificialSeqs <- 90000 # \"A\",\"C\",\"G\",\"T\"\n \n # Creating artificial data set\n # createRandomSequencesBasedOnDistr(numberOfArtificialSeqs, seqLengthLimit, c(0.3,0.3,0.2,0.2), \"data/artificialSeq-non-unis.fasta\")\n \n # Loading a fasta file - artificial dataset\n if (dataset_type == \"artificial\"){\n ompGene.list <- seqList(\"data/artificialSeqs.fasta\", type)\n ompGene.list.raw <- ompGene.list\n } else if (dataset_type == \"real\"){\n ompGene.list <- seqList(\"data/realSeqs_biom_150bp.fasta\", type)\n } else if (dataset_type == \"artificial-non-uni\"){\n ompGene.list <- seqList(\"data/artificialSeq-non-unis.fasta\", type)\n } else {\n print(\"Incorrect dataset type.\")\n }\n sequences <- unlist(ompGene.list)\n \n #encodingValues <- createRandomSequenceValues(seedValuesList, type) - we don't neet this function\n encodingValues <- matrix(0, nrow = length(encodings), ncol = 4)\n for (i in 1:nrow(encodingValues)){\n encodingValues[i,] <- encodings[[i]]\n }\n \n \n sizeExp <- length(ompGene.list)\n selectedSequences <- c(1:sizeExp)\n \n godelValuePoints <- data.frame(matrix(0, ncol = numberOfEncodings, nrow = sizeExp))\n namesList <- list()\n for (i in 1:numberOfEncodings) {\n namesList[i] <- paste('godel_log_pos', i, sep = '')\n }\n godelValuePoints <- setNames(godelValuePoints, namesList)\n godelValuePoints$seqNames <- unlist(attributes(ompGene.list)$name)\n \n stringAssignValues <- vector(mode=\"character\", length=numberOfEncodings)\n \n len_of_sequences <- str_length(sequences[1])\n primes <- primes[1:len_of_sequences]\n primes <- as.numeric(primes)\n \n # main loop - godel number calculation\n for (indexPos in 1:numberOfEncodings) {\n \n stringAssignValues[indexPos] <- assignSets(encodingValues[indexPos,], type)\n encoding <- encodingValues[indexPos,]\n godelValuePoints[, paste('godel_log_pos', indexPos, sep = '')] <- calculateGodelNumbers(sequences, primes, encoding)\n \n }\n \n \n statsPos <- data.frame(matrix(0, ncol = 7, nrow = numberOfEncodings))\n statsPos <- setNames(statsPos, c(\"minG\", \"firstQG\", \"medianG\", \"meanG\", \"thirdQG\", \"maxG\", \"stdG\"))\n for (indexPos in 1:numberOfEncodings) {\n statsPos[indexPos, ] <- godelStatistics(godelValuePoints[, paste('godel_log_pos', indexPos, sep = '')])\n }\n \n statsPos_rownames <- c()\n for (i in 1:numberOfEncodings){\n this_enc <- paste(encodingValues[i,], collapse = '')\n statsPos_rownames <- c(statsPos_rownames, paste(\"enc_\", this_enc, sep = ''))\n }\n \n rownames(statsPos) <- statsPos_rownames\n \n \n # Theoretical distribution parameters\n P1 <- sum(log(primes[1:seqLengthLimit]))\n P2 <- sum((log(primes[1:seqLengthLimit]))^2)\n theoreticalMeanEqual <- P1*2.5\n theoreticalStdEqual <- sqrt(P2*1.25)\n theoretical_dist <- rnorm(90000, theoreticalMeanEqual, theoreticalStdEqual)\n \n # comparisons\n para <- matrix(nrow=numberOfEncodings, ncol = 2)\n for (indexPos in 1:numberOfEncodings) {\n fit <- fitdistr(godelValuePoints[, indexPos], \"normal\")\n para[indexPos, 1] <- fit$estimate[\"mean\"]\n para[indexPos, 2] <- fit$estimate[\"sd\"]\n }\n \n \n statsPos$stringAssignValues <- as.factor(stringAssignValues)\n statsPos$fit_estimate <- ((para[,1]-theoreticalMeanEqual)/para[,1])*100\n statsPos$fit_sd <- ((para[,2]-theoreticalStdEqual)/para[,2])*100\n \n statsPos$theoretical_mean <- theoreticalMeanEqual\n statsPos$theoretical_std <-theoreticalStdEqual\n \n # t-test\n statsPos$p.value <- NaN\n for (i in 1:numberOfEncodings){\n t_test_results <- t.test(godelValuePoints[,i], theoretical_dist)\n statsPos[i,]$p.value <- t_test_results$p.value\n }\n \n \n #-------------------- Main histogram plotting ----------------------------------\n dir.create('plots')\n indexPos = 1 # Specify which encoding to plot\n binwidthPlot = 5\n this_enc <- paste(encodingValues[indexPos,], collapse = '')\n \n # comparisons file save\n filepath <- paste('plots/comparisons_',dataset_type, '.csv', sep = '' )\n write.csv(as.data.frame(statsPos), file = filepath)\n \n this_title= expression(paste('Histogram and Density plot of ln(Godel numbers) - encoding 1234', sep = '' ))\n \n # Plots\n filepath <- paste('plots/histogram_encoding_', this_enc,'_',dataset_type, '.png', sep = '' )\n png(file = filepath, width=1200, height=800)\n my_plot <- ggplot(godelValuePoints, aes(x=godelValuePoints[, indexPos]), environment = environment()) + \n geom_histogram(aes(y=..density..), colour=\"black\", fill=\"white\", binwidth=binwidthPlot)+\n geom_density(alpha=.2, fill=\"#FF6666\") +\n stat_function(fun = dnorm, args = list(mean = theoreticalMeanEqual, sd = theoreticalStdEqual), color = \"darkblue\", size = 1, linetype = \"longdash\") +\n stat_function(fun = dnorm, args = list(mean = para[indexPos,1], sd = para[indexPos,2]), color = \"darkred\", size = 2, linetype = \"dotdash\") +\n labs(title = this_title, x=expression('ln(Godel Numbers)'), y = \"Density\")+\n xlim(1000,3000) +\n ylim(0, 0.009) +\n scale_color_brewer(palette=\"Accent\") + \n theme(title = element_text(size=20),\n axis.text.x = element_text(size = 20, face = 'bold'), axis.text.y = element_text(size = 15), \n axis.title.x = element_text(size=20)) \n print(my_plot)\n \n dev.off()\n \n # ---------------- Other plots -------------------------------------------------\n \n p1 <- ggplot(statsPos, aes(x = reorder(stringAssignValues, fit_estimate), y = fit_estimate, group=1)) +\n geom_point() +\n geom_line() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n labs(title= \"Difference between theoretical and observed value of Mean (%)\",x=\"Assignments\", y = \"Difference in mean (%)\")\n \n p2 <- ggplot(statsPos, aes(x = reorder(stringAssignValues, fit_estimate), y = fit_sd, group=1)) +\n geom_point() +\n geom_line() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n labs(title= \"Difference between theoretical and observed value of standard deviation (%)\",x=\"Assignments\", y = \"Difference in standard deviation (%)\")\n \n ggarrange(p1 + rremove(\"x.text\"), p2,\n labels = c(\"A\", \"B\"),\n ncol = 1, nrow = 2)\n \n \n # a t g c\n lapply(which(statsPos$maxG == min(statsPos$maxG)),\n function(x) assignSets(encodingValues[x,], \"DNA\"))\n # artificial dataset: 4 , 1 , 3 , 2 (min of meanG)\n # artificial dataset: 4 , 2 , 1 , 3 (min of minG)\n # artificial dataset: 2 , 1 , 3 , 4 (min of maxG)\n \n # a t g c\n lapply(which(statsPos$maxG == max(statsPos$maxG)),\n function(x) assignSets(encodingValues[x,], \"DNA\"))\n # artificial dataset: 1 , 4 , 2 , 3 (max of meanG)\n # artificial dataset: 4 , 3 , 2 , 1 (max of minG)\n # artificial dataset: 1 , 3 , 4 , 2 (max of maxG)\n \n \n", "meta": {"hexsha": "8dbb13e14ee45cf0d07c7e1122797c02a25b3e66", "size": 13786, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Biological-Sequences-and-Godel-numbers.r", "max_stars_repo_name": "BiodataAnalysisGroup/godel-numbering", "max_stars_repo_head_hexsha": "104ae61378fd6c7d06131efdc59c80146278c4eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Biological-Sequences-and-Godel-numbers.r", "max_issues_repo_name": "BiodataAnalysisGroup/godel-numbering", "max_issues_repo_head_hexsha": "104ae61378fd6c7d06131efdc59c80146278c4eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Biological-Sequences-and-Godel-numbers.r", "max_forks_repo_name": "BiodataAnalysisGroup/godel-numbering", "max_forks_repo_head_hexsha": "104ae61378fd6c7d06131efdc59c80146278c4eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9779614325, "max_line_length": 155, "alphanum_fraction": 0.6020600609, "num_tokens": 3962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4955345869369528}} {"text": "### About:\n## The function is to estimate the mean and covariance function\n## from a cluster of functions/longitudinal observations. The output\n## will also predict each curve.\n\n## Function arguments:\n### \"data\" is a data frame with three arguments:\n# (1) \"argvals\": observation times;\n# (2) \"subj\": subject indices;\n# (3) \"y\": values of observations;\n# Note that: we only handle complete data, so missing values are not allowed at this moment\n\n## \"newdata\" is of the same strucutre as \"data\".\n## To predict at new values of \"argvals\", make the corresponding \"y\" NA\n\n### \"center\" means if we want to compute population mean\n\n### \"argvals.new\" if we want the estimated covariance function at \"argvals.new\"; if NULL,\n### then 100 equidistant points in the range of \"argvals\" in \"data\"\n\n### \"knots\" is the number of interior knots for B-spline basis functions to be used;\n\nface.sparse.inner <- function(data, newdata = NULL, W = NULL,\n center = TRUE, argvals.new = NULL,\n knots = 7, knots.option = \"equally-spaced\",\n p = 3, m = 2, lambda = NULL, lambda_mean = NULL,\n search.length = 14,\n lower = -3, upper = 10,\n calculate.scores = FALSE, pve = 0.99) {\n\n #########################\n #### step 0: read in data\n #########################\n check.data(data)\n if (!is.null(newdata)) {\n check.data(newdata, type = \"predict\")\n }\n\n y <- data$y\n t <- data$argvals\n subj <- data$subj\n tnew <- argvals.new\n if (is.null(tnew)) tnew <- seq(min(t), max(t), length = 100)\n\n fit_mean <- NULL\n\n knots.initial <- knots\n #########################\n #### step 1: demean\n #########################\n r <- y\n mu.new <- rep(0, length(tnew))\n if (center) {\n fit_mean <- pspline(data, argvals.new = tnew, knots = knots.initial, lambda = lambda_mean)\n mu.new <- fit_mean$mu.new\n r <- y - fit_mean$fitted.values\n }\n #########################\n #### step 2:raw estimates\n #########################\n indW <- F # whether identity W\n if (is.null(W)) indW <- T\n\n raw <- raw.construct(data.frame(\"argvals\" = t, \"subj\" = subj, \"y\" = as.vector(r)))\n C <- raw$C\n st <- raw$st\n N <- raw$st\n N2 <- raw$N2\n if (indW) W <- raw$W\n n0 <- raw$n0\n # indicator where ti = tj\n delta <- Matrix((st[, 1] == st[, 2]) * 1) # sparse\n\n #########################\n #### step 3: smooth\n #########################\n\n # set up\n knots <- construct.knots(t, knots, knots.option, p)\n ## construct design & penalty on column dimension\n List <- pspline.setting(st[, 1], knots = knots, p, m, type = \"simple\", knots.option = knots.option)\n B1 <- List$B\n B1 <- Matrix(B1)\n DtD <- List$P\n ## construct design on row dimension\n B2 <- spline.des(knots = knots, x = st[, 2], ord = p + 1, outer.ok = TRUE, sparse = TRUE)$design\n c <- dim(B1)[2]\n c2 <- c * (c + 1) / 2\n ## combine tensor product design\n B <- Matrix(t(KhatriRao(Matrix(t(B2)), Matrix(t(B1)))))\n G <- Matrix(duplication.matrix(c))\n\n BtWB <- matrix(0, nrow = c^2, ncol = c^2)\n Wdelta <- c()\n WC <- c()\n for (i in 1:n0) {\n seq <- (sum(N2[1:i]) - N2[i] + 1):(sum(N2[1:i])) # select combos for object i\n B3 <- Matrix(matrix(B[seq, ], nrow = length(seq)))\n W3 <- W[[i]] # don't form a large W\n BtWB <- BtWB + crossprod(B3, W3 %*% B3)\n Wdelta <- c(Wdelta, as.matrix(W3 %*% delta[seq]))\n WC <- c(WC, as.matrix(W3 %*% C[seq]))\n }\n\n GtBtWBG <- crossprod(G, BtWB %*% G)\n\n BG <- B %*% G # sparse\n detWde <- crossprod(delta, Wdelta) # detWde = sum(delta)\n GtBtWdelta <- crossprod(BG, Wdelta)\n XtWX <- rbind(cbind(GtBtWBG, GtBtWdelta), cbind(t(GtBtWdelta), detWde))\n X <- cbind(BG, delta)\n # precalculate (2 eigens)\n eSig <- eigen(XtWX, symmetric = TRUE)\n V <- eSig$vectors\n E <- eSig$values\n E <- E + 0.000001 * max(E)\n Sigi_sqrt <- matrix.multiply(V, 1 / sqrt(E)) %*% t(V)\n ## penalty\n P <- crossprod(G, Matrix(suppressMessages(kronecker(diag(c), DtD)))) %*% G\n\n Q <- bdiag(P, 0)\n tUQU <- crossprod(Sigi_sqrt, (Q %*% Sigi_sqrt))\n Esig <- eigen(tUQU, symmetric = TRUE)\n # s, f, ftilde, F(A here)\n U <- Esig$vectors\n s <- Esig$values\n A0 <- Sigi_sqrt %*% U\n A <- as.matrix(X %*% A0) # F=XA dense\n\n AtA <- crossprod(A) # diff\n f <- crossprod(A, C) # diff\n ftilde <- crossprod(A, WC) # diff\n\n c2 <- c2 + 1\n g <- rep(0, c2)\n G1 <- matrix(0, c2, c2)\n mat_list <- list()\n # G, g, Li(AitAi here), Litilde(Li here)\n for (i in 1:n0) {\n seq <- (sum(N2[1:i]) - N2[i] + 1):(sum(N2[1:i]))\n Ai <- matrix(A[seq, ], nrow = length(seq))\n AitAi <- crossprod(Ai) # t(Ai)%*%Ai\n Wi <- W[[i]]\n\n fi <- crossprod(Ai, C[seq]) # t(Fi)Ci\n Ji <- crossprod(Ai, Wi %*% C[seq])\n Li <- crossprod(Ai, Wi %*% Ai)\n g <- g + Ji * fi\n G1 <- G1 + AitAi * (Ji %*% t(ftilde))\n\n LList <- list()\n LList[[1]] <- AitAi\n LList[[2]] <- Li\n mat_list[[i]] <- LList\n }\n\n # select smoothing parameter\n Lambda <- seq(lower, upper, length = search.length)\n Gcv <- 0 * Lambda\n gcv <- function(x) {\n lambda <- exp(x)\n d <- 1 / (1 + lambda * s)\n ftilde_d <- ftilde * d\n cv0 <- -2 * sum(ftilde_d * f)\n cv1 <- sum(ftilde_d * (AtA %*% ftilde_d))\n cv2 <- 2 * sum(d * g)\n cv3 <- -4 * sum(d * (G1 %*% d))\n cv4 <- sum(unlist(sapply(mat_list, function(x) {\n a <- x[[1]] %*% ftilde_d\n b <- x[[2]] %*% ftilde_d\n 2 * sum(a * b * d)\n })))\n cv <- cv0 + cv1 + cv2 + cv3 + cv4\n return(cv)\n }\n if (is.null(lambda)) {\n Lambda <- seq(lower, upper, length = search.length) # construct lambda grid\n Length <- length(Lambda)\n Gcv <- rep(0, Length)\n for (i in 1:Length) {\n Gcv[i] <- gcv(Lambda[i])\n }\n i0 <- which.min(Gcv)\n lambda <- exp(Lambda[i0])\n }\n # parameter estimated (sym)\n alpha <- matrix.multiply(A0, 1 / (1 + lambda * s)) %*% ftilde\n Theta <- G %*% alpha[1:(c2 - 1)] # wrong index?\n Theta <- matrix(Theta, c, c)\n sigma2 <- alpha[c2]\n if (sigma2 <= 0.000001) {\n warning(\"error variance cannot be non-positive, reset to 1e-6!\")\n sigma2 <- 0.000001\n }\n # make sure Theta positive definite(2 eigens)\n Eigen <- eigen(Theta, symmetric = TRUE)\n Eigen$values[Eigen$values < 0] <- 0\n npc <- sum(Eigen$values > 0) # which.max(cumsum(Eigen$values)/sum(Eigen$values)>pve)[1]\n if (npc > 1) {\n Theta <- matrix.multiply(Eigen$vectors[, 1:npc], Eigen$values[1:npc]) %*% t(Eigen$vectors[, 1:npc])\n Theta_half <- matrix.multiply(Eigen$vectors[, 1:npc], sqrt(Eigen$values[1:npc]))\n }\n if (npc == 1) {\n Theta <- Eigen$values[1] * suppressMessages(kronecker(Eigen$vectors[, 1], t(Eigen$vectors[, 1])))\n Theta_half <- sqrt(Eigen$values[1]) * Eigen$vectors[, 1]\n }\n Eigen <- eigen(Theta, symmetric = TRUE)\n\n #########################\n #### step 4: calculate estimated covariance function\n ######################### (2 eigens)\n # prepare estimation dense design\n Bnew <- spline.des(knots = knots, x = tnew, ord = p + 1, outer.ok = TRUE, sparse = TRUE)$design\n Gmat <- crossprod(Bnew) / nrow(Bnew)\n eig_G <- eigen(Gmat, symmetric = T)\n G_half <- eig_G$vectors %*% diag(sqrt(eig_G$values)) %*% t(eig_G$vectors)\n G_invhalf <- eig_G$vectors %*% diag(1 / sqrt(eig_G$values)) %*% t(eig_G$vectors)\n\n Chat.new <- as.matrix(tcrossprod(Bnew %*% Matrix(Theta), Bnew)) # cov matrix\n Chat.diag.new <- as.vector(diag(Chat.new))\n Cor.new <- diag(1 / sqrt(Chat.diag.new)) %*% Chat.new %*% diag(1 / sqrt(Chat.diag.new)) # scale to cor matrix\n\n # what is these parts? (another npc)\n Eigen.new <- eigen(as.matrix(G_half %*% Matrix(Theta) %*% G_half), symmetric = TRUE)\n # Eigen.new = eigen(Chat.new,symmetric=TRUE)\n npc <- which.max(cumsum(Eigen$values) / sum(Eigen$values) > pve)[1] # determine number of PCs\n eigenfunctions <- matrix(Bnew %*% G_invhalf %*% Eigen.new$vectors[, 1:min(npc, length(tnew))], ncol = min(npc, length(tnew)))\n eigenvalues <- Eigen.new$values[1:min(npc, length(tnew))]\n # eigenfunctions = eigenfunctions*sqrt(length(tnew))/sqrt(max(tnew)-min(tnew))\n # eigenvalues = eigenvalues/length(tnew)*(max(tnew)-min(tnew))\n\n\n #########################\n #### step 5: calculate variance\n #########################\n var.error.hat <- rep(sigma2, length(t))\n var.error.new <- rep(sigma2, length(tnew))\n\n Chat.raw.new <- Chat.new + diag(var.error.new) # add variance sigma2\n Chat.raw.diag.new <- as.vector(diag(Chat.raw.new))\n Cor.raw.new <- diag(1 / sqrt(Chat.raw.diag.new)) %*% Chat.raw.new %*% diag(1 / sqrt(Chat.raw.diag.new))\n #########################\n #### step 6: prediction\n #########################\n if (!is.null(newdata)) {\n # means for newdata\n mu.pred <- rep(0, length(newdata$argvals))\n var.error.pred <- rep(sigma2, length(newdata$argvals))\n if (center) {\n mu.pred <- predict.pspline.face(fit_mean, newdata$argvals)\n }\n\n # setup prediction data\n subj.pred <- newdata$subj\n subj_unique.pred <- unique(subj.pred)\n y.pred <- newdata$y\n Chat.diag.pred <- 0 * y.pred\n se.pred <- 0 * y.pred\n\n scores <- list(\n subj = subj_unique.pred,\n scores = matrix(NA, nrow = length(subj_unique.pred), ncol = npc),\n u = matrix(NA, nrow = length(subj_unique.pred), ncol = nrow(Theta))\n )\n\n # prediction for each subject i\n for (i in 1:length(subj_unique.pred)) {\n # select the observations for subject i\n sel.pred <- which(subj.pred == subj_unique.pred[i])\n lengthi <- length(sel.pred)\n\n pred.points <- newdata$argvals[sel.pred]\n mu.predi <- mu.pred[sel.pred]\n var.error.predi <- var.error.pred[sel.pred]\n # center response\n y.predi <- y.pred[sel.pred] - mu.predi\n sel.pred.obs <- which(!is.na(y.predi))\n # select tij correspond to non na response\n obs.points <- pred.points[sel.pred.obs]\n if (!is.null(obs.points)) {\n var <- mean(var.error.predi[sel.pred.obs])\n if (var == 0 & length(sel.pred.obs) < npc) {\n stop(\"Measurement error estimated to be zero and there are fewer observed points thans PCs; scores\n cannot be estimated.\")\n }\n B3i.pred <- spline.des(knots = knots, x = pred.points, ord = p + 1, outer.ok = TRUE, sparse = TRUE)$design\n B3i <- spline.des(knots = knots, x = obs.points, ord = p + 1, outer.ok = TRUE, sparse = TRUE)$design\n Chati <- tcrossprod(B3i %*% Theta, B3i)\n Chat.diag.pred[sel.pred] <- diag(Chati)\n if (length(sel.pred.obs) == 1) Ri <- var.error.predi[sel.pred.obs]\n if (length(sel.pred.obs) > 1) Ri <- diag(var.error.predi[sel.pred.obs])\n Vi.inv <- as.matrix(solve(Chati + Ri))\n\n Vi.pred <- tcrossprod(B3i.pred %*% Theta, B3i.pred)\n Hi <- as.matrix(B3i.pred %*% tcrossprod(Theta, B3i) %*% Vi.inv)\n ui <- tcrossprod(Theta, B3i) %*% Vi.inv %*% y.predi[sel.pred.obs]\n scores$u[i, ] <- as.vector(ui)\n y.pred[sel.pred] <- as.numeric(Hi %*% y.predi[sel.pred.obs]) + mu.predi # prediction\n temp <- as.matrix(B3i.pred %*% tcrossprod(Theta, B3i))\n if (length(sel.pred.obs) > 1) {\n se.pred[sel.pred] <- sqrt(diag(Vi.pred - temp %*% Vi.inv %*% t(temp)))\n }\n if (length(sel.pred.obs) == 1) {\n se.pred[sel.pred] <- sqrt(Vi.pred[1, 1] - Vi.inv[1, 1] * temp %*% t(temp))\n }\n\n ## predict scores\n if (calculate.scores == TRUE) {\n temp <- matrix(t(eigenfunctions), nrow = npc) %*% (as.matrix(Bnew) %*% ui) / sum(eigenfunctions[, 1]^2)\n temp <- as.matrix(temp)\n scores$scores[i, 1:npc] <- temp[, 1]\n }\n }\n }\n } ## if(is.null(newdata))\n if (is.null(newdata)) {\n y.pred <- NULL\n mu.pred <- NULL\n var.error.pred <- NULL\n Chat.diag.pred <- NULL\n se.pred <- NULL\n scores <- NULL\n }\n\n\n\n res <- list(\n newdata = newdata, W = W, y.pred = y.pred, Theta = Theta, argvals.new = tnew,\n mu.new = mu.new, Chat.new = Chat.new, var.error.new = var.error.new,\n Cor.new = Cor.new, eigenfunctions = eigenfunctions, eigenvalues = eigenvalues,\n Cor.raw.new = Cor.raw.new, Chat.raw.diag.new = Chat.raw.diag.new,\n scores = scores, calculate.scores = calculate.scores,\n mu.hat = fit_mean$fitted.values, var.error.hat = var.error.hat,\n mu.pred = mu.pred, var.error.pred = var.error.pred, Chat.diag.pred = Chat.diag.pred,\n se.pred = se.pred,\n fit_mean = fit_mean, lambda_mean = fit_mean$lambda,\n lambda = lambda, Gcv = Gcv, Lambda = Lambda, knots = knots, knots.option = knots.option, s = s, npc = npc, p = p, m = m,\n center = center, pve = pve, sigma2 = sigma2, r = r, DtD = DtD,\n U = Eigen.new$vectors[, 1:npc], G_invhalf = G_invhalf\n )\n\n class(res) <- \"face.sparse\"\n return(res)\n}", "meta": {"hexsha": "5ec55db85d61e571f66b0ce7f539a0cb4451ec2f", "size": 12643, "ext": "r", "lang": "R", "max_stars_repo_path": "R/face.sparse.inner.r", "max_stars_repo_name": "ZhuolinSong/Ftesting", "max_stars_repo_head_hexsha": "d0ecb36b44d377ab012a6325220f52110aeaf8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/face.sparse.inner.r", "max_issues_repo_name": "ZhuolinSong/Ftesting", "max_issues_repo_head_hexsha": "d0ecb36b44d377ab012a6325220f52110aeaf8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/face.sparse.inner.r", "max_forks_repo_name": "ZhuolinSong/Ftesting", "max_forks_repo_head_hexsha": "d0ecb36b44d377ab012a6325220f52110aeaf8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7529069767, "max_line_length": 127, "alphanum_fraction": 0.5706715178, "num_tokens": 4018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4954534997051107}} {"text": "#' Function for fast sampling of DP mixture of Linear regressions.\n#'\n#' This function takes in a training data.frame and optional testing data.frame and performs posterior sampling. It returns posterior mean regression line for training and test sets. The function is built for continuous outcomes.\n#' This differs from NDPMix in the following ways: NDPMix returns draws from the posterior *predictive* distribution of the outcome, whereas fDPMix() returns the regression line. This will have the same mean as the NDPMix predictions, but lower variance. Finally, the back-end computation is different, with regression line evaluation at point X being evaluated as a weighted average of cluster-specific regression evaluations at X. This is faster than NDPMix which takes a Monte Carlo appraoch: assign X to one of the cluster specific regressions, then draw a predicted outcome from that cluster's regression.\n#' \n#' We recommend normalizing continuous covariates and outcomes via the \\code{scale} function before running \\code{fDPMix}\n#' \n#' Please see \\url{https://stablemarkets.github.io/ChiRPsite/index.html} for examples and detailed model and parameter descriptions.\n#' \n#' @import stats\n#' \n#' @param d_train A \\code{data.frame} object with outcomes and model covariates/features. All features must be \\code{as.numeric} - either continuous or binary with binary variables coded using \\code{1} and \\code{0}. Categorical features are not supported. We recommend standardizing all continuous features. NA values are not allowed and each row should represent a single subject, longitudinal data is not supported.\n#' @param d_test Optional \\code{data.frame} object containing a test set of subjects containing all variables specifed in \\code{formula}. The same rules that apply to \\code{d_train} apply to \\code{d_test}.\n#' @param formula Specified in the usual way, e.g. for \\code{p=2} covariates, \\code{y ~ x1 + x2}. All covariates - continuous and binary - must be \\code{as.numeric} , with binary variables coded as \\code{1} or \\code{0}. We recommend standardizing all continuous features. NA values are not allowed and each row should represent a single subject, longitudinal data is not supported.\n#' @param burnin integer specifying number of burn-in MCMC draws. \n#' @param iter integer greater than \\code{burnin} specifying how many total MCMC draws to take.\n#' @param init_k Optional. integer specifying the initial number of clusters to kick off the MCMC sampler.\n#' @param phi_y Optional. Length two \\code{as.numeric} vector specifying the mean and variance of the inverse gamma prior on the outcome variance. By default, \\code{phi_y[1]} is set to \\code{var(y)}, where \\code{y} is the outcome, so the inverse gamma prior is centered around the marginal empirical variance. With prior variance given by \\code{phi_y[2]}. By default, \\code{phi_y[2]=.5*var(y)}. This value should be large to be \"flat\" and small to be \"tight\" around the marginal empirical variance. \n#' @param beta_prior_mean Optional. If there are \\code{p} covariates, a length \\code{p+1} \\code{as.numeric} vector specifying mean of the Gaussian prior on the outcome model's conditional mean parameter vector. Default is regression coefficients from running OLS on the outcomes.\n#' @param beta_prior_var Optional. If there are \\code{p} covariates, a length \\code{p+1} \\code{as.numeric} vector specifying variance of the Gaussian prior on the outcome model's conditional mean parameter vector. The full covarince of the prior is set to be diagonal. This vector specifies the diagonal enteries of this prior covariance. Default is estimated variances from running OLS on the outcome.\n#' @param beta_var_scale Optional. A multiplicative constant that scales \\code{beta_prior_var}. If you leave \\code{beta_prior_mean} and \\code{beta_prior_var} at their defaults, This constant toggles how wide new cluster parameters are dispersed around the observed data parameters.\n#' @param mu_scale Optional. An \\code{as.numeric}, scalar constant that controls how widely distributed new cluster continuous covariate means are distributed around the empirical covariate mean. Specifically, all continuous covariates are assumed to have Gaussian likelihood with Gaussian prior on their means. \\code{mu_scale=2} specifies that the variance of the Gaussian prior is twice as large as the empirical variance.\n#' @param tau_x Optional numeric length two vector for specifying the inverse gamma prior on each continuous covariate's prior variance. By default, the inverse gamma prior is centered around the empirical variance. \\code{tau_x[1]} is the positive constant that multiplies this empirical variance. A value of 1 indicates that the inverse gamma is centered around the empirical variance. A value of one half centers the inverse gamma prior around one half the empirical covariate variance. The second argument of \\code{tau_x} is the prior variance. For example, if\\code{tau_x[1]=1} and \\code{tau_x[2]=.001}, then the inverse gamma prior is tight around the empirical variance. If \\code{tau_x[2]=100}, then the inverse gamma prior for this covariate is widely distributed around the empirical variance.\n#' @return Returns \\code{predictions$train} and \\code{cluster_inds$train}. \\code{predictions$train} returns an \\code{nrow(d_train)} by \\code{iter - burnin} matrix of posterior predictions. \\code{cluster_inds$train} returns an \\code{nrow(d_train)} by \\code{iter - burnin} matrix of cluster assignment indicators, which can be input into the function \\code{cluster_assign_mode()} to compute posterior mode assignment. \\code{predictions$test} and \\code{cluster_inds$test} are returned if \\code{d_test} is specified.\n#' @keywords Dirichlet Process Gaussian\n#' @examples\n#' set.seed(1)\n#' \n#' N = 200\n#' x<-seq(1,10*pi, length.out = N) # confounder\n#' y<-rnorm(n = length(x), sin(.5*x), .07*x )\n#' d <- data.frame(x=x, y=y)\n#' d$x <- as.numeric(scale(d$x))\n#' d$y <- as.numeric(scale(d$y))\n#' \n#' plot(d$x,d$y, pch=20, xlim=c(min(d$x), max(d$x)+1 ), col='gray')\n#' \n#' d_test = data.frame(x=seq(max(d$x), max(d$x+1 ), .01 ))\n#' \n#' \n#' res = fDPMix(d_train = d, d_test = d_test, formula = y ~ x,\n#' iter=100, burnin=50, tau_x = c(.01, .001) )\n#' \n#' ## in-sample\n#' lines(d$x, rowMeans(res$train), col='steelblue')\n#' lines(d$x, apply(res$train,1,quantile,probs=.05) , col='steelblue', lty=2)\n#' lines(d$x, apply(res$train,1,quantile,probs=.90) , col='steelblue', lty=2)\n#' \n#' ## out of sample\n#' lines(d_test$x, rowMeans(res$test), col='pink')\n#' lines(d_test$x, apply(res$test,1,quantile,probs=.05) , col='pink', lty=2)\n#' lines(d_test$x, apply(res$test,1,quantile,probs=.90) , col='pink', lty=2)\n#' \n#' @export\nfDPMix<-function(d_train, formula, d_test=NULL, burnin=100,iter=1000, init_k=10, \n phi_y=NULL,\n beta_prior_mean=NULL, beta_prior_var=NULL,beta_var_scale=1000, \n mu_scale=1, tau_x =c(.05,2) ){\n\n ###------------------------------------------------------------------------###\n #### 0 - Parse User Inputs ####\n ###------------------------------------------------------------------------###\n \n \n # error checking user inputs\n if( missing(d_train) ){ stop(\"ERROR: must specify a training data.frame.\") }\n x <- all.vars(formula[[3]]) # covariate names\n y <- all.vars(formula[[2]]) # outcome name\n \n nparams <- length(x) + 1\n \n y <- d_train[,y]\n \n if(is.null(phi_y)){\n phi_y = c(var(y), 1/2*var(y))\n }\n \n func_args<-mget(names(formals()),sys.frame(sys.nframe()))\n error_check(func_args,'fDP')\n\n if(!is.null(d_test)){\n xt <- model.matrix(data=rbind(d_train[,x, drop=F], d_test[,x, drop=F]),\n object= as.formula(paste0('~ ',paste0(x, collapse = '+'))))\n nt <- nrow(xt)\n test_ind = c(rep(0, nrow(d_train)), rep(1, nrow(d_test)) )\n }else{\n xt <- model.matrix(data=d_train,\n object= as.formula(paste0('~ ',paste0(x, collapse = '+'))))\n nt <- nrow(xt)\n test_ind = c( rep(0, nrow(d_train)) )\n }\n \n x_type <- vector(length = length(x))\n for(v in 1:length(x)){\n if( length(unique(d_train[, x[v] ]))==2 ){\n x_type[v] <- 'binary'\n }else if(length(unique(d_train[,x[v]]))>2){\n x_type[v] <- 'numeric'\n }\n }\n\n store_l <- iter - burnin\n x_names <- x\n x <- model.matrix(data=d_train, object = formula )\n\n n<-nrow(x)\n\n xall_names <- x_names\n nparams_all <- length(xall_names)\n xall <- d_train[,xall_names]\n\n all_type_map <- c(x_type)\n names(all_type_map) <- c(x_names)\n xall_type <- all_type_map[as.character(xall_names)]\n\n xall_names_bin <- xall_names[xall_type == 'binary']\n xall_names_num <- xall_names[xall_type == 'numeric']\n\n # parse numeric versus binary variables for outcome model\n n_bin_p <- sum(x_type=='binary')\n n_num_p <- sum(x_type=='numeric')\n\n ## calibrate priors\n if(is.null(beta_prior_mean)){\n reg <- lm(data=d_train, formula = formula)\n beta_prior_mean <- reg$coefficients\n }\n\n if(is.null(beta_prior_var)){\n reg <- lm(data=d_train, formula = formula)\n beta_prior_var <- beta_var_scale*diag(vcov(reg))\n }\n\n ## test let phi_y[1] equal prior mean of inv gamma prior for phi\n ## let phi_y[2] equal the prior variance. \n ## then set phy_i[1] = sample outcome variance \n ## and let phi_y[3] control flattness around sample variance.\n \n g1 = (1/phi_y[2])*(phi_y[1]^2) + 2\n b1 = (g1 - 1)*phi_y[1]\n\n prior_means <- apply(x[,xall_names_num, drop=F], 2, mean)\n names(prior_means) <- xall_names_num\n\n prior_var <- mu_scale*apply(x[,xall_names_num, drop=F], 2, var)\n names(prior_var) <- xall_names_num\n \n g2 = (1/tau_x[2])*( tau_x[1]*apply(x[,xall_names_num, drop=F], 2, var) + 2)\n b2 = (g2 - 1)*tau_x[1]*apply(x[,xall_names_num, drop=F], 2, var)\n names(g2) <- xall_names_num\n names(b2) <- xall_names_num\n \n K <- init_k\n a <- 1\n\n ###------------------------------------------------------------------------###\n #### 1 - Create Shells for storing Gibbs Results ####\n ###------------------------------------------------------------------------###\n\n alpha <- numeric(length = store_l)\n\n curr_class_list <- 1:K\n class_names <- paste0('c',curr_class_list)\n\n c_shell<-matrix(NA, nrow=n, ncol=1) # shell for indicators\n\n class_shell <- matrix(NA, nrow=n, ncol=store_l)\n\n psi_shell <- matrix(NA, nrow= 1, ncol = K) # shell for Y's cond. var\n colnames(psi_shell) <- class_names\n\n beta_shell <- matrix(NA, nrow = nparams, ncol = K)\n colnames(beta_shell) <- class_names\n rownames(beta_shell) <- colnames(x)\n\n c_b_shell <- vector(mode = 'list', length = n_bin_p) # -1 for trt\n names(c_b_shell) <- xall_names_bin\n\n c_n_shell <- vector(mode = 'list', length = n_num_p)\n names(c_n_shell) <- xall_names_num\n\n for( p in xall_names_bin ){\n c_b_shell[[p]] <- matrix(NA, nrow = 1, ncol = K)\n\n c_b_shell[[p]][1,] <- rep(.5, K)\n\n colnames(c_b_shell[[p]]) <- class_names\n }\n\n for( p in xall_names_num ){\n c_n_shell[[p]] <- list(matrix(NA, nrow=1, ncol=K),\n matrix(NA, nrow=1, ncol=K))\n\n c_n_shell[[p]][[2]][1, ] <- rep(0, K)\n c_n_shell[[p]][[2]][1, ] <- rep(20^2, K)\n\n colnames(c_n_shell[[p]][[1]]) <- class_names\n colnames(c_n_shell[[p]][[2]]) <- class_names\n }\n\n c_b_new <- numeric(length = n_bin_p)\n names(c_b_new) <- xall_names_bin\n\n c_n_new <- matrix(NA, nrow = 2, ncol = n_num_p)\n colnames(c_n_new) <- xall_names_num\n \n if(is.null(d_test)){\n predictions <- vector(mode = 'list', length = 1)\n predictions[[1]] <- matrix(nrow = n, ncol = store_l)\n names(predictions) <- c('train')\n }else{\n predictions <- vector(mode = 'list', length = 2)\n predictions[[1]] <- matrix(nrow = n, ncol = store_l)\n predictions[[2]] <- matrix(nrow = nrow(d_test), ncol = store_l)\n names(predictions) <- c('train','test')\n }\n\n ###------------------------------------------------------------------------###\n #### 2 - Set Initial Values ####\n ###------------------------------------------------------------------------###\n\n # initially assign everyone to one of K clusters randomly with uniform prob\n c_shell[,1] <- sample(x = class_names, size = n,\n prob = rep(1/K,K), replace = T)\n\n beta_start <- matrix(0, nrow=nparams, ncol=K)\n colnames(beta_start) <- class_names\n\n for(k in class_names){\n beta_shell[,k] <- beta_prior_mean\n }\n\n for(p in xall_names_bin ){\n c_b_shell[[p]][1,] <- rep(1, K)\n }\n\n for(p in xall_names_num ){\n c_n_shell[[p]][[2]][ 1 , ] <- rep(0, K)\n c_n_shell[[p]][[2]][ 1 , ] <- rep(20^2, K)\n }\n\n psi_shell[1,1:K] <- rep(500000, K)\n\n ###------------------------------------------------------------------------###\n #### 3 - Gibbs Sampler ####\n ###------------------------------------------------------------------------###\n message_seq <- seq(2, iter, round(iter/20) )\n cat(paste0('Iteration ',2,' of ', iter,' (burn-in) \\n'))\n message_step <- (iter)/10\n for(i in 2:iter){\n\n ## print message to user\n if( i %% message_step == 1 ) cat(paste0('Iteration ',i,' of ',\n iter,\n ifelse(i>burnin,' (sampling) ',\n ' (burn-in)') ,\n '\\n'))\n\n # compute size of each existing cluster\n class_ind<-c_shell[,1]\n nvec<-table(factor(class_ind,levels = class_names) )\n\n ###----------------------------------------------------------------------###\n #### 3.1 - update Concentration Parameter ####\n ###----------------------------------------------------------------------###\n\n a_star <- rnorm(n = 1, mean = a, sd = 1)\n if(a_star>0){\n r_num <- cond_post_alpha(a_star, n, K, nvec)\n r_denom <- cond_post_alpha(a, n, K, nvec)\n r <- exp(r_num - r_denom)\n accept <- rbinom(1,1, min(r,1) )==1\n if(accept){ a <- a_star }\n }\n\n ###----------------------------------------------------------------------###\n #### 3.2 - update parameters conditional on classification ####\n ###----------------------------------------------------------------------###\n K <- length(unique(class_names))\n for(k in class_names){ # cycle through existing clusters - update parameters\n\n ck_ind <- class_ind == k\n\n y_ck <- y[ck_ind]\n\n x_ck <- x[ck_ind,, drop=FALSE]\n\n psi_shell[1, k]<-rcond_post_psi(beta = beta_shell[,k, drop=F],\n y = y_ck, xm = x_ck,\n g1 = g1, b1 = b1)\n\n beta_shell[,k] <- rcond_post_beta(y=y_ck,\n xm=x_ck,\n psi = psi_shell[1,k],\n beta_prior_mean = beta_prior_mean,\n beta_prior_var = beta_prior_var)\n\n for( p in xall_names_bin ){\n c_b_shell[[p]][1, k] <- rcond_post_mu_trt(x_ck = x_ck[, p])\n }\n\n for( p in xall_names_num ){\n c_n_shell[[p]][[1]][1,k] <- rcond_post_mu_x(x_ck = x_ck[, p],\n phi_x = c_n_shell[[p]][[2]][1,k],\n lambda = prior_means[p],\n tau = prior_var[p])\n\n c_n_shell[[p]][[2]][1,k] <- rcond_post_phi(mu_x = c_n_shell[[p]][[1]][1, k],\n x = x_ck[ , p],\n g2 = g2[p], b2 = b2[p])\n }\n\n }\n\n ###----------------------------------------------------------------------###\n #### 3.3 - update classification conditional on parameters ####\n ###----------------------------------------------------------------------###\n\n ## draw parameters for potentially new cluster from priors\n ### draw beta, phi, covariate parameters\n\n beta_new <- mvtnorm::rmvnorm(n = 1, mean = beta_prior_mean,\n sigma = diag(beta_prior_var) )\n psi_new <- invgamma::rinvgamma(n = 1, shape = g1, rate = b1)\n\n for(p in xall_names_bin){\n c_b_new[p] <- rbeta(n = 1, shape1 = 1, shape2 = 1)\n }\n\n for(p in xall_names_num){\n c_n_new[1, p] <- rnorm(n = 1, prior_means[p], sqrt(prior_var[p]) )\n c_n_new[2, p] <- invgamma::rinvgamma(n = 1, shape = g2[p], rate = b2[p])\n }\n\n name_new <- paste0('c', max(as.numeric(substr(class_names, 2,10))) + 1)\n\n ## compute post prob of membership to existing and new cluster,\n ## then classify\n \n uniq_clabs = colnames(beta_shell)\n \n weights <- class_update_train_fdp(n = n, K = length(class_names), alpha = a,\n name_new = name_new,\n uniq_clabs = uniq_clabs,\n clabs = class_ind,\n\n y = y, x = x,\n x_cat_shell = c_b_shell , x_num_shell = c_n_shell,\n\n ## col number of each covar...index with base 0\n cat_idx=xall_names_bin, num_idx=xall_names_num,\n\n beta_shell = beta_shell,\n psi_shell = psi_shell,\n\n beta_new=beta_new, psi_new=psi_new,\n cat_new = c_b_new, num_new=c_n_new)\n \n c_shell[,1] <- apply(weights, 1, FUN = sample,\n x=c(colnames(beta_shell), name_new), size=1, replace=T)\n \n \n if( i > burnin ){\n \n ###--------------------------------------------------------------------###\n #### 4.0 - Predictions on a Training and Test set & Store Results ####\n ###--------------------------------------------------------------------###\n\n test_pred <- post_mean_test_fdp(n=nt,K=K,alpha=a, name_new=name_new,\n uniq_clabs = uniq_clabs, x=xt,\n x_cat_shell=c_b_shell, x_num_shell=c_n_shell,\n cat_idx=xall_names_bin, num_idx=xall_names_num,\n cat_new=c_b_new, num_new=c_n_new,\n clabs=class_ind, beta_shell, beta_new)\n if( is.null(d_test) ){\n predictions[['train']][, i-burnin ] <- test_pred[test_ind==0] \n }else{\n predictions[['train']][, i-burnin ] <- test_pred[test_ind==0] \n predictions[['test']][, i-burnin ] <- test_pred[test_ind==1]\n }\n }\n\n ###----------------------------------------------------------------------###\n #### 5.0 - update shell dimensions as clusters die/ are born ####\n ###----------------------------------------------------------------------###\n\n new_class_names <- unique(c_shell[,1])\n K_new <- length(new_class_names)\n\n # Grow shells by adding labels/parameters of new clusters\n new_class_name <- setdiff(new_class_names, class_names)\n if(length(new_class_name)>0){ # new cluster was born\n\n beta_shell <- cbind(beta_shell, t(beta_new) )\n colnames(beta_shell)[K+1] <- new_class_name\n\n psi_shell <- cbind(psi_shell, psi_new)\n colnames(psi_shell)[K+1] <- new_class_name\n\n for(p in xall_names_bin ){\n c_b_shell[[p]] <- cbind( c_b_shell[[p]], c_b_new[p] )\n colnames(c_b_shell[[p]])[K+1] <- new_class_name\n }\n\n for(p in xall_names_num ){\n c_n_shell[[p]][[1]] <- cbind(c_n_shell[[p]][[1]], c_n_new[1, p])\n colnames(c_n_shell[[p]][[1]])[K+1] <- new_class_name\n\n c_n_shell[[p]][[2]] <- cbind(c_n_shell[[p]][[2]], c_n_new[2, p])\n colnames(c_n_shell[[p]][[2]])[K+1] <- new_class_name\n }\n }\n\n # shrink shells by deleting labels of clusters that have died.\n dead_classes <- setdiff(class_names, new_class_names)\n if(length(dead_classes) > 0){ # clusters have died\n beta_shell <- beta_shell[,! colnames(beta_shell) %in% dead_classes, drop=F]\n\n psi_shell <- psi_shell[, ! colnames(psi_shell) %in% dead_classes, drop=F]\n\n for(p in xall_names_bin){\n c_b_shell[[p]] <- c_b_shell[[p]][, ! colnames(c_b_shell[[p]]) %in% dead_classes, drop=F]\n }\n\n for(p in xall_names_num){\n c_n_shell[[p]][[1]] <- c_n_shell[[p]][[1]][, ! colnames(c_n_shell[[p]][[1]]) %in% dead_classes, drop=F]\n c_n_shell[[p]][[2]] <- c_n_shell[[p]][[2]][, ! colnames(c_n_shell[[p]][[2]]) %in% dead_classes, drop=F]\n }\n }\n\n K <- K_new\n class_names <- new_class_names\n\n }\n\n results <- predictions\n cat('Sampling Complete.')\n return(results)\n}\n", "meta": {"hexsha": "4e82e88c865f207e2a0fb0c2ac18ec67ca3a347c", "size": 20813, "ext": "r", "lang": "R", "max_stars_repo_path": "R/FDPMix.r", "max_stars_repo_name": "lagvier/ChiRP", "max_stars_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-02-26T03:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T09:19:11.000Z", "max_issues_repo_path": "R/FDPMix.r", "max_issues_repo_name": "lagvier/ChiRP", "max_issues_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-02-24T19:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-22T01:26:40.000Z", "max_forks_repo_path": "R/FDPMix.r", "max_forks_repo_name": "lagvier/ChiRP", "max_forks_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-03T19:25:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T18:03:51.000Z", "avg_line_length": 47.3022727273, "max_line_length": 800, "alphanum_fraction": 0.5695478787, "num_tokens": 5310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091197845649}} {"text": "#autor: Joao Sollari Lopes\n#local: INE, Lisboa\n#Rversion: 3.2.3\n#criado: 08.02.2019\n#modificado: 08.02.2019\n\n## 1. FUNCTIONS\n{\n# Key:\n# a - auxiliar\n# d - dataframe\n# f - file name\n# i - iterator\n# l - list\n# n - vector size\n# s - selected samples\n# t - title\n# v - vector\n# w - weights\n\n# Perform Partition around medoids clustering (wide format) [allow for specific number of partitions]\n# dst1 - distance matrix of variables to be analysed\n# kbest - specify number of partitions [if is.null(kbest) then calculate best number of partitions]\n# col1 - colors for points\n# border - add border to columns\n# f1 - output filename\n# main - title for plots\nplot_pam_v2 = function(dst1,kbest=NULL,col1=NULL,border=1,f1,main=NULL){\n library(\"cluster\")\n kmax <- dim(as.matrix(dst1))[1]-1\n asw <- rep(0,kmax)\n for(k in 2:kmax)\n asw[k] = pam(dst1,k)$silinfo$avg.width\n if(is.null(kbest)){\n kbest = which.max(asw)\n }\n pres1 = pam(dst1,kbest)\n d1 = cbind(1:kmax,asw)\n colnames(d1) = c(\"K\",\"Average silhouette width\")\n d2 = silhouette(pres1)\n f2 = paste(f1,\"_1.csv\",sep=\"\")\n f3 = paste(f1,\"_2.csv\",sep=\"\")\n f4 = paste(f1,\"_3.csv\",sep=\"\")\n write.table(d1,f2,quote=TRUE,sep=\",\",eol=\"\\n\",na=\"NA\",dec=\".\",\n col.names=TRUE,row.names=FALSE)\n write.table(pres1$clusinfo,f3,quote=TRUE,sep=\",\",eol=\"\\n\",na=\"NA\",dec=\".\",\n col.names=TRUE,row.names=FALSE)\n write.table(d2,f4,quote=TRUE,sep=\",\",eol=\"\\n\",na=\"NA\",dec=\".\",col.names=NA)\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f1,\".eps\",sep=\"\"),width=7.0,height=3.5,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\",\n family=\"Helvetica\")\n }else{\n tiff(file=paste(f1,\".tif\",sep=\"\"),units=\"in\",width=7.0,height=3.5,\n res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mfcol=c(1,2),mar=c(2.2,2.2,1.2,1.2),mgp=c(1.0,0.2,0.0),\n tcl=-0.2,cex=0.8,cex.lab=0.8,cex.axis=0.8,cex.main=0.9)\n plot(d1,type=\"h\",main=main)\n points(kbest,asw[kbest],col=\"red\",type= \"h\")\n plot(d2,main=main,sub=\"\",xlab=\"Silhouette width\",do.n.k=FALSE,\n border=border,do.clus.stat=FALSE,mgp=c(1.0,0.2,0.0),\n col=col1[rownames(d2)])\n par(oldpar)\n invisible(dev.off())\n }\n}\n\n# min-max transformation\n# y - vector\n# miny - minimum value to scale y\n# maxy - maximum value to scale y\nminmax = function(y,miny=NULL,maxy=NULL){\n if(is.null(miny)){miny = min(y)}\n if(is.null(maxy)){maxy = max(y)}\n return((y - miny)/(maxy - miny))\n}\n\n# Inverse min-max transformation\n# y - vector\n# miny - minimum value to scale y\n# maxy - maximum value to scale y\nminmax_inv = function(y,miny,maxy){\n return(y*(maxy - miny) + miny)\n}\n\n# Construct network (wide format) [allow for very many nodes]\n# dst1 - distance matrix of variables to be analysed\n# col1 - colors for points\n# vmode - network layout\n# edge_thr - threshold for edges to plot\n# edge_lwd - scale for edges\n# label_cex - size of node labels\n# f1 - output filename\n# main - title for plots\nplot_sna_v2 = function(dst1,col1=NULL,vmode=\"fruchtermanreingold\",edge_thr=0.80,\n edge_lwd=10,label_cex=0.8,f1,main=NULL){\n library(\"sna\")\n m1 = as.matrix(dst1)\n m1 = -m1 #invert distances\n mind = min(m1)\n maxd = max(m1)\n m1 = minmax(m1,mind,maxd) #min-max transformation\n m1[m1 < edge_thr] = NA #remove dist < thresh\n m1 = ((m1 - edge_thr))/(1 - edge_thr) #rescale dist\n edge_col = \"lightblue\"\n vertex_cex=1.5\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f1,\".eps\",sep=\"\"),width=7,height=10,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\",\n family=\"Helvetica\")\n }else{\n tiff(file=paste(f1,\".tif\",sep=\"\"),units=\"in\",width=7,height=10,\n res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mar=c(1.1,1.1,2.1,1.1),mgp=c(0,0,0),xpd=TRUE,cex.main=0.9)\n gplot(m1,gmode=\"graph\",displaylabels=TRUE,label.cex=label_cex,\n label.pos=5,mode=vmode,jitter=FALSE,main=paste(main,\n \" [minmax(-dist) > \",edge_thr,\"]\",sep=\"\"),vertex.cex=vertex_cex,\n vertex.col=col1[colnames(m1)],vertex.border=1,vertex.lty=1,\n vertices.last=TRUE,edge.lwd=edge_lwd,edge.lty=1,edge.lty.neg=1,\n edge.col=edge_col)\n par(oldpar)\n invisible(dev.off())\n }\n}\n\n# Summary statistics for network\n# dst1 - distance matrix of variables to be analysed\n# f1 - output filename\nanalyse_net = function(dst1,f1){\n library(\"sna\")\n m1 = as.matrix(dst1)\n m1 = -m1 #invert distances\n mind = min(m1)\n maxd = max(m1)\n m1 = (m1 - mind)/(maxd - mind) #min-max transformation\n f2 = paste(f1,\"_degree.csv\",sep=\"\")\n f3 = paste(f1,\"_eigen.csv\",sep=\"\")\n f4 = paste(f1,\"_dens.csv\",sep=\"\")\n #Degree - number of links incident upon a node\n net_deg = degree(m1,gmode=\"graph\")\n s1 = order(net_deg,decreasing=TRUE)\n d1 = cbind(rownames(m1)[s1],net_deg[s1])\n colnames(d1) = c(\"Node\",\"Degree\")\n write.table(d1,f2,row.names=FALSE,col.names=TRUE,sep=\",\",dec=\".\",eol=\"\\n\",\n na=\"NA\")\n #Eigenvector centrality - Influence of a node in a network\n net_evc = evcent(m1,gmode=\"graph\",use.eigen=TRUE)\n s1 = order(abs(net_evc),decreasing=TRUE)\n d1 = cbind(rownames(m1)[s1],net_evc[s1])\n colnames(d1) = c(\"Node\",\"Eigenvector\")\n write.table(d1,f3,row.names=FALSE,col.names=TRUE,sep=\",\",dec=\".\",eol=\"\\n\",\n na=\"NA\")\n #Density - the proportion of direct ties in a network relative to the total number possible\n nvert = nrow(m1)\n m2 = m1; diag(m2) = NA; m2[upper.tri(m2)] = NA\n nedge = sum(m2 != 0 & !is.na(m2))\n tedge = nties(m1,mode=\"graph\")\n dens = gden(m1,mode=\"graph\")\n d1 = data.frame(nvert,nedge,tedge,dens)\n write.table(d1,f4,row.names=FALSE,col.names=TRUE,sep=\",\",dec=\".\",eol=\"\\n\",\n na=\"NA\")\n}\n\n# Reduce number of predictors\n# dat1 - data frame of variables to be analysed (only predictors)\n# y - response variable\n# thr1 - upper threshold for correlation between predictors \n# thr2 - lower threshold for correlation between predictors and response variables [if thr2==NULL then reduces till maxsize]\n# thr3 - lower threshold for coefficient of variation [if thr3==NULL then reduces till maxsize]\n# thr4 - upper threshold for Variance Inflation Factor (VIF)\n# maxsize - maximum number of predictors [if maxsize==NULL then reduces till nsubj - 1]\n# f1 - output filename\nreduce_predictors_v2 = function(dat1,y,thr1=0.95,method=\"spearman\",thr2=NULL,\n thr3=NULL,thr4=10,maxsize=NULL,f1){\n# Note: Sqrt(R^2) for continuous variables is the correlation between variables. Sqrt(R^2)\n# for continuous and categorical variables is the correlation between observed and predicted\n# values.\n if(is.null(maxsize)){\n maxsize = nrow(dat1) - 1\n }\n if(is.null(thr2)){\n doStep2 = TRUE\n }else if(thr2 > 0){\n doStep2 = TRUE\n }else{\n doStep2 = FALSE\n }\n if(is.null(thr3)){\n doStep3 = TRUE\n }else if(thr3 > 0){\n doStep3 = TRUE\n }else{\n doStep3 = FALSE\n }\n write(\"Step1: Highly correlated between themselves\",file=f1,append=FALSE)\n if(thr1 < 1){ #remove variables highly correlated between themselves\n vars = colnames(dat1)\n rm_vars = c()\n for(i1 in vars){\n for(i2 in vars){\n if(i1 < i2 & !i1 %in% rm_vars){\n rres = cor(dat1[,i1],dat1[,i2],method=method,use=\"complete\")\n if(abs(rres) > thr1){\n write(paste(\" Remove \",i2,\" (r_\",i1,\" = \",round(rres,2),\n \")\",sep=\"\"),file=f1,append=TRUE)\n rm_vars = c(rm_vars,i2)\n }\n }\n }\n }\n dat1 = dat1[,!vars %in% rm_vars]\n }else{\n write(\"\",file=f1,append=TRUE)\n }\n write(\"Step2: Low correlated with response variable\",file=f1,append=TRUE)\n if(doStep2){ #remove variables with low correlation with dependent variable\n vars = colnames(dat1)\n if(is.factor(y)){\n y = as.character(y)\n }\n cors = apply(dat1,2,function(x){sqrt(summary(lm(y~x))$r.squared)})\n if(is.null(thr2)){\n n_rm = ncol(dat1) - maxsize #n_rm, so that, nvars = nsubj - 1\n if(n_rm <= 0){\n thr2 = 0.00\n }else{\n thr2 = sort(cors)[n_rm]\n }\n }\n rm_vars = cors <= thr2\n if(sum(rm_vars) == 0){\n write(\"\",file=f1,append=TRUE)\n }else{\n dat1 = dat1[,!rm_vars]\n tmp = cbind(vars[rm_vars],cors[rm_vars])\n tmp = apply(tmp,1,function(x){paste(\" Remove \",x[1],\" (r = \",\n round(as.numeric(x[2]),2),\")\",sep=\"\")})\n write(tmp,file=f1,append=TRUE)\n }\n }else{\n write(\"\",file=f1,append=TRUE)\n }\n write(\"Step3: Variables with low variation\",file=f1,append=TRUE)\n if(doStep3){ #remove variables with low variation\n vars = colnames(dat1)\n sds = apply(dat1,2,sd,na.rm=TRUE)\n means = apply(dat1,2,mean,na.rm=TRUE)\n if(is.null(thr3)){\n n_rm = ncol(dat1) - maxsize #n_rm, so that, nvars = nsubj - 1\n if(n_rm <= 0){\n thr3 = 0.00\n }else{\n thr3 = sort(sds/means)[n_rm]\n }\n }\n rm_vars = sds/means <= thr3\n if(sum(rm_vars) == 0){\n write(\"\",file=f1,append=TRUE)\n }else{\n dat1 = dat1[,!rm_vars]\n tmp = cbind(vars[rm_vars],sds/means[rm_vars])\n tmp = apply(tmp,1,function(x){paste(\" Remove \",x[1],\" (r = \",\n round(as.numeric(x[2]),2),\")\",sep=\"\")})\n write(tmp,file=f1,append=TRUE)\n }\n }else{\n write(\"\",file=f1,append=TRUE)\n }\n write(\"Step4: Variables with low VIF\",file=f1,append=TRUE)\n if(thr4 < Inf){ #remove variables using VIF (reduce multicollinearity)\n vars = colnames(dat1)\n keep_vars = stepwise_vif(dat1,thresh=thr4,trace=FALSE)\n if(sum(!keep_vars) == 0){\n write(\"\",file=f1,append=TRUE)\n }else{\n dat1 = dat1[,keep_vars]\n tmp = paste(\" Remove\",vars[!vars %in% keep_vars])\n write(tmp,file=f1,append=TRUE)\n }\n }else{\n write(\"\",file=f1,append=TRUE)\n }\n return(dat1)\n}\n \n# Stepwise Variance Inflation Factors (VIF) selection to reduce collinearity\n# [From \"Marcus W Beck\" in https://gist.github.com/fawda123/4717702#file-vif_fun-r]\n# in_frame - data frame of variables to be analyzed\n# thresh - threshold for VIF\n# trace - print output of each iteration\nstepwise_vif = function(in_frame,thresh=10,trace=TRUE){\n if(class(in_frame) != 'data.frame'){\n in_frame = data.frame(in_frame)\n }\n #get initial vif value for all comparisons of variables\n var_names = names(in_frame)\n vif_init = vif(in_frame)\n vif_max = max(as.numeric(vif_init),na.rm=TRUE)\n if(vif_max < thresh){\n if(trace==TRUE){\n print(data.frame(vif_init))\n cat('\\n')\n cat(paste('All variables have VIF < ', thresh,', max VIF ',\n round(vif_max,2), sep=''),'\\n\\n')\n }\n return(var_names)\n }else{\n in_dat = in_frame\n #backwards selection of explanatory variables, stops when all VIF values are below 'thresh'\n while(vif_max >= thresh){\n var_names = names(in_dat)\n vif_vals = vif(in_dat)\n imax = which(vif_vals == max(as.numeric(vif_vals),na.rm=TRUE))[1]\n vif_max = as.numeric(vif_vals[imax])\n if(vif_max < thresh){\n break\n }\n if(trace==TRUE){\n print(data.frame(vif_vals))\n cat('\\n')\n cat('removed: ',names(vif_vals)[imax],vif_max,'\\n\\n')\n flush.console()\n }\n in_dat = in_dat[,!names(in_dat) %in% names(vif_vals)[imax]]\n }\n return(names(in_dat))\n }\n}\n\n# Calculate Variance Inflation Factors (VIF) at a model-level\n# [based on HH::vif()]\n# dat1 - data frame of variables to be analysed (only predictors)\nvif = function(dat1){\n#see https://en.wikipedia.org/wiki/Variance_inflation_factor\n#see car::vif() for calculation of VIF at variable-level\n#see HH::vif() for calculation of VIF at model-level\n#see faraway::vif() for calculation of VIF at model-level\n#see fmsb::vif() for calculation of VIF at model-level\n# Note: VIF can be defined at variable-level (using the partial R^2) and at the model\n# level (using R^2, i.e. coefficient of determination).\n vars = colnames(dat1)\n nvars = length(vars)\n r2 = vector(\"numeric\",length=nvars)\n names(r2) = vars\n for(i1 in 1:nvars){\n tmp = lm(dat1[,i1] ~ data.matrix(dat1[,-i1]),na.action=\"na.omit\")\n r2[i1] = 1/(1 - summary(tmp)$r.squared)\n }\n return(r2)\n}\n\n# Automatic model selection for multiple linear regression using General LM [simplified version]\n# dat1 - data frame of independet variables (predictors)\n# resp - dependent variable (response variable)\n# maxs1 - maximum number of terms in candidate models {\"hard\"}\n# crit - information criteria to use {\"aic\",\"aicc\",\"bic\",\"qaic\",\"qaicc\"}\n# thrs - threshold for nmods to perform exhaustive search\n# popsize - Population size\n# mutrate - Per locus (i.e. per term) mutation rate, [0,1]\n# sexrate - Sexual reproduction rate, [0,1]\n# imm - Immigration rate, [0,1]\n# deltaM - Stop Rule: change in mean IC\n# deltaB - Stop Rule: change in best IC\n# conseq - Stop Rule: times with no improvement\n# f1 - output filename\nmod_select_lm_v2 = function(dat1,resp,maxs1=\"hard\",crit=\"aicc\",thrs=100000,\n popsize=100,mutrate=0.001,sexrate=0.1,imm=0.3,deltaM=0.05,deltaB=0.05,\n conseq=5,nreps=2,f1){\n library(\"glmulti\")\n d1 = data.frame(resp,dat1)\n colnames(d1) = sapply(colnames(d1),function(x){gsub(\"[-|.]\",\"_\",x)}) #remove symbols used in \"formulas\"\n nvars = ncol(d1)\n vars = colnames(d1)\n hmax = (nrow(d1) - 1) - 3 #hard max (i.e. nparam = nsubj - 3)\n maxs1 = min(maxs1,hmax) #prevent maxs1 > hard max\n nmods = sum(sapply(1:maxs1,function(x){choose(nvars-1,x)})) + 1\n if(nmods < thrs){ #exhaustive search\n res2 = glmulti(y=vars[1],xr=vars[2:nvars],data=d1,level=1,maxsize=maxs1,\n method=\"h\",crit=crit,plotty=FALSE,report=FALSE,includeobjects=TRUE,\n marginality=FALSE,model=TRUE,fitfunction=\"lm\")\n }else{ #genetic algorithm\n res1 = vector(\"list\",length=nreps)\n for(i1 in 1:nreps){\n f2 = paste(f1,\"_rep\",i1,\"_1\",sep=\"\")\n res1[[i1]] = glmulti(y=vars[1],xr=vars[2:nvars],data=d1,level=1,\n maxsize=maxs1,method=\"g\",crit=crit,confsetsize=100,plotty=FALSE,\n report=FALSE,name=f2,includeobjects=TRUE,marginality=FALSE,\n model=TRUE,popsize=popsize,mutrate=mutrate,sexrate=sexrate,\n imm=imm,deltaM=deltaM,deltaB=deltaB,conseq=conseq,\n fitfunction=\"lm\")\n }\n if(nreps > 1){\n res2 = glmulti::consensus(xs=res1,confsetsize=100)\n }else{\n res2 = res1\n }\n }\n t1 = weightable(res2)\n t2 = t1[t1[,crit] <= min(t1[,crit]) + 2,]\n t3 = coef(res2)\n f2 = paste(f1,\".log\",sep=\"\")\n f3 = paste(f1,\"_1.csv\",sep=\"\")\n f4 = paste(f1,\"_2.csv\",sep=\"\")\n capture.output(print(res2),file=f2,append=FALSE,type=\"output\")\n write.table(t2,file=f3,sep=\",\",row.names=TRUE,col.names=NA)\n write.table(t3,file=f4,sep=\",\",row.names=TRUE,col.names=NA)\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f1,\".eps\",sep=\"\"),width=7.0,height=10,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\",\n family=\"Helvetica\")\n }else{\n tiff(file=paste(f1,\".tif\",sep=\"\"),units=\"in\",width=7.0,height=10,\n res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mfcol=c(3,1),mar=c(2.2,2.2,1.2,1.2),mgp=c(1.0,0.2,0.0),\n oma=c(0,0,0,0),tcl=-0.2,cex=0.8,cex.lab=0.8,cex.axis=0.8,cex.main=0.9)\n par(mar=c(2.2,10.2,1.2,1.2))\n plot(res2,type=\"s\",cex.names=0.6)\n par(mar=c(2.2,2.2,1.2,1.2))\n plot(res2,type=\"p\")\n plot(res2,type=\"w\")\n par(oldpar)\n invisible(dev.off())\n }\n a1 = formula(res2@objects[[1]]$terms) #formula\n a2 = res2@objects[[1]]$model #data\n l1 = list(a1,a2)\n names(l1) = c(\"formula\",\"data\")\n return(l1)\n}\n\n# Fit multiple linear regression using General LS\n# form1 - formula of the model to fit\n# dat1 - data frame of variables to fit \n# f1 - output filename\n# main - title for plots\nfit_lm = function(form1,dat1,f1,main){\n#see https://en.wikipedia.org/wiki/General_linear_model\n# Note: Multiple linear regression assumptions:\n# 1. The error terms need to be independent.\n# 2. The error variance is homoskedastic.\n# 3. The errors are normally distributed with mean = 0\n# 4. The independent variables should be independent from each other (i.e. little or no multicollinearity).\n# 5. Linearity between independent variables and dependent variable.\n# 6. Large sample sizes (i.e. 10-30 cases per parameter).\n library(\"car\")\n fit1 = lm(form1,data=dat1)\n sfit1 = summary(fit1)\n t1 = Anova(fit1,type=\"II\")\n f2 = paste(f1,\".log\",sep=\"\")\n f3 = paste(f1,\".csv\",sep=\"\")\n capture.output(print(sfit1),file=f2,append=FALSE,type=\"output\")\n write.table(t1,file=f3,sep=\",\",row.names=TRUE,col.names=NA)\n vars = all.vars(form1)\n y = dat1[,vars[1]]\n f = fit1$fitted.values\n r = fit1$residuals\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f1,\".eps\",sep=\"\"),width=7.0,height=7.0,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\",\n family=\"Helvetica\")\n }else{\n tiff(file=paste(f1,\".tif\",sep=\"\"),units=\"in\",width=7.0,height=7.0,\n res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mfcol=c(2,2),mar=c(2.2,2.2,1.2,1.2),mgp=c(1.0,0.2,0.0),\n tcl=-0.2,cex=0.8,cex.lab=0.8,cex.axis=0.8,cex.main=0.9)\n qqnorm(r,col=4); qqline(r) #wg-err_norm: qqplot \n plot(f,sqrt(abs(r)),xlab=\"Fitted\",ylab=\"sqrt(abs(Residuals))\",col=4)\n abline(h=0,lty=2) #wg-err_var: scatterplot\n hist(r,freq=FALSE,main=\"\",col=4,xlab=\"Residuals\") #wg-err_norm: histogram\n plot(f,y,xlab=\"Fitted values\",ylab=\"Values\",main=main,col=4)\n abline(c(0,1),lty=2) #goodness-of-fit: scatterplot\n par(oldpar)\n invisible(dev.off())\n }\n}\n\n# Fits multiple regression via neural networks\n# [adapted from nnet::nnet.formula()]\n# formula - formula of the regression\n# data - data frame of variables to fit\n# weights - weights for each subject\n# ... - arguments for \"nnet\" {e.g. size, decay, maxit, abstol, reltol, Hess, trace}\n# na.action - usual model parameter\n# contrast - usual model parameter\nmultivar = function(formula,data,weights,...,subset,na.action,contrasts=NULL){\n m = match.call(expand.dots=FALSE)\n if(is.matrix(eval.parent(m$data))){\n m$data <- as.data.frame(data)\n }\n m$... = m$contrasts = NULL\n m[[1L]] = quote(stats::model.frame)\n m = eval.parent(m)\n Terms = attr(m, \"terms\")\n x = model.matrix(Terms,m,contrasts)\n cons = attr(x,\"contrast\")\n xint = match(\"(Intercept)\",colnames(x),nomatch = 0L)\n if(xint > 0L){\n x = x[,-xint,drop=FALSE]\n }\n if(attr(Terms,\"intercept\") == 0){\n Qr = qr(x)\n }else{\n Qr = qr(cbind(1,x))\n colnames(Qr$qr) = c(\"(Intercept)\",colnames(Qr$qr)[-1])\n }\n w = model.weights(m)\n if(length(w) == 0L){\n w = rep(1,nrow(x))\n }\n y = model.response(m)\n miny = min(y)\n maxy = max(y)\n y_tr = minmax(y,miny,maxy)\n res = nnet.default(x,y_tr,w,linout=TRUE,...)\n res$terms = Terms\n res$coefnames = colnames(x)\n res$call = match.call()\n res$na.action = attr(m,\"na.action\")\n res$contrasts = cons\n res$call$formula = formula\n res$xlevels = .getXlevels(Terms, m)\n if(0){\n res$tr.fitted.values = matrix(minmax_inv(res$fitted.values[,1],\n miny,maxy))\n res$tr.residuals = matrix(y - res$tr.fitted.values)\n }else{\n res$tr.fitted.values = res$fitted.values\n res$tr.residuals = res$residuals\n res$fitted.values = matrix(minmax_inv(res$fitted.values[,1],miny,maxy))\n res$residuals = matrix(y - res$fitted.values)\n }\n res$deviance = sum(res$residuals^2)\n res$qr = Qr\n res$rank = res$qr$rank\n res$df.residual = length(y) - res$rank \n res$model = m\n class(res) = c(\"multivar\",\"nnet.formula\",\"nnet\")\n res\n}\n\n# Create logLik() function for \"multivar\" objects\n# [adapted from stats:::logLik.lm()]\n# object - \"multivar\" object\nlogLik.multivar = function(object,...){\n res = object$residuals\n p = object$rank\n N = length(res)\n if(is.null(w <- object$weights)){\n w = rep.int(1,N)\n }else{\n excl = w == 0\n if(any(excl)){\n res = res[!excl]\n N = length(res)\n w = w[!excl]\n }\n }\n val = 0.5*(sum(log(w)) - N*(log(2*pi) + 1 - log(N) + log(sum(w*res^2))))\n attr(val, \"nobs\") = N\n attr(val, \"df\") = p + 1\n class(val) = \"logLik\"\n val\n}\n\n# Create nobs() function for \"multivar\" objects\n# [adapted from stats:::nobs.lm()]\n# object - \"multivar\" object\nnobs.multivar = function(object){\n if(!is.null(w <- object$weights)){\n sum(w != 0)\n }else{\n nrow(object$residuals)\n }\n}\n\n# Create summary() function for \"multivar\" objects\n# [adapted from stats:::summary.lm()]\n# object - \"multivar\" object\nsummary_multivar = function(object){\n z = object\n p = z$rank\n rdf = z$df.residual\n if(p == 0){\n r = z$residuals\n n = length(r)\n w = z$weights\n if(is.null(w)){\n rss = sum(r^2)\n }else{\n rss = sum(w*r^2)\n r = sqrt(w)*r\n }\n resvar = rss/rdf\n ans = z[c(\"call\", \"terms\", if (!is.null(z$weights)) \"weights\")]\n ans$residuals = r\n ans$df = n\n ans$sigma = sqrt(resvar)\n ans$r.squared = ans$adj.r.squared <- 0\n return(ans)\n }\n Qr = object$qr\n n = nrow(Qr$qr)\n r = z$residuals\n f = z$fitted.values\n w = z$weights\n if(is.null(w)){\n mss = if(attr(z$terms, \"intercept\")){sum((f - mean(f))^2)}else{sum(f^2)}\n rss = sum(r^2)\n }else{\n mss = if(attr(z$terms, \"intercept\")){m = sum(w * f/sum(w));\n sum(w*(f - m)^2)}else{sum(w*f^2)}\n rss = sum(w*r^2)\n r = sqrt(w)*r\n }\n resvar = rss/rdf\n if(is.finite(resvar) && resvar < (mean(f)^2 + var(f))*1e-30) \n warning(\"essentially perfect fit: summary may be unreliable\")\n p1 = 1L:p\n ans = z[c(\"call\", \"terms\",if(!is.null(z$weights)){\"weights\"})]\n ans$residuals = r\n ans$sigma = sqrt(resvar)\n ans$df = c(p,rdf,ncol(Qr$qr))\n if(p != attr(z$terms,\"intercept\")){\n df.int = if(attr(z$terms, \"intercept\")){1L}else{0L}\n ans$r.squared = mss/(mss + rss)\n ans$adj.r.squared = 1 - (1 - ans$r.squared)*((n - df.int)/rdf)\n ans$fstatistic = c(value=(mss/(p - df.int))/resvar,numdf=p - df.int,\n dendf=rdf)\n }else{\n ans$r.squared = ans$adj.r.squared = 0\n }\n if(!is.null(z$na.action)){\n ans$na.action = z$na.action\n }\n ans\n}\n\n# Fit multiple regression using ANN [add finer tune for ANN]\n# form1 - formula of the model to fit\n# dat1 - data frame of variables to fit \n# nn_size - number of units in the hidden layer [ANN]\n# nn_decay - parameter for weight decay [ANN]\n# nn_maxit - maximum number of iterations [ANN]\n# nn_abstol - absolute fit criterion [ANN]\n# nn_reltol - relative fit criterion [ANN]\n# f1 - output filename\n# main - title for plots\nfit_nnet_v2 = function(form1,dat1,nn_size=10,nn_decay=0.01,nn_maxit=1000,\n nn_abstol=1e-4,nn_reltol=1e-8,f1,main){\n#see https://en.wikipedia.org/wiki/Artificial_neural_network\n# Note: Multiple regression assumptions:\n# 1. The error terms need to be independent.\n# 2. The independent variables should be independent from each other (i.e. little or no multicollinearity).\n# 3. Large sample sizes (i.e. 10-30 cases per parameter).\n# Note: Neuronal network caveats\n# 1. optimal number of hidden units is problem specific (risk of overfitting)\n library(\"nnet\")\n library(\"caret\")\n library(\"NeuralNetTools\")\n vars = all.vars(form1)\n if(is.null(nn_size) || is.null(nn_decay)){\n if(!is.null(nn_size)){\n gr_size = nn_size\n }else{\n gr_size = c(1,3*(1:10))\n }\n if(!is.null(nn_decay)){\n gr_decay = nn_decay\n }else{\n gr_decay = 1*10^(-(1:9))\n }\n y = as.matrix(dat1[,vars[1]])\n miny = min(y)\n maxy = max(y)\n dat2 = dat1\n dat2[,vars[1]] = minmax(y,miny,maxy)\n grid1 = expand.grid(size=gr_size,decay=gr_decay)\n train1 = train(form1,data=dat2,method=\"nnet\",maxit=nn_maxit,\n abstol=nn_abstol,reltol=nn_reltol,linout=TRUE,trace=FALSE,\n trControl=trainControl(method=\"boot\",number=100),tuneGrid=grid1,\n metric=\"RMSE\")\n nn_size = train1$bestTune[1,1]\n nn_decay = train1$bestTune[1,2]\n }\n fit1 = multivar(form1,dat1,size=nn_size,decay=nn_decay,maxit=nn_maxit,\n abstol=nn_abstol,reltol=nn_reltol,trace=FALSE)\n sfit1 = summary(fit1)\n sfit2 = summary_multivar(fit1)\n if(length(vars) > 1){\n t1 = olden(fit1,bar_plot=FALSE)\n }\n f2 = paste(f1,\"_1.log\",sep=\"\")\n f3 = paste(f1,\"_2.log\",sep=\"\")\n f4 = paste(f1,\"_3.log\",sep=\"\")\n f5 = paste(f1,\".csv\",sep=\"\")\n capture.output(print(sfit1),file=f2,append=FALSE,type=\"output\")\n capture.output(stats:::print.summary.lm(sfit2),file=f3,append=FALSE,\n type=\"output\")\n if(exists(\"train1\")){\n capture.output(train1,file=f4,append=FALSE,type=\"output\")\n }\n if(length(vars) > 1){\n write.table(t1,file=f5,sep=\",\",row.names=TRUE,col.names=NA)\n }\n f2 = paste(f1,\"_1\",sep=\"\")\n y = dat1[,vars[1]]\n f = fit1$fitted.values\n r = fit1$residuals\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f2,\".eps\",sep=\"\"),width=7.0,height=7.0,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\",\n family=\"Helvetica\")\n }else{\n tiff(file=paste(f2,\".tif\",sep=\"\"),units=\"in\",width=7.0,height=7.0,\n res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mfcol=c(2,2),mar=c(2.2,2.2,1.2,1.2),mgp=c(1.0,0.2,0.0),\n tcl=-0.2,cex=0.8,cex.lab=0.8,cex.axis=0.8,cex.main=0.9)\n\n qqnorm(r,col=4); qqline(r) #wg-err_norm: qqplot \n plot(f,sqrt(abs(r)),xlab=\"Fitted\",ylab=\"sqrt(abs(Residuals))\",col=4)\n abline(h=0,lty=2) #wg-err_var: scatterplot\n hist(r,freq=FALSE,main=\"\",col=4,xlab=\"Residuals\") #wg-err_norm: histogram\n plot(f,y,xlab=\"Fitted values\",ylab=\"Values\",main=main,col=4)\n abline(c(0,1),lty=2) #goodness-of-fit: scatterplot\n par(oldpar)\n invisible(dev.off())\n }\n if(length(vars) > 1){\n f2 = paste(f1,\"_2\",sep=\"\")\n for(i1 in c(\"eps\",\"tiff\")){\n if(i1 == \"eps\"){\n postscript(file=paste(f2,\".eps\",sep=\"\"),width=7.0,height=7.0,\n colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,\n paper=\"special\",family=\"Helvetica\")\n }else{\n tiff(file=paste(f2,\".tif\",sep=\"\"),units=\"in\",width=7.0,\n height=7.0,res=300,compression=\"lzw\",family=\"sans\")\n }\n oldpar = par(mar=c(1.1,1.1,2.1,1.1),mgp=c(0,0,0),xpd=TRUE,\n cex.main=0.9)\n plotnet(fit1,cex_val=0.7,circle_cex=3)\n par(oldpar)\n invisible(dev.off())\n }\n }\n}\n\n}\n\n", "meta": {"hexsha": "089492b4021a972296f13e28faa2fb0f01bb5003", "size": 28457, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/misc_v2.3.r", "max_stars_repo_name": "jsollari/DAA2019", "max_stars_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/misc_v2.3.r", "max_issues_repo_name": "jsollari/DAA2019", "max_issues_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/misc_v2.3.r", "max_forks_repo_name": "jsollari/DAA2019", "max_forks_repo_head_hexsha": "6b4e0764f6570bef4652a73a773f3b9ee8af92da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T11:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T11:11:10.000Z", "avg_line_length": 37.4434210526, "max_line_length": 124, "alphanum_fraction": 0.580208736, "num_tokens": 8900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.4950880200006023}} {"text": "#---\n#title: \"calculating plant density from survey done in 2020 on transect A\"\n#author: \"Tal Dahan-Meir\"\n#date: \"25/08/2021\"\n#---\n\nrequire(geosphere)\n\ncsv = read.csv(\"data/2020_plant_densities.csv\",colClasses=\"character\")\n\n#get dists between plants to next plants and add to data.frame\nnPlants_a = nrow(csv)\ncoordinates_next_plants = data.frame(\"altitude_nextPlant\" = rep(NA,nPlants_a),\n \"latitude_nextPlant\" = rep(NA,nPlants_a),\n \"longitude_nextPlant\" = rep(NA,nPlants_a))\nfor (i in 1:(nPlants_a-1)){\n coordinates_next_plants[i,] = csv[i+1,c(\"altitude\",\"latitude\",\"longitude\")]\n}\ncsv_distances = cbind (csv,coordinates_next_plants)\ncsv_distances$dist_meters = c( apply(csv_distances[1 : (nPlants_a-1), ], 1, function(tt) { distm(x = c(as.numeric(tt[6]), as.numeric(tt[5]) ), y = c(as.numeric(tt[9]), as.numeric(tt[8]) ) )} ), \"NA\")\ncsv_distances$position_meters = as.numeric(c( 0 ,cumsum (csv_distances[1:(nPlants_a-1), \"dist_meters\"] )))\ncsv_distances$plantsPerMeter = as.numeric(csv_distances$plants_until_next_point) / as.numeric(csv_distances$dist_meters)\ncsv_distances$plantsinMM_divided_by_pi = as.numeric(csv_distances$plants_in_1MM2) / pi\ncsv_distances$plantsinM_combined = as.numeric(csv_distances$plantsinMM_divided_by_pi)+as.numeric(csv_distances$plantsPerMeter)\n\nhead(csv_distances)\n\n\npdf(\"transect_a_density_2020.pdf\", height=8, width=22)\nplot (as.numeric(csv_distances$position_meters),\n as.numeric(csv_distances$plantsinMM_divided_by_pi),\n main = \"Density transect A\",\n cex.main=2,\n pch = 19,\n cex = 0.2,\n cex.lab = 1.5,\n cex.axis=1.4,\n ylim=c(0,25),\n xlim=c(0,320),\n col=\"black\",\n xlab = \"position (M)\",\n ylab = \"spikes per M^2\")\n\napply(csv_distances,1, function(xx){\n rect(xleft = as.numeric(xx[11]),\n ybottom = 0,\n xright = as.numeric(xx[11])+as.numeric(xx[10]),\n ytop = as.numeric(xx[12])/2,\n col=\"#00ABA920\",\n border= NA)} )\nnames_height_bonus = 0.5\napply(csv_distances,1, function(xx){\n text(x = as.numeric(xx[11]),\n y = as.numeric(xx[13])+names_height_bonus,\n as.character(xx[1]),\n col=\"black\",\n cex=1)} )\ndev.off()\n\n###calculate mean density in m^2###\n#(sum of plants around peg divided by pi - to transform from circle to ^2)+(sum of plants until next point divided by 2 - to transform from 2 meters to 1 meter width)/(transect length)\n(sum(as.numeric(csv_distances$plantsinMM_divided_by_pi))+(sum(as.numeric(csv_distances$plants_until_next_point),na.rm=T)/2))/max(csv_distances$position_meters)\n", "meta": {"hexsha": "dabcc0244f512d3ab8126ed915c587b5427e8cc5", "size": 2606, "ext": "r", "lang": "R", "max_stars_repo_path": "data_analysis/plant_density_2020.r", "max_stars_repo_name": "ellisztamas/Ammiad-1", "max_stars_repo_head_hexsha": "158d4f1ce8f0b6b4845ac477a377bd9d755cf945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data_analysis/plant_density_2020.r", "max_issues_repo_name": "ellisztamas/Ammiad-1", "max_issues_repo_head_hexsha": "158d4f1ce8f0b6b4845ac477a377bd9d755cf945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data_analysis/plant_density_2020.r", "max_forks_repo_name": "ellisztamas/Ammiad-1", "max_forks_repo_head_hexsha": "158d4f1ce8f0b6b4845ac477a377bd9d755cf945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T09:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:00:49.000Z", "avg_line_length": 41.3650793651, "max_line_length": 199, "alphanum_fraction": 0.6830391404, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49474391629627673}} {"text": "# James Rekow\r\n\r\nsubgroupVecMatcher = function(subgroupVec1, subgroupVec2){\r\n \r\n # ARGS: subgroupVec1 - a numeric vector whose ith element is the subgroup to which sample i belongs,\r\n # where sample i is an element of a set A\r\n # subgroupVec2 - another vector of the same form as subgroupVec1, corresponding to the same set A\r\n #\r\n # RETURNS: subgroupVec2Ordered - subgroupVec2 with the values permuted so as to minimize the number of\r\n # differences between subgroupVec1 and subgroupVec2\r\n \r\n # TODO: add a method argument with two options, Jaccard index, and misallocated elements\r\n \r\n library(gtools)\r\n\r\n # number of subgroups in subgroupVec2\r\n numSubgroups2 = max(subgroupVec2)\r\n \r\n # list which indices correspond to each subgroup\r\n subgroupIxList = lapply(as.list(1:numSubgroups2), function(ii) as.numeric(subgroupVec2 == ii))\r\n \r\n # create a matrix whose rows are the permutations of 1:numSubgroups 2\r\n permutationMat = permutations(n = numSubgroups2, r = numSubgroups2)\r\n \r\n createSubgroupVec = function(perm){\r\n \r\n # ARGS: perm - numeric vector that is a permutation of 1:numSubgroups2\r\n #\r\n # RETURNS: permSubgroupVec2 - subgroup created by permuting the values of subgroupVec2 according to\r\n # perm\r\n \r\n # compute the elements of the permutation in each subgroup\r\n permSubgroupVec2List = lapply(as.list(1:numSubgroups2), function(ii) perm[ii] * subgroupIxList[[ii]])\r\n \r\n # combine values to create the permuted subgroup vector\r\n permSubgroupVec2 = Reduce(\"+\", permSubgroupVec2List)\r\n \r\n return(permSubgroupVec2)\r\n \r\n } # end createSubgroupVec function\r\n \r\n computeSubgroupDiff = function(perm){\r\n \r\n # ARGS: perm - numeric vector that is a permutation of 1:numSubgroups2\r\n #\r\n # RETURNS: subgroupDiff - number of differences between subgroupVec1 and the given permutation\r\n # of the values of subgroupVec2. All of the values of i in subgroupVec2\r\n # are replaced by perm[i]\r\n \r\n # create subgroup corresponding to input permutation of values of subgroupVec2\r\n permSubgroupVec2 = createSubgroupVec(perm)\r\n \r\n # compute number of differences between the given permutation of values of subgroupVec2 and\r\n # subgroupVec1\r\n subgroupDiff = sum(subgroupVec1 != permSubgroupVec2)\r\n \r\n return(subgroupDiff)\r\n \r\n } # end computeSubgroupDiff function\r\n \r\n # compute the number of differences between subgroupVec1 and each permutation of values of subgroupVec2\r\n subgroupDiffs = apply(permutationMat, 1, computeSubgroupDiff)\r\n \r\n # find the row number of the permutation that gives the minimum number of subgroup differences\r\n minDiffIx = which.min(subgroupDiffs)\r\n \r\n # identify optimal permutation of values of subgroupVec2\r\n optimalPerm = permutationMat[minDiffIx, ]\r\n \r\n # create optimal permutation of values of subgroupVec2\r\n subgroupVec2Ordered = createSubgroupVec(optimalPerm)\r\n \r\n return(subgroupVec2Ordered)\r\n \r\n} # end subgroupVecMatcher function\r\n", "meta": {"hexsha": "f0b697d57440aae6d23eebe57104d3e0c63928ec", "size": 3154, "ext": "r", "lang": "R", "max_stars_repo_path": "subgroupVecMatcher.r", "max_stars_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_stars_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "subgroupVecMatcher.r", "max_issues_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_issues_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "subgroupVecMatcher.r", "max_forks_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_forks_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5, "max_line_length": 107, "alphanum_fraction": 0.6902346227, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.49451183228341306}} {"text": "library(MASS)\nlibrary(dplyr)\nlibrary(tidyr)\nlibrary(ggplot2)\nlibrary(ascii)\nlibrary(lubridate)\nlibrary(splines)\nlibrary(mgcv)\n\n## Import datasets needed for chapter 4\nPSDS_PATH <- file.path('~', 'statistics-for-data-scientists')\n\nlung <- read.csv(file.path(PSDS_PATH, 'data', 'LungDisease.csv'))\n\nzhvi <- read.csv(file.path(PSDS_PATH, 'data', 'County_Zhvi_AllHomes.csv'))\nzhvi <- unlist(zhvi[13,-(1:5)])\ndates <- parse_date_time(paste(substr(names(zhvi), start=2, stop=8), \"01\", sep=\".\"), \"Ymd\")\nzhvi <- data.frame(ym=dates, zhvi_px=zhvi, row.names = NULL) %>%\n mutate(zhvi_idx=zhvi/last(zhvi))\n\nhouse <- read.csv(file.path(PSDS_PATH, 'data', 'house_sales.csv'), sep='\\t')\n# house <- house[house$ZipCode > 0, ]\n# write.table(house, file.path(PSDS_PATH, 'data', 'house_sales.csv'), sep='\\t')\n## Code for Figure 1\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0401.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(4,4,0,0)+.1)\nplot(lung$Exposure, lung$PEFR, xlab=\"Exposure\", ylab=\"PEFR\")\ndev.off()\n\n## Code snippet 4.1\nmodel <- lm(PEFR ~ Exposure, data=lung)\nmodel\n\n## Code for figure 2\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0402.png'), width = 350, height = 350)\npar(mar=c(4,4,0,0)+.1)\n\nplot(lung$Exposure, lung$PEFR, xlab=\"Exposure\", ylab=\"PEFR\", ylim=c(300,450), type=\"n\", xaxs=\"i\")\nabline(a=model$coefficients[1], b=model$coefficients[2], col=\"blue\", lwd=2)\ntext(x=.3, y=model$coefficients[1], labels=expression(\"b\"[0]), adj=0, cex=1.5)\nx <- c(7.5, 17.5)\ny <- predict(model, newdata=data.frame(Exposure=x))\nsegments(x[1], y[2], x[2], y[2] , col=\"red\", lwd=2, lty=2)\nsegments(x[1], y[1], x[1], y[2] , col=\"red\", lwd=2, lty=2)\ntext(x[1], mean(y), labels=expression(Delta~Y), pos=2, cex=1.5)\ntext(mean(x), y[2], labels=expression(Delta~X), pos=1, cex=1.5)\ntext(mean(x), 400, labels=expression(b[1] == frac(Delta ~ Y, Delta ~ X)), cex=1.5)\ndev.off()\n\n## Code snippet 4.2\nfitted <- predict(model)\nresid <- residuals(model)\n\n## Code for figure 3\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0403.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(4,4,0,0)+.1)\n\nlung1 <- lung %>%\n mutate(Fitted=fitted,\n positive = PEFR>Fitted) %>%\n group_by(Exposure, positive) %>%\n summarize(PEFR_max = max(PEFR), \n PEFR_min = min(PEFR),\n Fitted = first(Fitted)) %>%\n ungroup() %>%\n mutate(PEFR = ifelse(positive, PEFR_max, PEFR_min)) %>%\n arrange(Exposure)\n\nplot(lung$Exposure, lung$PEFR, xlab=\"Exposure\", ylab=\"PEFR\")\nabline(a=model$coefficients[1], b=model$coefficients[2], col=\"blue\", lwd=2)\nsegments(lung1$Exposure, lung1$PEFR, lung1$Exposure, lung1$Fitted, col=\"red\", lty=3)\ndev.off()\n\n\n## Code snippet 4.3\nhead(house[, c(\"AdjSalePrice\", \"SqFtTotLiving\", \"SqFtLot\", \"Bathrooms\", \n \"Bedrooms\", \"BldgGrade\")])\n\n## Code snippet 4.4\nhouse_lm <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + \n Bedrooms + BldgGrade, \n data=house, na.action=na.omit)\n\n## Code snippet 4.5\nhouse_lm\n\n## Code snippet 4.6\nsummary(house_lm)\n\n## Code snippet 4.7\nhouse_full <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + \n Bedrooms + BldgGrade + PropertyType + NbrLivingUnits + \n SqFtFinBasement + YrBuilt + YrRenovated + NewConstruction,\n data=house, na.action=na.omit)\n\n## Code snippet 4.8\nstep_lm <- stepAIC(house_full, direction=\"both\")\nstep_lm\n\nlm(AdjSalePrice ~ Bedrooms, data=house)\n\n# WeightedRegression\n## Code snippet 4.9\nhouse$Year = year(house$DocumentDate)\nhouse$Weight = house$Year - 2005\n\n## Code snippet 4.10\nhouse_wt <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + \n Bedrooms + BldgGrade,\n data=house, weight=Weight, na.action=na.omit)\nround(cbind(house_lm=house_lm$coefficients, \n house_wt=house_wt$coefficients), digits=3)\n\n\n# Factor Variables\n## Code snippet 4.11\nhead(house[, 'PropertyType'])\n\n## Code snippet 4.12\nprop_type_dummies <- model.matrix(~PropertyType -1, data=house)\nhead(prop_type_dummies)\n\n## Code snippet 4.13\nlm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + \n Bedrooms + BldgGrade + PropertyType, data=house)\n\n## Code snippet 4.14\ntable(house$ZipCode)\n\n## Code snippet 4.15\nzip_groups <- house %>%\n mutate(resid = residuals(house_lm)) %>%\n group_by(ZipCode) %>%\n summarize(med_resid = median(resid),\n cnt = n()) %>%\n # sort the zip codes by the median residual\n arrange(med_resid) %>%\n mutate(cum_cnt = cumsum(cnt),\n ZipGroup = factor(ntile(cum_cnt, 5)))\nhouse <- house %>%\n left_join(select(zip_groups, ZipCode, ZipGroup), by='ZipCode')\n\n\n# correlated variables\n# Code snippet 4.15\nstep_lm$coefficients\n\n# Code snippet 4.16\nupdate(step_lm, . ~ . -SqFtTotLiving - SqFtFinBasement - Bathrooms)\n\n# ConfoundingVariables\n## Code snippet 4.17\nlm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + \n Bathrooms + Bedrooms + \n BldgGrade + PropertyType + ZipGroup,\n data=house, na.action=na.omit)\n\n\n# Interactions\n## Code snippet 4.18\nlm(AdjSalePrice ~ SqFtTotLiving*ZipGroup + SqFtLot + \n Bathrooms + Bedrooms + \n BldgGrade + PropertyType,\n data=house, na.action=na.omit)\n\nhead(model.matrix(~C(PropertyType, sum) , data=house))\n\n\n# outlier anaysis\n## Code snippet 4.19\nhouse_98105 <- house[house$ZipCode == 98105,]\nlm_98105 <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + \n Bedrooms + BldgGrade, data=house_98105)\n\n## Code snippet 4.20\nsresid <- rstandard(lm_98105)\nidx <- order(sresid, decreasing=FALSE)\nsresid[idx[1]]\nresid(lm_98105)[idx[1]]\n\n## Code snippet 4.21\nhouse_98105[idx[1], c('AdjSalePrice', 'SqFtTotLiving', 'SqFtLot',\n 'Bathrooms', 'Bedrooms', 'BldgGrade')]\n\n# Figure 4-5: Influential data point in regression\nseed <- 11\nset.seed(seed)\nx <- rnorm(25)\ny <- -x/5 + rnorm(25)\nx[1] <- 8\ny[1] <- 8\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0405.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(3,3,0,0)+.1)\nplot(x, y, xlab='', ylab='', pch=16)\nmodel <- lm(y~x)\nabline(a=model$coefficients[1], b=model$coefficients[2], col=\"blue\", lwd=3)\nmodel <- lm(y[-1]~x[-1])\nabline(a=model$coefficients[1], b=model$coefficients[2], col=\"red\", lwd=3, lty=2)\ndev.off()\n\n# influential observations\n## Code snippet 4.22\nstd_resid <- rstandard(lm_98105)\ncooks_D <- cooks.distance(lm_98105)\nhat_values <- hatvalues(lm_98105)\nplot(hat_values, std_resid, cex=10*sqrt(cooks_D))\nabline(h=c(-2.5, 2.5), lty=2)\n\n## Code for Figure 4-6\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0406.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(4,4,0,0)+.1)\nplot(hat_values, std_resid, cex=10*sqrt(cooks_D))\nabline(h=c(-2.5, 2.5), lty=2)\ndev.off()\n\n\n## Table 4-2\n\nlm_98105_inf <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + \n Bathrooms + Bedrooms + BldgGrade,\n subset=cooks_D<.08, data=house_98105)\n\ndf <- data.frame(lm_98105$coefficients,\n lm_98105_inf$coefficients)\nnames(df) <- c('Original', 'Influential Removed')\nascii((df),\n include.rownames=TRUE, include.colnames=TRUE, header=TRUE,\n digits=rep(0, 3), align=c(\"l\", \"r\", \"r\") ,\n caption=\"Comparison of regression coefficients with the full data and with influential data removed\")\n\n## heteroskedasticity\n## Code snippet 4.23\ndf <- data.frame(\n resid = residuals(lm_98105),\n pred = predict(lm_98105))\nggplot(df, aes(pred, abs(resid))) +\n geom_point() +\n geom_smooth() \n\n## Code for figure 4-7\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0407.png'), width = 4, height=4, units='in', res=300)\n\nggplot(df, aes(pred, abs(resid))) +\n geom_point() +\n geom_smooth() +\n theme_bw() \n\n\ndev.off()\n\n## Code for figure 4-8\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0408.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(4,4,0,0)+.1)\nhist(std_resid, main='')\ndev.off()\n\n\n## partial residuals plot\n## Code snippet 4.24\nterms <- predict(lm_98105, type='terms')\npartial_resid <- resid(lm_98105) + terms\n\n## Code snippet 4.25\ndf <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'],\n Terms = terms[, 'SqFtTotLiving'],\n PartialResid = partial_resid[, 'SqFtTotLiving'])\nggplot(df, aes(SqFtTotLiving, PartialResid)) +\n geom_point(shape=1) + scale_shape(solid = FALSE) +\n geom_smooth(linetype=2) + \n geom_line(aes(SqFtTotLiving, Terms)) \n\n## Code for figure 4-9\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0409.png'), width = 4, height=4, units='in', res=300)\n\ndf <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'],\n Terms = terms[, 'SqFtTotLiving'],\n PartialResid = partial_resid[, 'SqFtTotLiving'])\nggplot(df, aes(SqFtTotLiving, PartialResid)) +\n geom_point(shape=1) + scale_shape(solid = FALSE) +\n geom_smooth(linetype=2) + \n theme_bw() +\n geom_line(aes(SqFtTotLiving, Terms)) \n\ndev.off()\n\n\n## Code snippet 4.26\n\nlm(AdjSalePrice ~ poly(SqFtTotLiving, 2) + SqFtLot +\n BldgGrade + Bathrooms + Bedrooms, \n data=house_98105)\n\n\nlm_poly <- lm(AdjSalePrice ~ poly(SqFtTotLiving, 2) + SqFtLot + \n BldgGrade + Bathrooms + Bedrooms,\n data=house_98105)\nterms <- predict(lm_poly, type='terms')\npartial_resid <- resid(lm_poly) + terms\n\n## Code for Figure 4-10\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0410.png'), width = 4, height=4, units='in', res=300)\n\ndf <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'],\n Terms = terms[, 1],\n PartialResid = partial_resid[, 1])\nggplot(df, aes(SqFtTotLiving, PartialResid)) +\n geom_point(shape=1) + scale_shape(solid = FALSE) +\n geom_smooth(linetype=2) + \n geom_line(aes(SqFtTotLiving, Terms))+\n theme_bw()\n\ndev.off()\n\n\n## Code snippet 4.27\nknots <- quantile(house_98105$SqFtTotLiving, p=c(.25, .5, .75))\nlm_spline <- lm(AdjSalePrice ~ bs(SqFtTotLiving, knots=knots, degree=3) + SqFtLot + \n Bathrooms + Bedrooms + BldgGrade, data=house_98105)\n\n\nterms1 <- predict(lm_spline, type='terms')\npartial_resid1 <- resid(lm_spline) + terms\n\n## Code for Figure 4-12\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0412.png'), width = 4, height=4, units='in', res=300)\n\ndf1 <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'],\n Terms = terms1[, 1],\n PartialResid = partial_resid1[, 1])\nggplot(df1, aes(SqFtTotLiving, PartialResid)) +\n geom_point(shape=1) + scale_shape(solid = FALSE) +\n geom_smooth(linetype=2) + \n geom_line(aes(SqFtTotLiving, Terms))+\n theme_bw()\n\ndev.off()\n\n## Code snippet 4.27\nlm_gam <- gam(AdjSalePrice ~ s(SqFtTotLiving) + SqFtLot + \n Bathrooms + Bedrooms + BldgGrade, \n data=house_98105)\nterms <- predict.gam(lm_gam, type='terms')\npartial_resid <- resid(lm_gam) + terms\n\n## Code for Figure 4-13\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0413.png'), width = 4, height=4, units='in', res=300)\ndf <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'],\n Terms = terms[, 5],\n PartialResid = partial_resid[, 5])\nggplot(df, aes(SqFtTotLiving, PartialResid)) +\n geom_point(shape=1) + scale_shape(solid = FALSE) +\n geom_smooth(linetype=2) + \n geom_line(aes(SqFtTotLiving, Terms)) +\n theme_bw()\ndev.off()\n\n\n\n", "meta": {"hexsha": "f533bf7fcefa11b890de5c034d5af3951b2bede7", "size": 11265, "ext": "r", "lang": "R", "max_stars_repo_path": "references/statistics-for-data-scientists/src/chapter4.r", "max_stars_repo_name": "ronsims2/data_science_tutorials", "max_stars_repo_head_hexsha": "ce245eb875330f2d64e30a2340afb8ea2eb25c20", "max_stars_repo_licenses": ["FTL"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-08-07T11:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:48:45.000Z", "max_issues_repo_path": "chapter4.r", "max_issues_repo_name": "CLAUDERNORONHA/LIVRO-ESTATISTICA-PARA-CIENTISTA-DE-DADOS", "max_issues_repo_head_hexsha": "a4e34cff903c2db867127becdd0d431f34e97e2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91, "max_issues_repo_issues_event_min_datetime": "2019-11-11T15:41:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T04:17:18.000Z", "max_forks_repo_path": "chapter4.r", "max_forks_repo_name": "CLAUDERNORONHA/LIVRO-ESTATISTICA-PARA-CIENTISTA-DE-DADOS", "max_forks_repo_head_hexsha": "a4e34cff903c2db867127becdd0d431f34e97e2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-11-13T12:44:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T19:34:26.000Z", "avg_line_length": 31.2916666667, "max_line_length": 107, "alphanum_fraction": 0.6614292055, "num_tokens": 3819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4944706084493044}} {"text": "#' Variogram plots for spatial models.\n#'\n#' Produces variogram plots for checking spatial trends.\n#'\n#' @param model.obj An `asreml` model object.\n#' @param palette A string specifying the colour scheme to use for plotting. The default value (`\"default\"`) is equivalent to `\"rainbow\"`. Colour blind friendly palettes can also be provided via options `\"colour blind\"` (or `\"color blind\"`, both equivalent to `\"viridis\"`), `\"magma\"`, `\"inferno\"`, `\"plasma\"` or `\"cividis\"`. The `\"Spectral\"` palette from [scales::brewer_pal()] is also possible.\n#'\n#' @return A ggplot2 object.\n#'\n#' @importFrom interp interp\n#' @importFrom grDevices rainbow\n#' @importFrom lattice wireframe\n#' @importFrom cowplot plot_grid\n#' @importFrom ggplot2 ggplot geom_tile coord_equal geom_contour scale_fill_gradientn theme_bw scale_x_continuous scale_y_continuous theme labs\n#'\n#' @references S. P. Kaluzny, S. C. Vega, T. P. Cardoso, A. A. Shelly, \"S+SpatialStats: User’s Manual for Windows® and UNIX®\" _Springer New York_, 2013, p. 68, https://books.google.com.au/books?id=iADkBwAAQBAJ.\n#' @references A. R. Gilmour, B. R. Cullis, A. P. Verbyla, \"Accounting for Natural and Extraneous Variation in the Analysis of Field Experiments.\" _Journal of Agricultural, Biological, and Environmental Statistics 2, no. 3_, 1997, pp. 269–93, https://doi.org/10.2307/1400446.\n#'\n#' @examples\n#' \\dontrun{\n#' library(asreml)\n#' oats <- asreml::oats\n#' oats <- oats[order(oats$Row, oats$Column),]\n#' model.asr <- asreml(yield ~ Nitrogen + Variety + Nitrogen:Variety,\n#' random = ~ Blocks + Blocks:Wplots,\n#' residual = ~ ar1(Row):ar1(Column),\n#' data = oats)\n#' variogram(model.asr)\n#' }\n#' @export\n\nvariogram <- function(model.obj, palette = \"default\") {\n\n if(!(inherits(model.obj, \"asreml\"))) {\n stop(\"model.obj must be an asreml model object\")\n }\n\n aa <- vario_df(model.obj)\n xnam <- names(aa)[2]\n ynam <- names(aa)[1]\n fld <- interp::interp(y = aa[,1], x = aa[,2], z = aa$gamma)\n gdat <- cbind(expand.grid(x = fld$x, y = fld$y), z = as.vector(fld$z))\n\n a <- ggplot2::ggplot(gdat, ggplot2::aes(x = y, y = x, z = z, fill = z)) +\n ggplot2::geom_tile(alpha = 0.6) +\n ggplot2::coord_equal() +\n ggplot2::geom_contour(color = \"white\", alpha = 0.5) +\n ggplot2::theme_bw(base_size = 8) +\n ggplot2::scale_y_continuous(expand = c(0, 0), breaks = seq(1, max(gdat$x), 2)) +\n ggplot2::scale_x_continuous(expand = c(0, 0), breaks = seq(1, max(gdat$y), 2)) +\n ggplot2::theme(legend.position = \"none\", aspect.ratio = 0.3) +\n ggplot2::labs(y = paste(xnam, \"Lag\", sep = \" \"), x = paste(ynam, \"Lag\", sep = \" \"))\n\n if(tolower(palette) == \"rainbow\" | tolower(palette) == \"default\") {\n a <- a + ggplot2::scale_fill_gradientn(colours = grDevices::rainbow(100))\n\n b <- lattice::wireframe(z ~ y * x, data = gdat, aspect = c(61/87, 0.4),\n scales = list(cex = 0.5, arrows = FALSE),\n shade = TRUE, colorkey = FALSE,\n par.settings = list(axis.line = list(col = 'transparent')),\n xlab = list(label = paste(ynam, \"Lag\", sep = \" \"), cex = .8, rot = 20),\n ylab = list(label = paste(xnam, \"Lag\", sep = \" \"), cex = .8, rot = -18),\n zlab = list(label = NULL, cex.axis = 0.5))\n }\n else if(any(grepl(\"(colou?r([[:punct:]]|[[:space:]]?)blind)|cb|viridis\", palette, ignore.case = T))) {\n a <- a + ggplot2::scale_fill_gradientn(colours = scales::viridis_pal(option = \"viridis\")(50))\n\n # Create the lattice plot\n b <- lattice::wireframe(z ~ y * x, data = gdat, aspect = c(61/87, 0.4),\n scales = list(cex = 0.5, arrows = FALSE),\n drape = TRUE, colorkey = FALSE,\n par.settings = list(axis.line = list(col = 'transparent')),\n xlab = list(label = paste(ynam, \"Lag\", sep = \" \"), cex = .8, rot = 20),\n ylab = list(label = paste(xnam, \"Lag\", sep = \" \"), cex = .8, rot = -18),\n zlab = list(label = NULL, cex.axis = 0.5),\n col.regions = scales::viridis_pal(option = \"viridis\")(100))\n }\n else if(tolower(palette) %in% c(\"magma\", \"inferno\", \"cividis\", \"plasma\")) {\n a <- a + ggplot2::scale_fill_gradientn(colours = scales::viridis_pal(option = palette)(50))\n\n # Create the lattice plot\n b <- lattice::wireframe(z ~ y * x, data = gdat, aspect = c(61/87, 0.4),\n scales = list(cex = 0.5, arrows = FALSE),\n drape = TRUE, colorkey = FALSE,\n par.settings = list(axis.line = list(col = 'transparent')),\n xlab = list(label = paste(ynam, \"Lag\", sep = \" \"), cex = .8, rot = 20),\n ylab = list(label = paste(xnam, \"Lag\", sep = \" \"), cex = .8, rot = -18),\n zlab = list(label = NULL, cex.axis = 0.5),\n col.regions = scales::viridis_pal(option = palette)(100))\n }\n\n else if(palette %in% c(\"Spectral\")) {\n a <- a + ggplot2::scale_fill_gradientn(colours = scales::brewer_pal(palette = palette)(11))\n\n # Create the lattice plot\n b <- lattice::wireframe(z ~ y * x, data = gdat, aspect = c(61/87, 0.4),\n scales = list(cex = 0.5, arrows = FALSE),\n drape = TRUE, colorkey = FALSE,\n par.settings = list(axis.line = list(col = 'transparent')),\n xlab = list(label = paste(ynam, \"Lag\", sep = \" \"), cex = .8, rot = 20),\n ylab = list(label = paste(xnam, \"Lag\", sep = \" \"), cex = .8, rot = -18),\n zlab = list(label = NULL, cex.axis = 0.5),\n col.regions = scales::brewer_pal(palette = palette)(11))\n }\n else {\n stop(\"Invalid value for palette.\")\n }\n\n # if(isTRUE(horizontal)) {\n output <- cowplot::plot_grid(b, a, nrow = 2, scale = c(2, 1))\n # }\n # else if(isFALSE(horizontal)) {\n # output <- cowplot::plot_grid(b, a, ncol = 2, nrow = 1, scale = c(1, 1))\n # }\n # else {\n # stop(\"horizontal must be either TRUE or FALSE\")\n # }\n\n return(output)\n}\n\n#' Calculate the variogram data frame for a model\n#'\n#' @param model.obj An asreml model\n#'\n#' @return A data frame with the variogram for a model. The data frame contains the spatial coordinates (typically row and column), the $gamma$ for that position and the number of points with the separation.\n#' @keywords internal\nvario_df <- function(model.obj) {\n # The 'z' value for the variogram is the residuals\n # Need to be able to pull out the x/y from the model object\n\n dims <- unlist(strsplit(names(model.obj$R.param[1]), \":\"))\n Row <- as.numeric(model.obj$mf[[dims[1]]])\n Column <- as.numeric(model.obj$mf[[dims[2]]])\n Resid <- residuals(model.obj)\n\n nrows <- max(Row)\n ncols <- max(Column)\n\n vario <- expand.grid(Row = 0:(nrows-1), Column = 0:(ncols-1))\n\n # Ignore the 0, 0 case (gamma=0, counted row*cols times)\n gammas <- rep(0, nrows*ncols)\n nps <- rep(nrows*ncols, nrows*ncols)\n\n for (index in 2:nrow(vario)) {\n i <- vario[index, 'Row']\n j <- vario[index, 'Column']\n\n gamma <- 0\n np <- 0\n for (val_index in 1:nrows) {\n # val <- vals[val_index, ]\n\n # Deliberate double-counting so that offset handling is easy\n # (so e.g. we compute distance from (1,1)->(2,3), and then again\n # later from (2,3)->(1,1)).\n for (offset in unique(list(c(i, j), c(-i, j), c(i, -j), c(-i, -j)))) {\n row <- Row[val_index] + offset[1]\n col <- Column[val_index] + offset[2]\n\n if (0 < row && row <= nrows && 0 < col && col <= ncols) {\n other <- which(Row == row & Column == col)\n gamma <- gamma + (Resid[val_index]-Resid[other])^2\n np <- np + 1\n }\n }\n }\n # Since we double-counted precisely, halve to get the correct answer.\n np <- np / 2\n gamma <- gamma / 2\n\n if (np > 0) {\n gamma <- gamma / (2*np)\n }\n\n gammas[index] <- gamma\n nps[index] <- np\n }\n vario <- cbind(vario, data.frame(gamma = gammas, np = nps))\n colnames(vario) <- c(dims, \"gamma\", \"np\")\n class(vario) <- c(\"variogram\", \"data.frame\")\n return(vario)\n}\n", "meta": {"hexsha": "c8bb2ce805530e10418ff655a19faeb132baf37a", "size": 8806, "ext": "r", "lang": "R", "max_stars_repo_path": "R/variogram.r", "max_stars_repo_name": "biometryhub/biometryassist", "max_stars_repo_head_hexsha": "755a9399ab3f3b5879c4776c04874a92e597f737", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-25T09:02:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:35:27.000Z", "max_issues_repo_path": "R/variogram.r", "max_issues_repo_name": "biometryhub/biometryassist", "max_issues_repo_head_hexsha": "755a9399ab3f3b5879c4776c04874a92e597f737", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2022-01-25T09:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T03:35:05.000Z", "max_forks_repo_path": "R/variogram.r", "max_forks_repo_name": "biometryhub/biometryassist", "max_forks_repo_head_hexsha": "755a9399ab3f3b5879c4776c04874a92e597f737", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6, "max_line_length": 395, "alphanum_fraction": 0.5330456507, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4943898385523683}} {"text": "#' Compute arithmetic mean with confidence interval.\n.get_mean_with_ci <- function (data, key, metric_name) {\n # Key not used but supplied by group map calls.\n\n # We work on run means for speed.\n runs <- get_run_means (data, metric_name)\n\n # Do not even try with one run.\n if (length (runs) > 1) {\n\n # Standard bootstrap computation.\n mean_boot <- boot (runs, function (d, i) mean (d [i]), R = REPLICATES)\n\n # The computations can fail so fall back to something if they do.\n mean_ci <- tryCatch (boot.ci (mean_boot, type = 'bca', conf = CONFIDENCE), error = function (e) NA)\n if (!is.null (mean_ci) && !any (is.na (mean_ci))) return (tibble (avg = mean_boot $ t0, lo = mean_ci $ bca [1,4], hi = mean_ci $ bca [1,5]))\n mean_ci <- tryCatch (boot.ci (mean_boot, type = 'basic', conf = CONFIDENCE), error = function (e) NA)\n if (!is.null (mean_ci) && !any (is.na (mean_ci))) return (tibble (avg = mean_boot $ t0, lo = mean_ci $ basic [1,4], hi = mean_ci $ basic [1,5]))\n }\n\n return (tibble (avg = mean (runs), lo = NA, hi = NA))\n}\n\n\n#' Compute arithmetic means with confidence intervals per given group.\ncomp_mean_with_ci <- function (data, metric_name) {\n return (data %>% group_modify (.get_mean_with_ci, metric_name))\n}\n", "meta": {"hexsha": "6b9c85366439761242ee51805c3ca683a0d44fb4", "size": 1292, "ext": "r", "lang": "R", "max_stars_repo_path": "code/comp_mean_with_ci.r", "max_stars_repo_name": "renaissance-benchmarks/measurements", "max_stars_repo_head_hexsha": "ac2a470ec627c53845d0749234cb29090c0b2fcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-05-06T16:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-25T03:06:18.000Z", "max_issues_repo_path": "code/comp_mean_with_ci.r", "max_issues_repo_name": "renaissance-benchmarks/measurements", "max_issues_repo_head_hexsha": "ac2a470ec627c53845d0749234cb29090c0b2fcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-05-07T14:52:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T10:35:27.000Z", "max_forks_repo_path": "code/comp_mean_with_ci.r", "max_forks_repo_name": "renaissance-benchmarks/measurements", "max_forks_repo_head_hexsha": "ac2a470ec627c53845d0749234cb29090c0b2fcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-17T20:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-17T20:14:51.000Z", "avg_line_length": 44.5517241379, "max_line_length": 152, "alphanum_fraction": 0.6339009288, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49409087136832885}} {"text": "s = 0\n\ni = 1\nrepeat\n\n{\n \n s = s + i\n i = i + 1\n \n if(i==9)\n break\n}\ncat(\"sum is\", s)\n", "meta": {"hexsha": "aca78bfae21f485d4cdb4e69d6e3e317f0190516", "size": 95, "ext": "r", "lang": "R", "max_stars_repo_path": "Basics/control_structures/repeat.r", "max_stars_repo_name": "DivyaMaddipudi/R-Programming-Basics", "max_stars_repo_head_hexsha": "28546e2f159b98bd8e94503b2a2e07aef68e24f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basics/control_structures/repeat.r", "max_issues_repo_name": "DivyaMaddipudi/R-Programming-Basics", "max_issues_repo_head_hexsha": "28546e2f159b98bd8e94503b2a2e07aef68e24f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basics/control_structures/repeat.r", "max_forks_repo_name": "DivyaMaddipudi/R-Programming-Basics", "max_forks_repo_head_hexsha": "28546e2f159b98bd8e94503b2a2e07aef68e24f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 6.3333333333, "max_line_length": 16, "alphanum_fraction": 0.3578947368, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.49402351662873206}} {"text": "#!/usr/bin/env Rscript\n\n# Helper functions to annotate adducts\nadductCalculator<-function(mz=NA,charge=NA,mode=\"pos\",adduct=NA, primary = T)\n{\n if(is.na(mz))stop(\"Provide the mz!\")\n if(is.na(mode))stop(\"Provide the polarity!\")\n\n Ion.name.pos=c(\"M+3H\",\n \"M+2H+Na\",\n \"M+H+2Na\",\n \"M+3Na\",\n \"M+2H\",\n \"M+H+NH4\",\n \"M+H+Na\",\n \"M+H+K\",\n \"M+ACN+2H\",\n \"M+2Na\",\n \"M+2ACN+2H\",\n \"M+3ACN+2H\",\n \"M+H\",\n \"M+NH4\",\n \"M+Na\",\n \"M+CH3OH+H\",\n \"M+K\",\n \"M+ACN+H\",\n \"M+2Na-H\",\n \"M+IsoProp+H\",\n \"M+ACN+Na\",\n \"M+2K-H\",\n \"M+DMSO+H\",\n \"M+2ACN+H\",\n \"M+IsoProp+Na+H\",\n \"2M+H\",\n \"2M+NH4\",\n \"2M+Na\",\n \"2M+K\",\n \"2M+ACN+H\",\n \"2M+ACN+Na\")\n\n Ion.mass.pos=c(\n \"M/3 + 1.007276\",\n \"M/3 + 8.334590\",\n \"M/3 + 15.7661904\",\n \"M/3 + 22.989218\",\n \"M/2 + 1.007276\",\n \"M/2 + 9.520550\",\n \"M/2 + 11.998247\",\n \"M/2 + 19.985217\",\n \"M/2 + 21.520550\",\n \"M/2 + 22.989218\",\n \"M/2 + 42.033823\",\n \"M/2 + 62.547097\",\n \"M + 1.007276\",\n \"M + 18.033823\",\n \"M + 22.989218\",\n \"M + 33.033489\",\n \"M + 38.963158\",\n \"M + 42.033823\",\n \"M + 44.971160\",\n \"M + 61.06534\",\n \"M + 64.015765\",\n \"M + 76.919040\",\n \"M + 79.02122\",\n \"M + 83.060370\",\n \"M + 84.05511\",\n \"2M + 1.007276\",\n \"2M + 18.033823\",\n \"2M + 22.989218\",\n \"2M + 38.963158\",\n \"2M + 42.033823\",\n \"2M + 64.015765\")\n\n Charge.pos=c(\n \"3+\",\n \"3+\",\n \"3+\",\n \"3+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"2+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\",\n \"1+\")\n\n Extended.pos<-c(T,T,T,T,T,T,T,T,T,T,T,T,F,F,F,T,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T)\n\n Ion.name.neg<-c(\"M-3H\",\n \"M-2H\",\n \"M-H2O-H\",\n \"M-H\",\n \"M+Na-2H\",\n \"M+Cl\",\n \"M+K-2H\",\n \"M+FA-H\",\n \"M+Hac-H\",\n \"M+Br\",\n \"M+TFA-H\",\n \"2M-H\",\n \"2M+FA-H\",\n \"2M+Hac-H\",\n \"3M-H\")\n\n Ion.mass.neg<-c(\"M/3 - 1.007276\",\n \"M/2 - 1.007276\",\n \"M - 19.01839\",\n \"M - 1.007276\",\n \"M + 20.974666\",\n \"M + 34.969402\",\n \"M + 36.948606\",\n \"M + 44.998201\",\n \"M + 59.013851\",\n \"M + 78.918885\",\n \"M + 112.985586\",\n \"2M - 1.007276\",\n \"2M + 44.998201\",\n \"2M + 59.013851\",\n \"3M - 1.007276\")\n\n Charge.neg<-c(\"3-\",\n \"2-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\",\n \"1-\")\n\n Extended.neg<-c(T,T,T,F,F,F,F,T,T,T,T,T,T,T,T)\n\n adductsFile.pos<-data.frame(\n\tIon.name=Ion.name.pos[!(Extended.pos & primary)],\n\tIon.mass=Ion.mass.pos[!(Extended.pos & primary)],\n\tCharge=Charge.pos[!(Extended.pos & primary)])\n adductsFile.neg<-data.frame(\n\tIon.name=Ion.name.neg[!(Extended.neg & primary)],\n\tIon.mass=Ion.mass.neg[!(Extended.neg & primary)],\n\tCharge=Charge.neg[!(Extended.neg & primary)])\n\n if(tolower(mode)%in%c(\"pos\",\"positive\",\"p\"))\n {\n # select the adducts (primary or extended)\n tmpAdduct<-adductsFile.pos\n if(!is.na(charge) & is.numeric(charge))\n {\n chargeSign<-NA\n chargeSign<-\"+\"\n tmpAdduct<-tmpAdduct[tmpAdduct[,\"Charge\"]==paste(charge,chargeSign,sep=\"\"),]\n }\n if(!is.na(adduct))\n {\n\n tmpAdduct<-tmpAdduct[tmpAdduct[,\"Ion.name\"]%in%adduct,]\n }\n\n if(nrow(tmpAdduct)==0){\n warning(\"Not found! Reporting all possible adducts\")\n tmpAdduct<-adductsFile.pos\n }\n signs<-sapply(str_extract(as.character(tmpAdduct[,\"Ion.mass\"]),\"\\\\+|\\\\-\"),function(x){x[[1]]})\n signs[signs==\"+\"]=-1\n signs[signs==\"-\"]=+1\n mzCoefficients<-\n str_extract(sapply(strsplit(as.character(tmpAdduct[,\"Ion.mass\"]),split = \"\\\\+|\\\\-\"),function(x){x[1]}),\n \"\\\\d+\")\n\n mzCoefficients[is.na(mzCoefficients)]<-1\n mzCoefficients<-as.numeric(mzCoefficients)\n mzCoefficients[!grepl(\"/\",as.character(tmpAdduct[,\"Ion.mass\"]),fixed=T)]<-\n 1/ mzCoefficients[!grepl(\"/\",as.character(tmpAdduct[,\"Ion.mass\"]),fixed=T)]\n\n result<- mz+ (as.numeric(signs)*\n as.numeric(sapply(strsplit(as.character(tmpAdduct[,\"Ion.mass\"]),\"\\\\+|\\\\-\"),function(x){x[[2]]})))\n\n result<- result*mzCoefficients\n }else if(tolower(mode)%in%c(\"neg\",\"negative\",\"n\"))\n {\n tmpAdduct<-adductsFile.neg\n if(!is.na(charge) & is.numeric(charge))\n {\n chargeSign<-NA\n chargeSign<-\"-\"\n tmpAdduct<-tmpAdduct[tmpAdduct[,\"Charge\"]==paste(charge,chargeSign,sep=\"\"),]\n }\n if(!is.na(adduct))\n {\n\n tmpAdduct<-tmpAdduct[tmpAdduct[,\"Ion.name\"]%in%adduct,]\n }\n\n if(nrow(tmpAdduct)==0){\n warning(\"Not found! Reporting all possible adducts\")\n tmpAdduct<-adductsFile.neg\n }\n signs<-sapply(str_extract(as.character(tmpAdduct[,\"Ion.mass\"]),\"\\\\+|\\\\-\"),function(x){x[[1]]})\n signs[signs==\"+\"]=-1\n signs[signs==\"-\"]=+1\n mzCoefficients<-\n str_extract(sapply(strsplit(as.character(tmpAdduct[,\"Ion.mass\"]),split = \"\\\\+|\\\\-\"),function(x){x[1]}),\n \"\\\\d+\")\n\n mzCoefficients[is.na(mzCoefficients)]<-1\n mzCoefficients<-as.numeric(mzCoefficients)\n mzCoefficients[!grepl(\"/\",as.character(tmpAdduct[,\"Ion.mass\"]),fixed=T)]<-\n 1/ mzCoefficients[!grepl(\"/\",as.character(tmpAdduct[,\"Ion.mass\"]),fixed=T)]\n\n result<- mz+ (as.numeric(signs)*\n as.numeric(sapply(strsplit(as.character(tmpAdduct[,\"Ion.mass\"]),\"\\\\+|\\\\-\"),function(x){x[[2]]})))\n result<- result*mzCoefficients\n\n }else\n {\n stop(\"Incorrect mode! Mode has to be either positive or negative!\")\n }\n\n\nreturn(data.frame(correctedMS=result,adductName=tmpAdduct[,\"Ion.name\"]))\n\n}\n", "meta": {"hexsha": "62430dc5d8f43e2a6b82afad564edc79e793cfc8", "size": 6069, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/adductCalculator.r", "max_stars_repo_name": "jordeu/metaboigniter", "max_stars_repo_head_hexsha": "5417e975537515a16cc621292bbd77e3830585aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-02-19T12:58:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T18:49:31.000Z", "max_issues_repo_path": "bin/adductCalculator.r", "max_issues_repo_name": "jordeu/metaboigniter", "max_issues_repo_head_hexsha": "5417e975537515a16cc621292bbd77e3830585aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2021-02-04T21:08:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T11:41:15.000Z", "max_forks_repo_path": "bin/adductCalculator.r", "max_forks_repo_name": "jordeu/metaboigniter", "max_forks_repo_head_hexsha": "5417e975537515a16cc621292bbd77e3830585aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-04T09:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T07:33:05.000Z", "avg_line_length": 24.4717741935, "max_line_length": 118, "alphanum_fraction": 0.4722359532, "num_tokens": 2198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4938836545616781}} {"text": "##################################################################################################################\r\n######### WHO Child Growth Standards #####\r\n######### Department of Nutrition for Health and Development #####\r\n######### World Health Organization #####\r\n######### Last modified on 07/10/2013 - Developed using R version 3.0.1 (2013-05-16) #####\r\n######### This code corcerns the standard approach for the prevalences, i.e. the calculation of the #####\r\n######### prevalences takes into account all the valid (non-missing) z-scores for each of the indicators. #####\r\n##################################################################################################################\r\n\r\n\r\n##################################################################################################################\r\n######### Function for calculating the z-scores and prevalences for a nutritional survey #####\r\n##################################################################################################################\r\n\r\n\r\n########################################################################\r\n#### Auxiliar functions\r\n########################################################################\r\n\r\n#############################################################################\r\n##### Prevalence calculation for the upper bound and corresponding 95% C.I.\r\n#############################################################################\r\n\r\n#### Without oedema (for head circumference-for-age and arm circumferecen-for-age)\r\n\r\nprevph.L <- function(a,x,w) { \r\n ph <- sum((x > a)*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum((!is.na(x))*w,na.rm=T))+(1/(2*sum((!is.na(x))*w,na.rm=T)))\r\n vec <- c(rounde(sum((!is.na(x))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), ph+aux)*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#### With oedema (only for weight-for-length/height and bmi-for-age)\r\n\r\nprevph <- function(a,x,w,f) { \r\n f<-as.character(f)\r\n ph <- sum((x > a)*w,na.rm=T)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T))+(1/(2*sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)))\r\n vec <- c(rounde(sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), ph+aux)*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#############################################################################\r\n##### Prevalence calculation for the lower bound and corresponding 95% C.I.\r\n#############################################################################\r\n\r\n#### Without oedema (for length/height-for-age)\r\n\r\nprevnh.L <- function(a,x,w) { \r\n ph <- sum((x < a)*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum((!is.na(x))*w,na.rm=T))+(1/(2*sum((!is.na(x))*w,na.rm=T)))\r\n vec <- c(rounde(sum((!is.na(x))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), ph+aux)*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#### With oedema (for all weight-related indicators)\r\n\r\nprevnh <- function(a,x,w,f) { \r\n f<-as.character(f)\r\n ph <- sum((x < a | f==\"y\")*w,na.rm=T)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T))+(1/(2*sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)))\r\n vec <- c(rounde(sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), ph+aux)*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n###########################################\r\n#### Weighted mean and standard deviation\r\n###########################################\r\n\r\nwmean <- function(x,w) { return(rounde(sum(x*w,na.rm=T)/sum(w[!is.na(x)]),digits=2) ) }\r\n\r\nwsd <- function(x,w) { \r\n mh <- sum(x*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n sdh<-ifelse(length(x[!is.na(x)])>0,rounde(sqrt(sum(((x-mh)^2)*w,na.rm=T)/(sum((!is.na(x))*w,na.rm=T) - 1)),digits=2),NA)\r\n return( sdh )\r\n }\r\n\r\n\r\n######################################################################################\r\n#### Rounding function - SPlus rounding function uses the nearest even number rule\r\n######################################################################################\r\n\r\nrounde <- function(x,digits=0) {\r\n\texpo<-10^digits\r\n\treturn(ifelse(abs(x*expo) - floor(abs(x*expo)) < 0.5, sign(x*expo) * floor(abs(x*expo)), sign(x*expo) * (floor(abs(x*expo)) + 1))/expo)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual Length-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zlen<-function(mat,lenanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\t\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=0 & mat$age.days[i]<=1856) {\r\n\t\t\r\n\t\tl.val<-lenanthro$l[lenanthro$age==mat$age.days[i] & lenanthro$sex==mat$sex[i]]\r\n\t\tm.val<-lenanthro$m[lenanthro$age==mat$age.days[i] & lenanthro$sex==mat$sex[i]]\r\n\t\ts.val<-lenanthro$s[lenanthro$age==mat$age.days[i] & lenanthro$sex==mat$sex[i]]\r\n\t\tmat$zlen[i]<-(((mat$clenhei[i]/m.val)^l.val)-1)/(s.val*l.val)\t\r\n\t\n\t}\telse mat$zlen[i]<- NA\r\n\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual Head circumference-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zhc<-function(mat,hcanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=0 & mat$age.days[i]<=1856) {\r\n\t\t\r\n\t\tl.val<-hcanthro$l[hcanthro$age==mat$age.days[i] & hcanthro$sex==mat$sex[i]]\r\n\t\tm.val<-hcanthro$m[hcanthro$age==mat$age.days[i] & hcanthro$sex==mat$sex[i]]\r\n\t\ts.val<-hcanthro$s[hcanthro$age==mat$age.days[i] & hcanthro$sex==mat$sex[i]]\r\n\t\tmat$zhc[i]<-(((mat$headc[i]/m.val)^l.val)-1)/(s.val*l.val)\t\r\n\t\n\t}\telse mat$zhc[i]<- NA\r\n\t\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual Weight-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zwei<-function(mat,weianthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=0 & mat$age.days[i]<=1856 & mat$oedema[i]!=\"y\") {\r\n\t\t\r\n\t\tl.val<-weianthro$l[weianthro$age==mat$age.days[i] & weianthro$sex==mat$sex[i]]\r\n\t\tm.val<-weianthro$m[weianthro$age==mat$age.days[i] & weianthro$sex==mat$sex[i]]\r\n\t\ts.val<-weianthro$s[weianthro$age==mat$age.days[i] & weianthro$sex==mat$sex[i]]\r\n\r\n\t\tmat$zwei[i]<-(((mat$weight[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zwei[i]) & mat$zwei[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zwei[i]<- 3+((mat$weight[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zwei[i]) & mat$zwei[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zwei[i]<- (-3)+((mat$weight[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zwei[i]<-NA\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual Arm circumference-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zac<-function(mat,acanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=91 & mat$age.days[i]<=1856) {\r\n\r\n\t\tl.val<-acanthro$l[acanthro$age==mat$age.days[i] & acanthro$sex==mat$sex[i]]\r\n\t\tm.val<-acanthro$m[acanthro$age==mat$age.days[i] & acanthro$sex==mat$sex[i]]\r\n\t\ts.val<-acanthro$s[acanthro$age==mat$age.days[i] & acanthro$sex==mat$sex[i]]\r\n\t\tmat$zac[i]<-(((mat$armc[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zac[i]) & mat$zac[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zac[i]<- 3+((mat$armc[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zac[i]) & mat$zac[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zac[i]<- (-3)+((mat$armc[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zac[i]<-NA\r\n\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual Triceps skinfold-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zts<-function(mat,tsanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=91 & mat$age.days[i]<=1856) {\r\n\r\n\t\tl.val<-tsanthro$l[tsanthro$age==mat$age.days[i] & tsanthro$sex==mat$sex[i]]\r\n\t\tm.val<-tsanthro$m[tsanthro$age==mat$age.days[i] & tsanthro$sex==mat$sex[i]]\r\n\t\ts.val<-tsanthro$s[tsanthro$age==mat$age.days[i] & tsanthro$sex==mat$sex[i]]\r\n\r\n\t\tmat$zts[i]<-(((mat$triskin[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zts[i]) & mat$zts[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zts[i]<- 3+((mat$triskin[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zts[i]) & mat$zts[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zts[i]<- (-3)+((mat$triskin[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zts[i]<-NA\r\n\t\t\r\n}\r\n\r\nreturn(mat)\r\n}\r\n\r\n\r\n######################################################################################\r\n### Function for calculating individual Subscapular skinfold-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zss<-function(mat,ssanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tif(!is.na(mat$age.days[i]) & mat$age.days[i]>=91 & mat$age.days[i]<=1856) {\r\n\r\n\t\tl.val<-ssanthro$l[ssanthro$age==mat$age.days[i] & ssanthro$sex==mat$sex[i]]\r\n\t\tm.val<-ssanthro$m[ssanthro$age==mat$age.days[i] & ssanthro$sex==mat$sex[i]]\r\n\t\ts.val<-ssanthro$s[ssanthro$age==mat$age.days[i] & ssanthro$sex==mat$sex[i]]\r\n\r\n\t\tmat$zss[i]<-(((mat$subskin[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zss[i]) & mat$zss[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zss[i]<- 3+((mat$subskin[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zss[i]) & mat$zss[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zss[i]<- (-3)+((mat$subskin[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zss[i]<-NA\r\n}\r\n\r\nreturn(mat)\r\n}\r\n\r\n\r\n######################################################################################\r\n### Function for calculating individual Weight-for-length/height z-scores\r\n######################################################################################\r\n\r\ncalc.zwfl<-function(mat,wflanthro,wfhanthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\r\n\tmat$zwfl[i]<-NA\r\n\r\n if(mat$oedema[i]!=\"y\") {\r\n\t\r\n\t\tif( (!is.na(mat$age.days[i]) & mat$age.days[i]<731) | (is.na(mat$age.days[i]) & !is.na(mat$l.h[i]) & (mat$l.h[i]==\"l\" | mat$l.h[i]==\"L\")) | (is.na(mat$age.days[i]) & is.na(mat$l.h[i]) & !is.na(mat$clenhei[i]) & mat$clenhei[i]<87) ) {\r\n\t\t\t\r\n\t\t\tif(!is.na(mat$clenhei[i]) & mat$clenhei[i]>=45 & mat$clenhei[i]<=110) {\r\n\t\t\r\n\t\t\t### Interpolated l,m,s values\r\n\r\n\t\t\tlow.len<-trunc(mat$clenhei[i]*10)/10\r\n upp.len<-trunc(mat$clenhei[i]*10+1)/10\r\n\t\t\tdiff.len<-(mat$clenhei[i]-low.len)/0.1\r\n\t\t\t\r\n\t\t\tif(diff.len>0) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\tl.val<-wflanthro$l[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]+diff.len*( wflanthro$l[wflanthro$length==upp.len & wflanthro$sex==mat$sex[i]]-wflanthro$l[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]] )\r\n\t\t\tm.val<-wflanthro$m[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]+diff.len*( wflanthro$m[wflanthro$length==upp.len & wflanthro$sex==mat$sex[i]]-wflanthro$m[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]] )\r\n\t\t\ts.val<-wflanthro$s[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]+diff.len*( wflanthro$s[wflanthro$length==upp.len & wflanthro$sex==mat$sex[i]]-wflanthro$s[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]] )\r\n\t\t\t} else {\r\n\t\t\t\tl.val<-wflanthro$l[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]\r\n\t\t\t\tm.val<-wflanthro$m[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]\r\n\t\t\t\ts.val<-wflanthro$s[wflanthro$length==low.len & wflanthro$sex==mat$sex[i]]\n\t\t\t}\r\n\t\t\r\n\t\t\tmat$zwfl[i]<-(((mat$weight[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\t\tif(!is.na(mat$zwfl[i]) & mat$zwfl[i]>3) {\r\n\t\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\t\tmat$zwfl[i]<- 3+((mat$weight[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\t\tif(!is.na(mat$zwfl[i]) & mat$zwfl[i]<(-3)) {\r\n\t\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\t\tmat$zwfl[i]<- (-3)-((sd3neg-mat$weight[i])/sd23neg)\n\t\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\telse \t\tif( (!is.na(mat$age.days[i]) & mat$age.days[i]>=731) | (is.na(mat$age.days[i]) & !is.na(mat$l.h[i]) & (mat$l.h[i]==\"h\" | mat$l.h[i]==\"H\")) | (is.na(mat$age.days[i]) & is.na(mat$l.h[i]) & !is.na(mat$clenhei[i]) & mat$clenhei[i]>=87) ) {\r\n\t\t\t\r\n\t\t\tif(!is.na(mat$clenhei[i]) & mat$clenhei[i]>=65 & mat$clenhei[i]<=120) {\r\n\t\t\r\n\t\t\t### Interpolated l,m,s values\r\n\r\n\t\t\tlow.len<-trunc(mat$clenhei[i]*10)/10\r\n \t\tupp.len<-trunc(mat$clenhei[i]*10+1)/10\r\n\t\t\tdiff.len<-(mat$clenhei[i]-low.len)/0.1\r\n\t\t\t\r\n\t\t\tif(diff.len>0) {\t\r\n\t\t\tl.val<-wfhanthro$l[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]+diff.len*( wfhanthro$l[wfhanthro$height==upp.len & wfhanthro$sex==mat$sex[i]]-wfhanthro$l[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]] )\r\n\t\t\tm.val<-wfhanthro$m[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]+diff.len*( wfhanthro$m[wfhanthro$height==upp.len & wfhanthro$sex==mat$sex[i]]-wfhanthro$m[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]] )\r\n\t\t\ts.val<-wfhanthro$s[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]+diff.len*( wfhanthro$s[wfhanthro$height==upp.len & wfhanthro$sex==mat$sex[i]]-wfhanthro$s[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]] )\r\n } else {\r\n\t\t\tl.val<-wfhanthro$l[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]\r\n\t\t\tm.val<-wfhanthro$m[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]\r\n\t\t\ts.val<-wfhanthro$s[wfhanthro$height==low.len & wfhanthro$sex==mat$sex[i]]\n\t\t\t}\r\n\r\n\t\t\tmat$zwfl[i]<-(((mat$weight[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\t\tif(!is.na(mat$zwfl[i]) & mat$zwfl[i]>3) {\r\n\t\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\t\tmat$zwfl[i]<- 3+((mat$weight[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t\t}\r\n\t\t\tif(!is.na(mat$zwfl[i]) & mat$zwfl[i]<(-3)) {\r\n\t\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\t\tmat$zwfl[i]<- (-3)-((sd3neg-mat$weight[i])/sd23neg)\n\t\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\n\t\t\r\n\t\tif(!is.na(mat$age.day[i]) & mat$age.days[i]>1856) mat$zwfl[i]<-NA\r\n\r\n}\r\n\r\nreturn(mat)\r\n}\r\n\r\n\r\n######################################################################################\r\n### Function for calulating individual BMI-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zbmi<-function(mat,bmianthro){\r\n\r\nfor(i in 1:length(mat$age.days)) {\r\n\t\r\n\tif(!is.na(mat$age.days[i]) & mat$oedema[i]!=\"y\") {\r\n\t\t\r\n\t\tl.val<-bmianthro$l[bmianthro$age==mat$age.days[i] & bmianthro$sex==mat$sex[i]]\r\n\t\tm.val<-bmianthro$m[bmianthro$age==mat$age.days[i] & bmianthro$sex==mat$sex[i]]\r\n\t\ts.val<-bmianthro$s[bmianthro$age==mat$age.days[i] & bmianthro$sex==mat$sex[i]]\r\n\r\n\t\tmat$zbmi[i]<-(((mat$cbmi[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zbmi[i]) & mat$zbmi[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zbmi[i]<- 3+((mat$cbmi[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zbmi[i]) & mat$zbmi[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zbmi[i]<- (-3)+((mat$cbmi[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zbmi[i]<-NA\r\n\t\t\t\r\n}\r\n\r\nreturn(mat)\r\n}\r\n\r\n\r\n\r\n\r\n###################################################################################\r\n#### Main function starts here: igrowup\r\n###################################################################################\r\n\r\n###############################################################################################################################################\r\n#### This function can be used to: \r\n#### 1. Calculate the z-scores for the indicators: length/height-for-age, weight-for-age, weight-for-legnth/height and body mass index-for-age\r\n#### The output file with z-scores values is exported the file to an Excel spreadsheet (see readme file);\r\n#### 2. Calculate the prevalence rates of stunting, underweight, wasting and overweight, and z-scores means and standard deviations. Results\r\n#### are exported to an Excel spreadsheet, displayed by age group.\r\n###############################################################################################################################################\r\n\r\n\r\n#############################################################################\r\n##### Function for calculating the z-scores for all indicators\r\n#############################################################################\r\n\r\nigrowup.standard <- function(FileLab=\"Temp\",FilePath=\"C:\\\\Documents and Settings\",mydf,sex,age,age.month=F,weight=rep(NA,dim(mydf)[1]),lenhei=rep(NA,dim(mydf)[1]),measure=rep(NA,dim(mydf)[1]),\r\n headc=rep(NA,dim(mydf)[1]),armc=rep(NA,dim(mydf)[1]),triskin=rep(NA,dim(mydf)[1]),subskin=rep(NA,dim(mydf)[1]),oedema=rep(\"n\",dim(mydf)[1]),sw=rep(1,dim(mydf)[1])) {\r\n\t\r\n#############################################################################\r\n########### Calculating the z-scores for all indicators\r\n#############################################################################\r\n \r\n old <- options(warn=(-1))\r\n \r\n sex.x<-as.character(get(deparse(substitute(mydf)))[,deparse(substitute(sex))])\r\n age.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(age))])\r\n if(!missing(weight)) weight.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(weight))]) else weight.x<-as.double(weight)\r\n if(!missing(lenhei)) lenhei.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(lenhei))]) else lenhei.x<-as.double(lenhei)\r\n if(!missing(headc)) headc.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(headc))]) else headc.x<-as.double(headc)\r\n if(!missing(armc)) armc.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(armc))]) else armc.x<-as.double(armc)\r\n if(!missing(triskin)) triskin.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(triskin))]) else triskin.x<-as.double(triskin)\r\n if(!missing(subskin)) subskin.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(subskin))]) else subskin.x<-as.double(subskin)\r\n if(!missing(measure)) lorh.vec<-as.character(get(deparse(substitute(mydf)))[,deparse(substitute(measure))]) else lorh.vec<-as.character(measure)\r\n if(!missing(oedema)) oedema.vec<-as.character(get(deparse(substitute(mydf)))[,deparse(substitute(oedema))]) else oedema.vec<-oedema\r\n if(!missing(sw))\tsw<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(sw))])\telse sw<-as.double(sw)\r\n sw<-ifelse(is.na(sw),0,sw)\r\n\r\n\tsex.vec<-NULL\r\n\t\r\n\tif(age.month) age.vec<-rounde(age.x*30.4375) else age.vec<-rounde(age.x)\r\n\tlenhei.vec<-ifelse((!is.na(age.vec) & age.vec<731 & !is.na(lorh.vec) & (lorh.vec==\"h\" | lorh.vec==\"H\")),lenhei.x+0.7,#\r\n\t\t ifelse((!is.na(age.vec) & age.vec>=731 & !is.na(lorh.vec) & (lorh.vec==\"l\" | lorh.vec==\"L\")),lenhei.x-0.7,lenhei.x))\r\n \r\n sex.vec<-ifelse(!is.na(sex.x) & (sex.x==\"m\" | sex.x==\"M\" | sex.x==\"1\"),1,ifelse(!is.na(sex.x) & (sex.x==\"f\" | sex.x==\"F\" | sex.x==\"2\"),2,NA))\r\n\r\n lorh.vec<-ifelse(is.na(lorh.vec) | lorh.vec==\"l\" | lorh.vec==\"L\" | lorh.vec==\"h\" | lorh.vec==\"H\",lorh.vec,NA)\r\n\r\n oedema.vec<-ifelse(oedema.vec==\"n\" | oedema.vec==\"N\",\"n\",ifelse(oedema.vec==\"y\" | oedema.vec==\"Y\",\"y\",\"n\"))\r\n\r\n mat<-cbind.data.frame(age.x,as.integer(age.vec),as.double(sex.vec),weight.x,lenhei.x,lorh.vec,lenhei.vec,headc.x,armc.x,triskin.x,subskin.x,oedema.vec,sw,stringsAsFactors=F)\r\n\tnames(mat)<-c(\"age\",\"age.days\",\"sex\",\"weight\",\"len.hei\",\"l.h\",\"clenhei\",\"headc\",\"armc\",\"triskin\",\"subskin\",\"oedema\",\"sw\")\r\n\t\r\n\tmat$cbmi<-mat$weight/((lenhei.vec/100)^2)\r\n\tmat$zlen<-rep(NA,length(mat$age))\r\n\tmat$zwei<-rep(NA,length(mat$age))\r\n\tmat$zwfl<-rep(NA,length(mat$age))\r\n\tmat$zbmi<-rep(NA,length(mat$age))\r\n\tmat$zhc<-rep(NA,length(mat$age))\r\n\tmat$zac<-rep(NA,length(mat$age))\r\n\tmat$zts<-rep(NA,length(mat$age))\r\n\tmat$zss<-rep(NA,length(mat$age))\r\n\r\n\tmat$zlen<-rep(NA,length(mat$age))\r\n\tmat$flen<-rep(NA,length(mat$age))\r\n\tmat$fwei<-rep(NA,length(mat$age))\r\n\tmat$fwfl<-rep(NA,length(mat$age))\r\n\tmat$fbmi<-rep(NA,length(mat$age))\r\n\tmat$fhc<-rep(NA,length(mat$age))\r\n\tmat$fac<-rep(NA,length(mat$age))\r\n\tmat$fts<-rep(NA,length(mat$age))\r\n\tmat$fss<-rep(NA,length(mat$age))\r\n\r\n\r\n\r\n#############################################################################\r\n########### Calculating the z-scores for all indicators\r\n#############################################################################\r\n\r\ncat(\"Please wait while calculating z-scores...\\n\") \r\n\r\n### Length-for-age z-score\r\n\r\nmat<-calc.zlen(mat,lenanthro)\r\n\r\n### Head circumference-for-age z-score\r\n\r\nmat<-calc.zhc(mat,hcanthro)\r\n\r\n### Weight-for-age z-score\r\n\r\nmat<-calc.zwei(mat,weianthro)\r\n\r\n### Arm circumference-for-age z-score\r\n\r\nmat<-calc.zac(mat,acanthro)\r\n\r\n### Triceps skinfold-for-age z-score\r\n\r\nmat<-calc.zts(mat,tsanthro)\r\n\r\n### Subscapular skinfold-for-age z-score\r\n\r\nmat<-calc.zss(mat,ssanthro)\r\n\r\n### Weight-for-length/height z-score\r\n\r\nmat<-calc.zwfl(mat,wflanthro,wfhanthro)\r\n\r\n### BMI-for-age z-score\r\n\r\nmat<-calc.zbmi(mat,bmianthro)\r\n\r\n#### Rounding the z-scores to two decimals\r\n\r\n\t\t\tmat$zlen<-rounde(mat$zlen,digits=2)\r\n\t\t\tmat$zwei<-rounde(mat$zwei,digits=2)\r\n\t\t\tmat$zwfl<-rounde(mat$zwfl,digits=2)\r\n\t\t\tmat$zbmi<-rounde(mat$zbmi,digits=2)\r\n\t\t\tmat$zhc<-rounde(mat$zhc,digits=2)\r\n\t\t\tmat$zac<-rounde(mat$zac,digits=2)\r\n\t\t\tmat$zts<-rounde(mat$zts,digits=2)\r\n\t\t\tmat$zss<-rounde(mat$zss,digits=2)\r\n\r\n#### Flagging z-score values for individual indicators\r\n\r\n\t\t\tmat$flen<-ifelse(abs(mat$zlen) > 6,1,0)\r\n\t\t\tmat$fwei<-ifelse(mat$zwei > 5 | mat$zwei < (-6),1,0)\r\n\t\t\tmat$fwfl<-ifelse(abs(mat$zwfl) > 5,1,0)\r\n\t\t\tmat$fbmi<-ifelse(abs(mat$zbmi) > 5,1,0)\r\n\t\t\tmat$fhc<-ifelse(abs(mat$zhc) > 5,1,0)\r\n\t\t\tmat$fac<-ifelse(abs(mat$zac) > 5,1,0)\r\n\t\t\tmat$fts<-ifelse(abs(mat$zts) > 5,1,0)\r\n\t\t\tmat$fss<-ifelse(abs(mat$zss) > 5,1,0)\r\n\t\t\t\r\ncat(paste(\"Z-scores calculated - preparing matrix to be exported...\")) \r\n\r\nmat<-cbind.data.frame(mydf,mat[,-c(1,3:6,8:9)])\r\n\r\n\r\n###################################################################################################\r\n######### Export data frame with z-scores and flag variables\r\n###################################################################################################\r\n\r\nassign(\"matz\",mat,envir = .GlobalEnv)\r\n\r\nwrite.table(matz, file=paste(FilePath,\"\\\\\",FileLab,\"_z_st.csv\",sep=\"\"),na=\"\",row.names = FALSE,sep=\",\",quote = TRUE)\r\n\r\n\r\ncat(paste(\"Z-scores calculated and exported to \",FilePath,\"\\\\\",FileLab,\"_z_st.csv\\n\\n\",sep=\"\")) \r\n\r\n\r\n#######################################################################################################\r\n#### Calculating prevalences and summary statistics. \r\n#######################################################################################################\r\n\r\nif(any(sw <0)) stop(\"Negative weights are not allowed and program will stop. Prevalence tables will not be produced.\")\r\n\r\nmat.out<-mat\r\n\r\n################################\r\n#### Creating age group variable\r\n################################\r\n\r\nmat.out$sw.vec<-sw\r\nmat.out$sex.vec<-as.double(sex.vec)\r\nmat.out$oedema.vec<-as.character(oedema.vec)\r\n\r\nif(age.month) mat.out$agegr <- ifelse(!is.na(age.x) & age.x<6,0,ifelse(!is.na(age.x) & age.x<12,6,#\r\n ifelse(!is.na(age.x) & age.x<24,12,ifelse(!is.na(age.x) & age.x<36,24,#\r\n ifelse(!is.na(age.x) & age.x<48,36,ifelse(!is.na(age.x) & age.x<61,48,NA) )))))\r\n\r\nelse mat.out$agegr <- ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<6,0,ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<12,6,#\r\n ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<24,12,ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<36,24,#\r\n ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<48,36,ifelse(!is.na(mat.out$age.days) & mat.out$age.days/30.4375<61,48,NA) )))))\r\n\r\n##############################################\r\n#### Make z-score as missing if it is flagged\r\n##############################################\r\n\r\nmat.out$zlen<-ifelse(!is.na(mat.out$flen) & mat.out$flen!=0,NA,mat.out$zlen)\r\nmat.out$zwei<-ifelse(!is.na(mat.out$fwei) & mat.out$fwei!=0,NA,mat.out$zwei)\r\nmat.out$zwfl<-ifelse(!is.na(mat.out$fwfl) & mat.out$fwfl!=0,NA,mat.out$zwfl)\r\nmat.out$zbmi<-ifelse(!is.na(mat.out$fbmi) & mat.out$fbmi!=0,NA,mat.out$zbmi)\r\nmat.out$zhc<-ifelse(!is.na(mat.out$fhc) & mat.out$fhc!=0,NA,mat.out$zhc)\r\nmat.out$zac<-ifelse(!is.na(mat.out$fac) & mat.out$fac!=0,NA,mat.out$zac)\r\nmat.out$zts<-ifelse(!is.na(mat.out$fts) & mat.out$fts!=0,NA,mat.out$zts)\r\nmat.out$zss<-ifelse(!is.na(mat.out$fss) & mat.out$fss!=0,NA,mat.out$zss)\r\n\r\n##############################################\r\n#### Include all levels of age group variable\r\n##############################################\r\n\r\nmat.aux<-as.data.frame(cbind(array(rep(NA,((dim(mat.out)[2]-1)*6)),dim=c(6,(dim(mat.out)[2]-1)) ),c(0,6,12,24,36,48)))\r\nnames(mat.aux)<-names(mat.out)\r\nmat.out<-rbind(mat.out,mat.aux)\r\n\r\n##############################################################################################\r\n#### Make Oedema variable to be \"n\" if age greater than 60 completed months (>=61 months).\r\n#### This is beacuse children with oedema counts in the prevalence even if z-score is missing\r\n#### for weight related indicators.\r\n##############################################################################################\r\n\r\nmat.out$oedema.vec<-ifelse((!is.na(mat.out$age.days) & mat.out$age.days/30.4375>=61) | mat.out$oedema.vec==\"NA\",\"n\",mat.out$oedema.vec)\r\n\r\n#####################################################################################################################################################\r\n#### Creating matrix with estimated prevalences, confidence intervals, and means and standard deviations of z-scores and exporting it to Excel file.\r\n#####################################################################################################################################################\r\n\r\ncat(\"\\nPlease wait while calculating prevalences and z-score summary statistics...\\n\") \r\n\r\n#### Sexes combined\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<-t(cbind.data.frame(#\r\n prevnh(-3,mat.out$zwei,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-3, z$zwei, z$sw.vec, z$oedema.vec)),#\r\n prevnh.L(-3,mat.out$zlen,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zlen, z$sw.vec)),#\r\n prevnh(-3,mat.out$zwfl,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-3, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevnh(-3,mat.out$zbmi,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-3, z$zbmi, z$sw.vec, z$oedema.vec))))\r\n\r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh(-2,mat.out$zwei,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-2, z$zwei, z$sw.vec, z$oedema.vec)),#\r\n prevnh.L(-2,mat.out$zlen,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zlen, z$sw.vec)),#\r\n prevnh(-2,mat.out$zwfl,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-2, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevnh(-2,mat.out$zbmi,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-2, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +1 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(1,mat.out$zwfl,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(1, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(1,mat.out$zbmi,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(1, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +2 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(2,mat.out$zwfl,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(2, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(2,mat.out$zbmi,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(2, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +3 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(3,mat.out$zwfl,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(3, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(3,mat.out$zbmi,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(3, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out$zwei,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zwei,z$sw.vec)),#\r\n wmean(mat.out$zlen,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zlen,z$sw.vec)),#\r\n wmean(mat.out$zwfl,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zwfl,z$sw.vec)),#\r\n wmean(mat.out$zbmi,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zbmi,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out$zwei,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zwei,z$sw.vec)),#\r\n wsd(mat.out$zlen,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zlen,z$sw.vec)),#\r\n wsd(mat.out$zwfl,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zwfl,z$sw.vec)),#\r\n wsd(mat.out$zbmi,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zbmi,z$sw.vec)))))\r\n\r\n\r\n####################################################################################################################\r\n##### Creating matrix to export as Excel file\r\n\r\nmat[1:14,8]<-mat[1:14,17]\r\nmat[1:14,9]<-mat[1:14,18]\r\nmat[1:14,10:18]<-array(rep(\"\",126),dim=c(14,9))\r\nrm(mat1)\r\nmat1<-rbind(c(\"Set 1:\",\"Sexes\",\"combined\",rep(\"\",15)),c(\"Weight\",\"-for-\",\"age\",rep(\"\",15)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\",\"\",\"\", \"\",\"\",\"\", \"\",\"\",\"\", \"\"),mat[1:7,],#\r\n c(\"Length\",\"/height\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\",\"\",\"\", \"\",\"\",\"\", \"\",\"\",\"\", \"\"),mat[8:14,],#\r\n c(\"Weight\",\"-for-\",\"length\",\"/height\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[15:21,],#\r\n c(\"BMI\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[22:28,])\r\n\r\nfor(j in 1:dim(mat1)[2]) mat1[,j]<-ifelse(mat1[,j]==\"NA\" | mat1[,j]==\"NaN\",\"\",mat1[,j])\r\n \r\nmat1<-cbind(c(\"\",rep(c(\"\",\" Age\",\" 0-60\",\"0-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),4)),mat1)\r\n\r\n\t\r\n####################################################################################################################\r\n\r\n##### For boys and girls\r\n\r\nfor(i in 1:2) {\r\n\r\nmat.out.sex<-mat.out[!is.na(mat.out$sex.vec) & mat.out$sex.vec==i,]\t\r\n\r\nmat.aux<-as.data.frame(cbind(array(rep(NA,((dim(mat.out.sex)[2]-1)*6)),dim=c(6,(dim(mat.out.sex)[2]-1)) ),c(0,6,12,24,36,48)))\r\nnames(mat.aux)<-names(mat.out.sex)\r\nmat.out.sex<-rbind.data.frame(mat.out.sex,mat.aux )\r\nmat.out.sex$oedema.vec<-ifelse((!is.na(mat.out.sex$age.days) & mat.out.sex$age.days/30.4375>=61) | mat.out.sex$oedema.vec==\"NA\",\"n\",mat.out.sex$oedema.vec)\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<-t(cbind.data.frame(#\r\n prevnh(-3,mat.out.sex$zwei,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-3, z$zwei, z$sw.vec, z$oedema.vec)),#\r\n prevnh.L(-3,mat.out.sex$zlen,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zlen, z$sw.vec)),#\r\n prevnh(-3,mat.out.sex$zwfl,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-3, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevnh(-3,mat.out.sex$zbmi,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-3, z$zbmi, z$sw.vec, z$oedema.vec))))\r\n\r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh(-2,mat.out.sex$zwei,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-2, z$zwei, z$sw.vec, z$oedema.vec)),#\r\n prevnh.L(-2,mat.out.sex$zlen,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zlen, z$sw.vec)),#\r\n prevnh(-2,mat.out.sex$zwfl,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-2, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevnh(-2,mat.out.sex$zbmi,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-2, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +1 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(1,mat.out.sex$zwfl,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(1, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(1,mat.out.sex$zbmi,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(1, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +2 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(2,mat.out.sex$zwfl,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(2, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(2,mat.out.sex$zbmi,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(2, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +3 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n array(rep(NA,28),dim=c(4,7)),#\r\n prevph(3,mat.out.sex$zwfl,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(3, z$zwfl, z$sw.vec, z$oedema.vec)),#\r\n prevph(3,mat.out.sex$zbmi,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(3, z$zbmi, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out.sex$zwei,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zwei,z$sw.vec)),#\r\n wmean(mat.out.sex$zlen,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zlen,z$sw.vec)),#\r\n wmean(mat.out.sex$zwfl,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zwfl,z$sw.vec)),#\r\n wmean(mat.out.sex$zbmi,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zbmi,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out.sex$zwei,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zwei,z$sw.vec)),#\r\n wsd(mat.out.sex$zlen,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zlen,z$sw.vec)),#\r\n wsd(mat.out.sex$zwfl,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zwfl,z$sw.vec)),#\r\n wsd(mat.out.sex$zbmi,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zbmi,z$sw.vec)))))\r\n\r\n####################################################################################################################\r\n##### Creating matrix to export as Excel file\r\n\r\nmat[1:14,8]<-mat[1:14,17]\r\nmat[1:14,9]<-mat[1:14,18]\r\nmat[1:14,10:18]<-array(rep(\"\",126),dim=c(14,9))\r\n\r\nmat2<-rbind(c(paste(\"Set \",i+1,\":\",sep=\"\"),c(\"Males\",\"Females\")[i],rep(\"\",16)),c(\"Weight\",\"-for-\",\"age\",rep(\"\",15)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\",\"\",\"\", \"\",\"\",\"\", \"\",\"\",\"\", \"\"),mat[1:7,],#\r\n c(\"Length\",\"/height\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\",\"\",\"\", \"\",\"\",\"\", \"\",\"\",\"\", \"\"),mat[8:14,],#\r\n c(\"Weight\",\"-for-\",\"length\",\"/height\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[15:21,],#\r\n c(\"BMI\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[22:28,])\r\n\r\n\r\nfor(j in 1:dim(mat2)[2]) mat2[,j]<-ifelse(mat2[,j]==\"NA\" | mat2[,j]==\"NaN\",\"\",mat2[,j])\r\n \r\nmat2<-cbind(c(\"\",rep(c(\"\",\" Age\",\" 0-60\",\" 0-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),4)),mat2)\r\n\r\nnames(mat2)<-names(mat1)\r\n\t\r\nmat1<-rbind(mat1,mat2)\r\n\r\n} #### End of loop for sex\r\n\r\n###################################################################################################################\r\n######### Creating another matrix for the second set of indicators\r\n###################################################################################################################\r\n\r\n#####################################################################################################################################################\r\n#### Creating matrix with estimated prevalences, confidence intervals, and means and standard deviations of z-scores and exporting it to Excel file.\r\n#####################################################################################################################################################\r\n\r\n#### Sexes combined\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<-t(cbind.data.frame(#\r\n prevnh.L(-3,mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zhc, z$sw.vec)),#\r\n prevnh.L(-3,mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zac, z$sw.vec)),#\r\n prevnh.L(-3,mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zts, z$sw.vec)),#\r\n prevnh.L(-3,mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zss, z$sw.vec))))\r\n\r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh.L(-2,mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zhc, z$sw.vec)),#\r\n prevnh.L(-2,mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zac, z$sw.vec)),#\r\n prevnh.L(-2,mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zts, z$sw.vec)),#\r\n prevnh.L(-2,mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +1 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(1,mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(1, z$zhc, z$sw.vec)),#\r\n prevph.L(1,mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(1, z$zac, z$sw.vec)),#\r\n prevph.L(1,mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(1, z$zts, z$sw.vec)),#\r\n prevph.L(1,mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(1, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +2 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(2,mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(2, z$zhc, z$sw.vec)),#\r\n prevph.L(2,mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(2, z$zac, z$sw.vec)),#\r\n prevph.L(2,mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(2, z$zts, z$sw.vec)),#\r\n prevph.L(2,mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(2, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +3 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(3,mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(3, z$zhc, z$sw.vec)),#\r\n prevph.L(3,mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(3, z$zac, z$sw.vec)),#\r\n prevph.L(3,mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(3, z$zts, z$sw.vec)),#\r\n prevph.L(3,mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(3, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zhc,z$sw.vec)),#\r\n wmean(mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zac,z$sw.vec)),#\r\n wmean(mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zts,z$sw.vec)),#\r\n wmean(mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zss,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out$zhc,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zhc,z$sw.vec)),#\r\n wsd(mat.out$zac,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zac,z$sw.vec)),#\r\n wsd(mat.out$zts,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zts,z$sw.vec)),#\r\n wsd(mat.out$zss,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zss,z$sw.vec)))))\r\n\r\n\r\n####################################################################################################################\r\n##### Exporting matrix to Excel file\r\n\r\n\r\nmat3<-rbind(c(\"Set 1:\",\"Sexes\",\"combined\",rep(\"\",15)),c(\"Head \",\"circumference\",\"-for-\",\"age\",rep(\"\",14)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[1:7,],#\r\n c(\"MUAC\",\"-for-\",\"age\",\"\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[8:14,],#\r\n c(\"Triceps \",\"skinfold\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[15:21,],#\r\n c(\"Subscapular \",\"skinfold\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[22:28,])\r\n\r\nfor(j in 1:dim(mat3)[2]) mat3[,j]<-ifelse(mat3[,j]==\"NA\" | mat3[,j]==\"NaN\",\"\",mat3[,j])\r\n\r\n\r\nmat3<-cbind.data.frame(c(\"\",c(c(\"\",\" Age\",\" 0-60\",\" 0-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),rep(c(\"\",\" Age\",\" 3-60\",\" 3-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),3))),mat3)\r\n\r\n####################################################################################################################\r\n\r\n##### For boys and girls\r\n\r\nfor(i in 1:2) {\r\n\r\nmat.out.sex<-mat.out[!is.na(mat.out$sex.vec) & mat.out$sex.vec==i,]\r\nmat.aux<- as.data.frame(cbind(array(rep(NA,((dim(mat.out.sex)[2]-1)*6)),dim=c(6,(dim(mat.out.sex)[2]-1)) ),c(0,6,12,24,36,48))\t)\r\nnames(mat.aux)<-names(mat.out.sex)\r\nmat.out.sex<-rbind(mat.out.sex, mat.aux)\r\nmat.out.sex$oedema.vec<-ifelse((!is.na(mat.out.sex$age.days) & mat.out.sex$age.days/30.4375>=61) | mat.out.sex$oedema.vec==\"NA\",\"n\",mat.out.sex$oedema.vec)\r\n\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<-t(cbind.data.frame(#\r\n prevnh.L(-3,mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zhc, z$sw.vec)),#\r\n prevnh.L(-3,mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zac, z$sw.vec)),#\r\n prevnh.L(-3,mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zts, z$sw.vec)),#\r\n prevnh.L(-3,mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zss, z$sw.vec))))\r\n\r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh.L(-2,mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zhc, z$sw.vec)),#\r\n prevnh.L(-2,mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zac, z$sw.vec)),#\r\n prevnh.L(-2,mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zts, z$sw.vec)),#\r\n prevnh.L(-2,mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +1 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(1,mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(1, z$zhc, z$sw.vec)),#\r\n prevph.L(1,mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(1, z$zac, z$sw.vec)),#\r\n prevph.L(1,mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(1, z$zts, z$sw.vec)),#\r\n prevph.L(1,mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(1, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +2 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(2,mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(2, z$zhc, z$sw.vec)),#\r\n prevph.L(2,mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(2, z$zac, z$sw.vec)),#\r\n prevph.L(2,mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(2, z$zts, z$sw.vec)),#\r\n prevph.L(2,mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(2, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### % > +3 SD for weight-for-length/height and bmi-for-age\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph.L(3,mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(3, z$zhc, z$sw.vec)),#\r\n prevph.L(3,mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(3, z$zac, z$sw.vec)),#\r\n prevph.L(3,mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(3, z$zts, z$sw.vec)),#\r\n prevph.L(3,mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(3, z$zss, z$sw.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zhc,z$sw.vec)),#\r\n wmean(mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zac,z$sw.vec)),#\r\n wmean(mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zts,z$sw.vec)),#\r\n wmean(mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zss,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out.sex$zhc,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zhc,z$sw.vec)),#\r\n wsd(mat.out.sex$zac,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zac,z$sw.vec)),#\r\n wsd(mat.out.sex$zts,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zts,z$sw.vec)),#\r\n wsd(mat.out.sex$zss,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zss,z$sw.vec)))))\r\n\r\n####################################################################################################################\r\n##### Exporting matrix to Excel file\r\n\r\nmat4<-rbind.data.frame(c(paste(\"Set \",i+1,\":\",sep=\"\"),c(\"Males\",\"Females\")[i],rep(\"\",16)),c(\"Head \",\"circumference\",\"-for-\",\"age\",rep(\"\",14)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[1:7,],#\r\n c(\"MUAC\",\"-for-\",\"age\",\"\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[8:14,],#\r\n c(\"Triceps \",\"skinfold\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[15:21,],#\r\n c(\"Subscapular \",\"skinfold\",\"-for-\",\"age\",rep(\"\",14)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[22:28,])\r\n\r\nfor(j in 1:dim(mat4)[2]) mat4[,j]<-ifelse(mat4[,j]==\"NA\" | mat4[,j]==\"NaN\",\"\",mat4[,j])\r\n\r\nmat4<-cbind.data.frame(c(\"\",c(c(\"\",\" Age\",\" 0-60\",\" 0-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),rep(c(\"\",\" Age\",\" 3-60\",\" 3-5\",\" 6-11\",\" 12-23\",\" 24-35\",\" 36-47\",\" 48-60\"),3))),mat4)\r\n\r\nnames(mat4)<-names(mat3)\r\nmat3<-rbind.data.frame(mat3,mat4)\r\n\r\n} #### End of loop for sex\r\n\r\nnames(mat3)<-names(mat1)\r\n\r\nmat3<-rbind.data.frame(mat1,mat3)\r\n\r\n###################################################################################################################\r\n######### Export table with prevalence values and their confidence intervals, and mean and SD of the z-scores\r\n###################################################################################################################\r\n\r\nassign(\"matprev\",mat3,envir = .GlobalEnv)\r\n\r\nwrite.table(matprev, file=paste(FilePath,\"\\\\\",FileLab,\"_prev_st.csv\",sep=\"\"),na=\" \",row.names = FALSE,col.names=F,sep=\",\",quote = TRUE)\r\n\r\ncat(paste(\"Prevalences and z-score summary statistics calculated and exported to \",FilePath,\"\\\\\",FileLab,\"_prev_st.csv\\n\",sep=\"\")) \r\n\r\non.exit(options(old))\r\n\r\ninvisible()\r\n\r\n\r\n} #### End of function igrowup.standard\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4c801fd7b6544e80fb39cd46048cc9815f6ab178", "size": 54035, "ext": "r", "lang": "R", "max_stars_repo_path": "data_preprocess/data/igrowup_R/igrowup_standard.r", "max_stars_repo_name": "hathawayj/growthstandards", "max_stars_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-09-23T20:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:01:30.000Z", "max_issues_repo_path": "data_preprocess/data/igrowup_R/igrowup_standard.r", "max_issues_repo_name": "hathawayj/growthstandards", "max_issues_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-24T01:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T14:29:51.000Z", "max_forks_repo_path": "data_preprocess/data/igrowup_R/igrowup_standard.r", "max_forks_repo_name": "hathawayj/growthstandards", "max_forks_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-24T15:41:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T04:20:50.000Z", "avg_line_length": 57.3619957537, "max_line_length": 247, "alphanum_fraction": 0.5263255297, "num_tokens": 17462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.493763998531117}} {"text": "# load packages\nlibrary(dplyr)\nlibrary(tidyr)\nlibrary(ggplot2)\nlibrary(mirt)\nlibrary(readxl)\n\n# Function for DIF Extraction\nget.dif.items <- function(out.list,p.val,parms){\n dif.items <- NULL\n non.dif.items <- NULL\n for(i in 1:length(out.list)){ # loop list of items\n chi.sq <- out.list[[i]][2,6] #2 groups, so second row, and 6th column\n df <- out.list[[i]][2,7]\n p <- out.list[[i]][2,8]\n i.name <- names(out.list[i])\n d <- c(i.name,chi.sq,df,p,parms[i,])\n \n if(p < p.val){\n dif.items <- rbind(dif.items,d)\n }else{\n non.dif.items <- rbind(non.dif.items,d)\n }\n }\n if (!is.null(dif.items)) {\n dif.items <- data.frame(dif.items, row.names = NULL)\n colnames(dif.items)[1] <- \"item\"\n colnames(dif.items)[2] <- \"chi.sq\"\n colnames(dif.items)[3] <- \"df\"\n colnames(dif.items)[4] <- \"p\"\n \n }\n if (!is.null(non.dif.items)) {\n non.dif.items <- data.frame(non.dif.items, row.names = NULL)\n colnames(non.dif.items)[1] <- \"item\"\n colnames(non.dif.items)[2] <- \"chi.sq\"\n colnames(non.dif.items)[3] <- \"df\"\n colnames(non.dif.items)[4] <- \"p\"\n }\n r.list <- list(dif_items = dif.items, no_dif = non.dif.items)\n return(r.list)\n}\n\n# load data\nbelin <- read_excel('Data/IExcel_IRT_All5A.xlsx')\n\n\n# Items names (column names of items)\nenglish_items <- dplyr::select(belin, starts_with('Eng_AV_'))\nmath_items <- dplyr::select(belin, starts_with('Math_AV_'))\nread_items <- dplyr::select(belin, starts_with('Read_AV_'))\nsci_items <- dplyr::select(belin, starts_with(\"Sci_AV_\"))\n\n# group variable\ngrade <- as.character(belin$Grade)\n\n\n# Eigenvalue\nenglish_eigen <- eigen(cor(english_items))$values\nenglish_eigen[1] / english_eigen[2]\nenglish_eigen[1] / sum(english_eigen)\n\nmath_eigen <- eigen(cor(math_items))$values\nmath_eigen[1] / math_eigen[2]\nmath_eigen[1] / sum(math_eigen)\n\nread_eigen <- eigen(cor(read_items))$values\nread_eigen[1] / read_eigen[2]\nread_eigen[1] / sum(read_eigen)\n\nsci_eigen <- eigen(cor(sci_items))$values\nsci_eigen[1] / sci_eigen[2]\nsci_eigen[1] / sum(sci_eigen)\n\n\n# CTT DIF ----\nlibrary(difR)\n\nbelin_mh <- cbind(math_items, select(belin, Grade))\nnames = c('5', '6')\ndifGMH(belin_mh, group = \"Grade\", focal.name = names,\n p.adjust.method = \"BH\")\n\ndifGenLogistic(belin_mh, group = \"Grade\", focal.name = names,\n p.adjust.method = \"BH\")\ndifGenLogistic(belin_mh, group = \"Grade\", focal.name = names,\n p.adjust.method = \"BH\", type = 'nudif')\ndifGenLogistic(belin_mh, group = \"Grade\", focal.name = names,\n p.adjust.method = \"BH\", type = 'udif')\n\n# logistic regression ---\nbelin_mh <- belin_mh %>%\n mutate(total_score = rowSums(select(., starts_with(\"Math_AV_\"))))\n\nmath_it2_log <- glm(Math_AV_2 ~ 1 + total_score + factor(Grade) + total_score:factor(Grade),\n data = belin_mh, family = binomial)\nsummary(math_it2_log)\n\n#--------------------------------------------------------\n# English -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_eng <- multipleGroup(data = english_items, model = 1, group = grade,\n invariance = c(colnames(english_items), \n 'free_means', 'free_var')) # 132 iterations\n\nconstrained_parameters_eng <- coef(mult_group_eng, simplify = TRUE)[[1]][[1]]\ndif_add_eng <- DIF(mult_group_eng, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\n\n# dif_out_eng <- get.dif.items(out.list = dif_add_eng, p.val = .05,\n# parms = constrained_parameters_eng)\n# dif_out_eng\n\n# Freely estimate items with DIF.\nmodel_eng <- '\n I = 1-40\n CONSTRAINB = (1-13, 15-20, 22, 23, 25, 28, 30-36, 39, a1), \n (1-13, 15-20, 22, 23, 25, 28, 30-36, 39, d)\n'\nmult_group_part_eng <- multipleGroup(data = english_items, model = model_eng, \n group = grade,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 135 Iterations\nparameters_eng <- coef(mult_group_part_eng, simplify = TRUE)\n\n#--------------------------------------------------------\n# Mathematics -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_math <- multipleGroup(data = math_items, model = 1, group = grade,\n invariance = c(colnames(math_items), \n 'free_means', 'free_var')) # 186 iterations\n\nconstrained_parameters_math <- coef(mult_group_math, simplify = TRUE)[[1]][[1]]\ndif_add_math <- DIF(mult_group_math, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_math\n\n# dif_out_math <- get.dif.items(out.list = dif_add_math, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_math\n\n# Freely estimate items with DIF.\nmodel_math <- '\n I = 1-30\n CONSTRAINB = (1, 4, 5, 8, 11, 13, 14, 17-18, 21-23, 25-30, a1), \n (1, 4, 5, 8, 11, 13, 14, 17-18, 21-23, 25-30, d)\n'\nmult_group_part_math <- multipleGroup(data = math_items, model = model_math, \n group = grade,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 243 Iterations\nparameters_math <- coef(mult_group_part_math, simplify = TRUE)\n\n# probability ----\nprob_item2 <- data.frame(rbind(\n cbind(probtrace(extract.item(mult_group_part_math, 2, group = 1), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 4'),\n cbind(probtrace(extract.item(mult_group_part_math, 2, group = 2), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 5'),\n cbind(probtrace(extract.item(mult_group_part_math, 2, group = 3), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 6')\n )\n )\nprob_item2$P.0 <- as.numeric(as.character(prob_item2$P.0))\nprob_item2$P.1 <- as.numeric(as.character(prob_item2$P.1))\nprob_item2$theta <- as.numeric(as.character(prob_item2$theta))\n\np <- ggplot(prob_item2, aes(x = theta, y = P.1)) + \n geom_line(aes(group = group, color = group), size = 2) + \n scale_x_continuous(\"Aptitude\", breaks = seq(-6, 6, 1)) + \n ylab(\"Probability Correct\") + \n scale_color_grey(\"\", start = 0) + \n theme_bw(base_size = 12)\nggsave(filename = \"icc_math2.png\", plot = p, dpi = 'retina', height = 4, width = 6,\n path = 'paper/figs')\n\n# iteminformation ----\ninfo_item2 <- data.frame(rbind(\n cbind(iteminfo(extract.item(mult_group_part_math, 2, group = 1), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 4'),\n cbind(iteminfo(extract.item(mult_group_part_math, 2, group = 2), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 5'),\n cbind(iteminfo(extract.item(mult_group_part_math, 2, group = 3), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 6')\n)\n)\ninfo_item2$V1 <- as.numeric(as.character(info_item2$V1))\ninfo_item2$theta <- as.numeric(as.character(info_item2$theta))\n\np <- ggplot(info_item2, aes(x = theta, y = V1)) + \n geom_line(aes(group = group, color = group), size = 2) + \n scale_x_continuous(\"Aptitude\", breaks = seq(-6, 6, 1)) + \n ylab(\"Item Information\") + \n viridis::scale_color_viridis(\"\", discrete = TRUE, option = 'magma') + \n theme_bw(base_size = 12)\nggsave(filename = \"info_math2.png\", plot = p, dpi = 'retina', height = 4, width = 6,\n path = 'paper/figs')\n\n# Model Implied test score ----\n# test_scores <- data.frame(rbind(\n# cbind(expected.test(extract.group(mult_group_part_math, 1), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 4'),\n# cbind(expected.test(extract.group(mult_group_part_math, 2), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 5'),\n# cbind(expected.test(extract.group(mult_group_part_math, 3), Theta = seq(-6, 6, .1)), theta = seq(-6, 6, .1), group = 'Grade 6')\n# )\n# )\n\ntmp <- plot(mult_group_part_math)\n\n# tmp$panel.args\npltdata <- data.frame(lapply(tmp$panel.args, function(x) do.call(cbind, x))[[1]])\nnames(pltdata) <- c(\"theta\", \"tcc\", \"num\")\npltdata$group <- paste0('Grade ', tmp$panel.args.common$groups)\n\np <- ggplot(pltdata, aes(x = theta, y = tcc)) + \n geom_line(aes(group = group, color = group), size = 2) + \n scale_x_continuous(\"Aptitude\", breaks = seq(-6, 6, 1)) + \n scale_y_continuous(\"Model Implied Number Correct\", breaks = seq(0, 30, 5),\n limits = c(0, 30)) + \n scale_color_grey(\"\") + \n theme_bw(base_size = 12)\nggsave(filename = \"test_math.png\", plot = p, dpi = 'retina', height = 4, width = 6,\n path = 'paper/figs')\n\n# Using plink to get model implied test scores ----\nlibrary(plink)\n\nparameters_math <- coef(mult_group_part_math, simplify = TRUE, \n IRTpars = TRUE)\n\nitem_info <- bind_rows(\n cbind(group = 'Grade 4', drm(data.frame(parameters_math[[1]]$items[, 1:2]), seq(-6, 6, .1))@prob\n ),\n cbind(group = 'Grade 5', drm(data.frame(parameters_math[[2]]$items[, 1:2]), seq(-6, 6, .1))@prob\n ),\n cbind(group = 'Grade 6', drm(data.frame(parameters_math[[3]]$items[, 1:2]), seq(-6, 6, .1))@prob\n )\n) %>%\n mutate(tcc = rowSums(select(., contains('item'))))\n\np <- ggplot(item_info, aes(x = theta1, y = tcc)) + \n geom_line(aes(group = group, color = group), size = 2) + \n scale_x_continuous(\"Aptitude\", breaks = seq(-6, 6, 1)) + \n scale_y_continuous(\"Model Implied Number Correct\", breaks = seq(0, 30, 5),\n limits = c(0, 30)) + \n scale_color_grey(\"\", start = 0) + \n theme_bw(base_size = 12)\nggsave(filename = \"test_math.png\", plot = p, dpi = 'retina', height = 4, width = 6,\n path = 'paper/figs')\n\n#--------------------------------------------------------\n# Reading -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_read <- multipleGroup(data = read_items, model = 1, group = grade,\n invariance = c(colnames(read_items), \n 'free_means', 'free_var')) # 144 iterations\n\nconstrained_parameters_read <- coef(mult_group_read, simplify = TRUE)[[1]][[1]]\ndif_add_read <- DIF(mult_group_read, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_read\n\n# dif_out_read <- get.dif.items(out.list = dif_add_read, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_read\n\n# Freely estimate items with DIF.\nmodel_read <- '\n I = 1-30\n CONSTRAINB = (2-18, 21, 24-28, 30, a1), \n (2-18, 21, 24-28, 30, d)\n'\nmult_group_part_read <- multipleGroup(data = read_items, model = model_read, \n group = grade,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 144 Iterations\nparameters_read <- coef(mult_group_part_read, simplify = TRUE)\n\n#--------------------------------------------------------\n# Science -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_sci <- multipleGroup(data = sci_items, model = 1, group = grade,\n invariance = c(colnames(sci_items), \n 'free_means', 'free_var')) # 171 iterations\n\nconstrained_parameters_sci <- coef(mult_group_sci, simplify = TRUE)[[1]][[1]]\ndif_add_sci <- DIF(mult_group_sci, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_sci\n\n# dif_out_sci <- get.dif.items(out.list = dif_add_sci, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_sci\n\n# Freely estimate items with DIF.\nmodel_sci <- '\n I = 1-28\n CONSTRAINB = (2-14, 16-21, 23-28, a1), \n (2-14, 16-21, 23-28, d)\n'\nmult_group_part_sci <- multipleGroup(data = sci_items, model = model_sci, \n group = grade,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 122 Iterations\nparameters_sci <- coef(mult_group_part_sci, simplify = TRUE)\n\n\n# save models\nsave(mult_group_part_eng, mult_group_part_math, mult_group_part_read, mult_group_part_sci,\n file = 'Data/multiple_group_models.rda')\n\nM2(mult_group_part_eng)\nM2(mult_group_part_math)\nM2(mult_group_part_read)\nM2(mult_group_part_sci)\n\n\n# Sex DIF ----\nsex <- as.character(belin$ngender)\n\n\n# English -----------------------------------------------\n# Fit multigroup IRT model sex is group.\nmult_group_eng <- multipleGroup(data = english_items, model = 1, group = sex,\n invariance = c(colnames(english_items), \n 'free_means', 'free_var')) # 30 iterations\n\nconstrained_parameters_eng <- coef(mult_group_eng, simplify = TRUE)[[1]][[1]]\ndif_add_eng <- DIF(mult_group_eng, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\n\n# dif_out_eng <- get.dif.items(out.list = dif_add_eng, p.val = .05,\n# parms = constrained_parameters_eng)\n# dif_out_eng\n\n# Freely estimate items with DIF.\nmodel_eng <- '\nI = 1-40\nCONSTRAINB = (1-8, 10, 12, 14-16, 18-30, 32, 34, 36-38, 40, a1), \n(1-8, 10, 12, 14-16, 18-30, 32, 34, 36-38, 40, d)\n'\nmult_group_part_eng <- multipleGroup(data = english_items, model = model_eng, \n group = sex,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 38 Iterations\nparameters_eng <- coef(mult_group_part_eng, simplify = TRUE)\n\n# Mathematics -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_math <- multipleGroup(data = math_items, model = 1, group = sex,\n invariance = c(colnames(math_items), \n 'free_means', 'free_var')) # 33 iterations\n\nconstrained_parameters_math <- coef(mult_group_math, simplify = TRUE)[[1]][[1]]\ndif_add_math <- DIF(mult_group_math, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_math\n\n# dif_out_math <- get.dif.items(out.list = dif_add_math, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_math\n\n# Freely estimate items with DIF.\nmodel_math <- '\nI = 1-30\nCONSTRAINB = (1-8, 10-12, 16-20, 22, 23, 25-28, 30, a1), \n(1-8, 10-12, 16-20, 22, 23, 25-28, 30, d)\n'\nmult_group_part_math <- multipleGroup(data = math_items, model = model_math, \n group = sex,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 19 Iterations\nparameters_math <- coef(mult_group_part_math, simplify = TRUE)\n\n#--------------------------------------------------------\n# Reading -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_read <- multipleGroup(data = read_items, model = 1, group = sex,\n invariance = c(colnames(read_items), \n 'free_means', 'free_var')) # 50 iterations\n\nconstrained_parameters_read <- coef(mult_group_read, simplify = TRUE)[[1]][[1]]\ndif_add_read <- DIF(mult_group_read, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_read\n\n# dif_out_read <- get.dif.items(out.list = dif_add_read, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_read\n\n# Freely estimate items with DIF.\nmodel_read <- '\n I = 1-30\n CONSTRAINB = (1, 4-9, 11-13, 15-20, 22, 23, 25-27, 29, a1), \n (1, 4-9, 11-13, 15-20, 22, 23, 25-27, 29, d)\n'\nmult_group_part_read <- multipleGroup(data = read_items, model = model_read, \n group = sex,\n invariance = c('free_means', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 54 Iterations\nparameters_read <- coef(mult_group_part_read, simplify = TRUE)\n\n#--------------------------------------------------------\n# Science -----------------------------------------------\n# Fit multigroup IRT model grade is group.\nmult_group_sci <- multipleGroup(data = sci_items, model = 1, group = sex,\n invariance = c(colnames(sci_items), \n 'free_mean', 'free_var')) # 27 iterations\n\nconstrained_parameters_sci <- coef(mult_group_sci, simplify = TRUE)[[1]][[1]]\ndif_add_sci <- DIF(mult_group_sci, c('a1', 'd'), scheme = 'drop',\n seq_state = .05)\ndif_add_sci\n\n# dif_out_sci <- get.dif.items(out.list = dif_add_sci, p.val = .05,\n# parms = constrained.parameters)\n# dif_out_sci\n\n# Freely estimate items with DIF.\nmodel_sci <- '\n I = 1-28\n CONSTRAINB = (1-3, 5, 6, 9-10, 13, 15-18, 20-21, 23-27, a1), \n (1-3, 5, 6, 9-10, 13, 15-18, 20-21, 23-27, d)\n'\nmult_group_part_sci <- multipleGroup(data = sci_items, model = model_sci, \n group = sex,\n invariance = c('free_mean', 'free_var'), \n #constrain = constrain, \n technical = list(NCYCLES = 2000)) # 39 Iterations\nparameters_sci <- coef(mult_group_part_sci, simplify = TRUE)\n", "meta": {"hexsha": "676989166ac06dc8eac8410176c17e9d733fd03b", "size": 17930, "ext": "r", "lang": "R", "max_stars_repo_path": "R/multigroup_irt.r", "max_stars_repo_name": "lebebr01/gcq-irt", "max_stars_repo_head_hexsha": "07b104dcc119ad045dbadacfc567627e022a0705", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/multigroup_irt.r", "max_issues_repo_name": "lebebr01/gcq-irt", "max_issues_repo_head_hexsha": "07b104dcc119ad045dbadacfc567627e022a0705", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/multigroup_irt.r", "max_forks_repo_name": "lebebr01/gcq-irt", "max_forks_repo_head_hexsha": "07b104dcc119ad045dbadacfc567627e022a0705", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6009280742, "max_line_length": 159, "alphanum_fraction": 0.5592861127, "num_tokens": 5058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4937592526151671}} {"text": "data(ms_world) ## measles case data\ndata(contact_countries) ## mapping of countries in ESEN2 to countries in POLYMOD\n\n## country-specific R0 scaling\ndata(polymod)\n\ncontact_r0 <- list()\nfor (country in survey_countries(polymod))\n{\n m <- contact_matrix(survey=polymod, countries=country, n=100, symmetric=TRUE,\n estimated.contact.age = \"sample\", sample.all.age.groups = TRUE,\n age.limits=seq(0, 65, by=5))\n contact_r0[[country]] <- vapply(m$matrices, function(x) {\n as.numeric(eigen(x$matrix, only.values = TRUE)$values[1])\n }, 0)\n}\n\ncontact_r0_means <- vapply(contact_r0, mean, 0)\nccr0 <- data.frame(country=names(contact_r0_means), contact_r0=contact_r0_means) %>%\n remove_rownames %>%\n mutate(rel_r0 = contact_r0 / mean(contact_r0))\n\ncr0 <- tibble(country=factor(names(contact_countries)), polymod=contact_countries) %>%\n remove_rownames %>%\n left_join(ccr0 %>%\n dplyr::rename(polymod=country) %>%\n mutate(polymod=as.character(polymod)), by=\"polymod\") %>%\n mutate(polymod=factor(polymod),\n country=countrycode(country, \"country.name\", \"eurostat.name\"))\n\nmodel_adjImm <- sero_adjImm %>%\n gather(variable, immunity, ends_with(\"_immunity\")) %>%\n separate(variable, c(\"model\", \"dump\")) %>%\n mutate(model=recode_factor(model, adjusted=\"contact-adjusted\", mean=\"plain\"),\n country=countrycode(country, \"country.name\", \"eurostat.name\")) %>%\n select(-dump) %>%\n left_join(cr0, by=c(\"country\")) %>%\n rename(scaled=rel_r0) %>%\n mutate(fixed=1) %>%\n gather(r0_model, rel_r0, fixed, scaled) %>%\n mutate(susceptibility=(1-immunity)*rel_r0) %>%\n select(-contact_r0, -rel_r0)\n\nsurvey_years <- model_adjImm %>%\n group_by(country) %>%\n summarise(survey_yr=as.integer(max(year, na.rm=TRUE)))\n\nms_cases <- ms_world %>%\n tbl_df() %>%\n inner_join(survey_years, by=(\"country\"))\n\nhorizon <- 10\n\nhorizon_col <- paste(\"years\", horizon, sep=\".\")\ncase_col <- paste(\"cases\", horizon, sep=\".\")\nms_cases %<>%\n replace_na(list(cases=0)) %>%\n mutate(!!horizon_col := if_else(year > survey_yr & year <= survey_yr + horizon, 1, 0),\n !!case_col := !!sym(horizon_col) * cases)\n\nmsw <- ms_cases %>%\n select(-year) %>%\n rename(year=survey_yr) %>%\n select(-starts_with(\"years.\")) %>%\n gather(variable, cases, starts_with(\"cases.\")) %>%\n separate(variable, c(\"dummy\", \"window\"), sep=\"\\\\.\") %>%\n mutate(window=as.integer(window)) %>%\n select(-dummy) %>%\n group_by(country, window, year) %>%\n summarise(sum.cases=sum(cases),\n max.cases=max(cases)) %>%\n rowwise %>%\n mutate(pop_df=list(wpp_age(country, year)),\n population=sum(pop_df$population)) %>%\n select(-pop_df) %>%\n ungroup %>%\n mutate(cases.per.million.per.year = signif(sum.cases / (population*window)*1e6),\n max.cases.per.million = signif(max.cases / (population)*1e6))\n\nthreshold_test <- seq(0.8, 1, by=0.01)\n\nmeasure <- \"cases.per.million.per.year\"\nmeasure_threshold <- 5\nmethod <- \"spearman\"\n\ncorr_coeff <- function(df)\n{\n corr <- cor.test(1 - df$susceptibility, log(df[[measure]]), method=method)\n correlation <- data.frame(corr[c(\"estimate\", \"p.value\")])\n\n outbreaks <- df[[measure]] > measure_threshold\n immunity <- 1 - df$susceptibility\n correct_threshold <-\n lapply(threshold_test, function(t) {sum(outbreaks == (immunity < t))})\n correct <-\n data.frame(threshold=threshold_test, correct=unlist(correct_threshold))\n\n n <- nrow(df)\n return(tibble(correlation=list(correlation), correct=list(correct), n))\n}\n\ncc <- model_adjImm %>%\n left_join(msw, by=c(\"country\", \"year\")) %>%\n group_by(sample, eqi, r0_model, model, vaccination, window) %>%\n nest %>%\n mutate(corr=map(data, corr_coeff)) %>%\n select(-data) %>%\n unnest(corr)\n\nscorr <- cc %>%\n unnest(correlation) %>%\n group_by(eqi, r0_model, model, vaccination, window) %>%\n summarise(p.value=mean(p.value),\n median=median(estimate),\n min.estimate=quantile(estimate, 0.05),\n max.estimate=quantile(estimate, 0.95),\n n=n()) %>%\n ungroup() %>%\n arrange(median) %>%\n mutate_at(vars(5:ncol(.)), signif, digits=2)\n\n## correlation summary table\nopts_current$set(label = \"correlations\")\nscorr %>%\n mutate(mean_ci=paste0(median, \"~(\", min.estimate, \", \", max.estimate, \")\")) %>%\n arrange(model, r0_model, eqi) %>%\n select(`Immunity model`=model, `$R_0$ model`=r0_model, `Vaccination model`=vaccination, `Equivocal samples`=eqi,\n `Correlation~(90\\\\% CI)`=mean_ci) %>%\n kable(\"latex\",\n escape=FALSE, linesep=\"\", booktabs=TRUE,\n caption=\"Spearman's rank correlation between immunity estimated from nationwide serology and~(if contact-adjusted) contact studies on the one hand and the mean number of cases in the 10 years following the studies on the other. The model with the greatest absolute correlation is highlighted in bold.\") %>%\n kable_styling(latex_options=c(\"hold_position\")) %>%\n write(\"table_2.tex\")\n\n## misclassification error\nsmce <- cc %>%\n unnest(correct) %>%\n group_by(eqi, r0_model, model, vaccination, window, threshold) %>%\n dplyr::summarise(median=median(1-correct/n),\n mean=mean(1-correct/n),\n min=mean-sd(1-correct/n),\n max=mean+sd(1-correct/n)) %>%\n ungroup\n\n## figures for paper\np <- ggplot(msw %>%\n arrange(cases.per.million.per.year) %>%\n mutate(country=factor(country, levels=unique(country))),\n aes(x=country, y=100*cases.per.million.per.year)) +\n geom_bar(stat=\"identity\") +\n geom_text(aes(label=scales::comma(max.cases)), position=position_dodge(width=0.9), vjust=-0.3) +\n expand_limits(y=50000) +\n theme(axis.text.x=element_text(angle = 45, vjust = 1, hjust = 1)) +\n scale_x_discrete(\"\") +\n geom_vline(xintercept=9.5, linetype=\"dotted\", lwd=0.7) +\n geom_hline(yintercept=500, linetype=\"dotted\", lwd=0.7) +\n scale_y_log10(\"Cases per year per million\",\n breaks=10^(0:4), labels=10^((-2):2))\nsave_plot(\"figure_1.pdf\", p, base_aspect_ratio = 1.9)\n\nsmce_select <- smce %>%\n filter(eqi == \"positive\", r0_model==\"fixed\", vaccination==\"projected\", threshold < 1)\n\np <- ggplot(smce_select, aes(x=threshold, y=mean, ymin=min, ymax=max)) +\n facet_grid(~model) +\n geom_point() +\n geom_line() +\n geom_ribbon(alpha=0.25) +\n scale_x_continuous(\"Threshold level\", label=scales::percent) +\n scale_y_continuous(\"Misclassification error\")\n\nsave_plot(\"figure_2.pdf\", p, base_aspect_ratio = 1.9, base_height = 3)\n\nnumber_formatter <- function(x)\n{\n return(as.character(if_else(x >= 10, round(x), if_else(x >= 1, round(x, 1), signif(x, 2)))))\n}\n\nesen2_adjImm <- model_adjImm %>%\n filter(eqi == \"positive\", vaccination==\"projected\") %>%\n group_by(country, model) %>%\n summarise(immunity=mean(immunity)) %>%\n mutate(immunity=signif(immunity, 2)) %>%\n spread(model, immunity)\n\n## pretty format summary table\nopts_current$set(label = \"outbreaks\")\nmsw %>%\n left_join(esen2_adjImm) %>%\n arrange(max.cases.per.million) %>%\n dplyr::select(country, sum.cases, max.cases, cases.per.million.per.year, max.cases.per.million,\n `contact-adjusted`, plain) %>%\n mutate(country=as.character(country),\n sum.cases=as.integer(sum.cases),\n max.cases=as.integer(max.cases),\n cases.per.million.per.year=formattable(cases.per.million.per.year, formatter=number_formatter),\n max.cases.per.million=formattable(max.cases.per.million, formatter=number_formatter)) %>%\n mutate_all(linebreak) %>%\n kable(\"latex\",\n col.names=linebreak(c(\"Country\",\n \"Total\\n(10 years)\",\n \"Maximum\\nannual\",\n \"Mean annual\\n(per million)\",\n \"Maximum\\nannual\\n(per million)\",\n \"contact-\\nadjusted\",\n \"plain\"),\n align=\"c\"),\n escape=FALSE, linesep=\"\", booktabs=TRUE,\n caption=\"Measles cases in the 10 years following the ESEN2 serological study, and mean estimated population immunity~(contact-adjusted or not, with fixed $R_0$ and equivocal samples interpreted as positive) based on the study and adjusted for vaccination uptake.\") %>%\n add_header_above(c(\" \", Cases=4, Immunity=2)) %>%\n kable_styling(latex_options=c(\"hold_position\")) %>%\n ## kable_as_image(\"esen2\") %>%\n write(\"table_1.tex\")\n", "meta": {"hexsha": "c896989b7852433ba418f6c24dd63365cb4b2e20", "size": 8624, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/analysis/serology_analysis.r", "max_stars_repo_name": "sbfnk/immunity.thresholds", "max_stars_repo_head_hexsha": "c8f59f28262c884b20ddf3077356cf5c53e09c72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inst/analysis/serology_analysis.r", "max_issues_repo_name": "sbfnk/immunity.thresholds", "max_issues_repo_head_hexsha": "c8f59f28262c884b20ddf3077356cf5c53e09c72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inst/analysis/serology_analysis.r", "max_forks_repo_name": "sbfnk/immunity.thresholds", "max_forks_repo_head_hexsha": "c8f59f28262c884b20ddf3077356cf5c53e09c72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2990654206, "max_line_length": 316, "alphanum_fraction": 0.6301020408, "num_tokens": 2351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4936761949249286}} {"text": "#' Optimal Leader/Mentor Matching\n#'\n#' Implementes the algorithm described in Valente and Davis (1999)\n#'\n#' @template graph_template\n#' @param n Number of leaders\n#' @param cmode Passed to \\code{\\link{dgr}}.\n#' @param lead.ties.method Passed to \\code{\\link{rank}}\n#' @param geodist.args Passed to \\code{\\link{approx_geodesic}}.\n#'\n#' @details The algorithm works as follows:\n#' \\enumerate{\n#' \\item Find the top \\code{n} individuals ranking them by \\code{dgr(graph, cmode)}.\n#' The rank is computed by the function \\code{\\link{rank}}. Denote this set \\code{M}.\n#' \\item Compute the geodesic matrix.\n#' \\item For each \\code{v in V} do:\n#'\n#' \\enumerate{\n#' \\item Find the mentor \\code{m in M} such that is closest to \\code{v}\n#' \\item Were there a tie, choose the mentor that minimizes the average\n#' path length from \\code{v}'s direct neighbors to \\code{m}.\n#' \\item If there are no paths to any member of \\code{M}, or all have the\n#' same average path length to \\code{v}'s neighbors, then assign one\n#' randomly.\n#' }\n#' }\n#'\n#' @return An object of class \\code{diffnet_mentor} and \\code{data.frame} with the following columns:\n#' \\item{name}{Character. Labels of the vertices}\n#' \\item{degree}{Numeric. Degree of each vertex in the graph}\n#' \\item{iselader}{Logical. \\code{TRUE} when the vertex was picked as a leader.}\n#' \\item{match}{Character. The corresponding matched leader.}\n#'\n#' The object also contains the following attributes:\n#'\n#' \\item{nleaders}{Integer scalar. The resulting number of leaders (could be greater than \\code{n})}.\n#' \\item{graph}{The original graph used to run the algorithm.}\n#'\n#' @references\n#' Valente, T. W., & Davis, R. L. (1999). Accelerating the Diffusion of\n#' Innovations Using Opinion Leaders. The ANNALS of the American Academy of\n#' Political and Social Science, 566(1), 55–67.\n#' \\doi{10.1177/000271629956600105}\n#' @examples\n#' # A simple example ----------------------------------------------------------\n#' set.seed(1231)\n#' graph <- rgraph_ws(n=50, k = 4, p = .5)\n#'\n#' # Looking for 3 mentors\n#' ans <- mentor_matching(graph, n = 3)\n#'\n#' head(ans)\n#' table(ans$match) # We actually got 9 b/c of ties\n#'\n#' # Visualizing the mentor network\n#' plot(ans)\n#'\n#' @export\nmentor_matching <- function(\n graph,\n n,\n cmode = \"indegree\",\n lead.ties.method = \"average\",\n geodist.args = list()\n) {\n\n cls <- class(graph)\n\n if (any(c(\"dgCMatrix\", \"matrix\", \"array\") %in% cls)) {\n # Adding labels in case there aren't any\n if (!length(rownames(graph))) {\n warning(\"-graph- as no labels (rownames). We'll add some from 1 to n.\")\n dimnames(graph) <- list(1:nnodes(graph), 1:nnodes(graph))\n }\n }\n\n if (any(c(\"dgCMatrix\", \"matrix\") %in% cls)) {\n\n # Matrix method\n .mentor_matching(graph, n, cmode, lead.ties.method, geodist.args)\n\n } else if (\"list\" %in% cls) {\n\n # List method\n lapply(graph, .mentor_matching, n = n,\n cmode = cmode, lead.ties.method = lead.ties.method,\n geodist.args = geodist.args)\n\n } else if (\"array\" %in% cls) {\n\n # Array method\n apply(graph, 3, .mentor_matching, n = n,\n cmode = cmode, lead.ties.method = lead.ties.method,\n geodist.args = geodist.args)\n\n } else if (\"diffnet\" %in% cls) {\n\n # diffnet method\n g <- graph$graph\n g <- lapply(g, `dimnames<-`, value = list(nodes(graph), nodes(graph)))\n lapply(g, .mentor_matching, n = n,\n cmode = cmode, lead.ties.method = lead.ties.method,\n geodist.args = geodist.args)\n\n } else stopifnot_graph(graph)\n\n}\n\n\n.mentor_matching <- function(\n graph,\n n,\n cmode = \"indegree\",\n lead.ties.method = \"average\",\n geodist.args = list()\n) {\n\n # Step 1. Find the pcent with highest\n d <- dgr(graph, cmode = cmode)\n r <- -rank(d, ties.method = lead.ties.method)\n r <- as.integer(as.factor(r))\n top <- which(r <= n)\n\n # Step 2: Match each individual with their closest one\n G <- do.call(\n approx_geodist,\n c(list(graph = as.matrix(graph)), geodist.args)\n )\n\n ans <- sapply(1:nnodes(graph), function(i) {\n x <- which(G[i,top] == min(G[i,top]))\n\n # If there are any ties, then solve them by taking a look at i's\n # neighbors\n if (length(x) > 1) {\n\n # Picking neighbors\n j <- which(graph[i,-top] != 0)\n\n # If all of them are top\n if (!length(j))\n return(sample(top, size = 1))\n\n # Average pathlength per top\n j <- sapply(top, function(h) {\n mean(G[j,h])\n })\n\n # Choose the min\n top[which.min(j)]\n\n } else top[x]\n })\n\n # Mentors should be assigned to them selfs\n ans[top] <- top\n\n # Returning\n structure(\n data.frame(\n name = nodes(graph),\n degree = d,\n isleader = 1:nnodes(graph) %in% top,\n match = nodes(graph)[ans],\n stringsAsFactors = FALSE\n ),\n class = c(\"diffnet_mentor\", \"data.frame\"),\n nleaders = length(top),\n graph = graph\n )\n\n}\n\n#' @export\n#' @rdname mentor_matching\nleader_matching <- mentor_matching\n\n#' @export\n#' @param x An object of class \\code{diffnet_mentor}.\n#' @template plotting_template\n#' @param lead.cols Character vector of length \\code{attr(x,\"nleaders\")}. Colors\n#' to be applied to each group. (see details)\n#' @param vshapes Character scalar of length 2. Shapes to identify leaders (mentors)\n#' and followers respectively.\n#' @param add.legend Logical scalar. When \\code{TRUE} generates a legend to distinguish\n#' between leaders and followers.\n#' @param y Ignored.\n#' @param ... Further arguments passed to \\code{\\link[igraph:plot.igraph]{plot.igraph}}\n#' @param main Character scalar. Passed to \\code{\\link[graphics:title]{title}}\n#' @rdname mentor_matching\nplot.diffnet_mentor <- function(\n x,\n y = NULL,\n vertex.size = \"degree\",\n minmax.relative.size = getOption(\"diffnet.minmax.relative.size\", c(0.01, 0.04)),\n lead.cols = grDevices::topo.colors(attr(x, \"nleaders\")),\n vshapes = c(Leader=\"square\", Follower=\"circle\"),\n add.legend = TRUE,\n main = \"Mentoring Network\",\n ...) {\n\n\n igraph.args <- list(...)\n oldpar <- graphics::par(no.readonly = TRUE)\n on.exit(graphics::par(oldpar))\n graphics::par(xpd = NA)\n\n set_igraph_plotting_defaults(\"igraph.args\")\n\n # Creating igraph obj\n ig <- cbind(\n as.character(x[[\"name\"]]),\n as.character(x[[\"match\"]])\n )\n\n ig <- edgelist_to_adjmat(ig)\n ig <- ig[x[[\"name\"]],][,x[[\"name\"]]]\n ig <- igraph::graph_from_adjacency_matrix(ig, weighted = NULL)\n\n # Creating plot\n graphics::plot.new()\n graphics::plot.window(xlim = c(-1,1), ylim = c(-1,1))\n\n igraph::V(ig)$shape <- vshapes[2-x[[\"isleader\"]]]\n\n igraph.args$vertex.size <- rescale_vertex_igraph(\n compute_vertex_size(ig, vertex.size),\n minmax.relative.size = minmax.relative.size\n )\n\n igraph.args$vertex.color <- lead.cols[as.integer(factor(x[[\"match\"]]))]\n\n do.call(igraph::plot.igraph, c(list(x = ig), igraph.args))\n\n if (add.legend) {\n\n # Checking names\n if (!length(names(vshapes)))\n names(vshapes) <- c(\"Leader\", \"Follower\")\n\n A<-B<-1\n ig <- igraph::make_graph(~A,B)\n igraph::V(ig)$name <- names(vshapes)\n igraph::V(ig)$color <- \"gray\"\n igraph::V(ig)$label.color <- \"black\"\n igraph::V(ig)$shape <- vshapes\n igraph::V(ig)$size <- 2\n plot(ig, layout = rbind(c(-.4, -1.3), c(.15, -1.3)), add=TRUE,\n vertex.size = 5, rescale=FALSE, vertex.label.dist = 1, vertex.label.degree=0)\n\n }\n\n title(main=main)\n\n # Returning\n invisible(x)\n\n}\n\n\n\n\n", "meta": {"hexsha": "fa35ef9b765650d198d013b00708a53505be1037", "size": 7509, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mentor.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/mentor.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/mentor.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 28.5513307985, "max_line_length": 101, "alphanum_fraction": 0.6235184445, "num_tokens": 2194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4935930430204954}} {"text": "# lhl.R\n\n# Church two step breakpoint algorithm, from Church et al, 1994.\n\nlhl_old <- function(r_times){\n \n # initial values\n # s1 <- 0 # start\n s2 <- 0 # stop\n t1 <- 0 # first low rate duration\n t2 <- 0 # high rate duration\n t3 <- 0 # second low rate duration\n r1 <- 0 # first low rate\n r2 <- 0 # high rate\n r3 <- 0 # second low rate\n index_s1 <- 0 # index to get start (inner for loop)\n index_s2 <- 0 # index to get stop (outer for loop)\n algorithm_s1 <- 0 # as above, indexed by index_s1\n algorithm_s2 <- 0\n end_trial <- 180\n nr <- length(r_times) # number of responses\n r <- nr/180 # get overall response rate\n \n # 'if' conditional states that trials must have more than 3 responses\n if (nr > 3) { \n \n # loop through response times, except the last\n # then choose best t1 (inner for loop), \n # then get best s2 estimate (outer for loop)\n \n for (i in 1:(nr - 1)) { \n \n s2[i] <- r_times[i + 1] \n t3[i] <- end_trial - s2[i]\n \n if (t3[i] <= 0) {\n r3[i] <- 0 # necessary to avoid division by 0\n t3[i] <- 0\n } else {\n r3[i] <- sum(r_times > s2[i])/t3[i]\n }\n \n for (j in seq_along(s2)) { # loop through putative s2 and choose t1\n \n t1[j] <- r_times[j] # This seems wrong! j = 1, 2, 3..., not the values of s2\n r1[j] <- sum(r_times <= t1[j])/t1[j]\n t2[j] <- s2[i] - t1[j] # high-rate duration\n \n if (t2[j] == 0) { \n r2[j] <- 0 # necessary to avoid division by 0\n } else {\n r2[j] <- sum(r_times > t1[j] & r_times <= s2[i])/t2[j]\n }\n \n algorithm_s1[j] <- t1[j]*(r - r1[j]) + t2[j]*(r2[j] - r) + t3[i]*(r - r3[i])\n index_s1 <- which(algorithm_s1 == max(algorithm_s1,na.rm = T))\n # some times two indexes with same algorithm value\n # get the first of them\n if(length(index_s1) > 1){\n index_s1 <- min(index_s1)\n }\n \n } # end inner loop (get s1 value)\n \n algorithm_s2[i] <- t1[index_s1]*(r - r1[index_s1]) + t2[i]*(r2[i] - r) + t3[i]*(r - r3[i])\n \n } # end outer for loop (get s2 value after s1)\n \n index_s2 <- which(algorithm_s2 == max(algorithm_s2, na.rm = T))\n \n if (length(index_s2) > 1) { \n index_s2 <- min(index_s2)\n }\n \n start <- t1[index_s1]\n stop <- s2[index_s2]\n mid <- (start + stop)/2\n low_rate_1 <- sum(r_times <= start)/start\n low_rate_2 <- sum(r_times > stop)/(end_trial - stop)\n spread <- stop - start\n \n high_rate <- sum(r_times > start & r_times <= stop)/spread\n \n bpts <- \n data.frame(start = start,\n stop = stop,\n mid = mid,\n spread = spread,\n high_rate = high_rate,\n r1 = low_rate_1,\n r3 = low_rate_2)\n \n bpts\n } # end if \n \n}\n", "meta": {"hexsha": "bf75c7fbda440dd79e8fdcf9d0451e83c6c60cfa", "size": 2867, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/r/versions/lhl_old.r", "max_stars_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_stars_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/r/versions/lhl_old.r", "max_issues_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_issues_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/r/versions/lhl_old.r", "max_forks_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_forks_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5567010309, "max_line_length": 96, "alphanum_fraction": 0.5207534008, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4933427715844208}} {"text": "# Gamlss estimation of gene noise for each gene for COVID19\n\nlibrary(edgeR)\nlibrary(gamlss)\nlibrary(gtools)\n\n\nsetwd(\"/media/yuri/Data/home1/GNI_data/infection/ResultsSciRep\")\nload(\"COVID19_RNAseq.Rdat\")\n\n\n################################################################################\n# Functions for GAMLSS analysis\n# gNBI.RS - the Rigby and Stasinopoulos algorithm for GAMLSS\ngNBI.RS = function(dat, f1, f2){\n res = tryCatch(\n gamlss::gamlss(f1, sigma.fo = f2, data = dat, family = NBI(), method = RS(), n.cyc = 500),\n warning = function(w) NULL, error = function(e) NULL)\n res\n}\n\n# gNBI.CG - the Cole and Green algorithm for GAMLSS\ngNBI.CG = function(dat, f1, f2){\n res = tryCatch(\n gamlss::gamlss(f1, sigma.fo = f2, data = dat, family = NBI(), method = CG(), n.cyc = 500),\n warning = function(w) NULL, error = function(e) NULL)\n res\n}\n\n# Gamlss estimation of gene noise for each gene for COVID19\ngene_noise_COVID <- mclapply(seq(nrow(DGE_RNAcounts$counts)), function(i) {\n\n cat(i, \"\\r\")\n\n # COVID - data.frame\n # y - RNA counts\n # x - fixed effect factor (COVID19 mild/severe)\n # ofs - offset log(library size x normalization factor), see edgeR\n # Sex - gender\n # age - age\n # rnd - Sex:age interaction was used as random effect\n\n COVID = data.frame(y = DGE_RNAcounts$counts[i,],\n x = factor(DGE_RNAcounts$samples$stage),\n ofs = DGE_RNAcounts$samples$offset,\n Sex = DGE_RNAcounts$samples$Sex,\n age = DGE_RNAcounts$samples$age\n )\n COVID$age[is.na(COVID$age)] = median(COVID$age[!is.na(COVID$age)])\n COVID$age = quantcut(COVID$age, q=10)\n COVID$rnd = paste0(COVID$Sex, \":\", COVID$age)\n\n # f1 - gamlss formula for mu\n f1 = formula(y ~ x + random(factor(rnd)) + offset(ofs) )\n # f2 - gamlss formula for sigma\n f2 = formula(y ~ x + random(factor(rnd)))\n\n # gamlss model\n # m0 - model for mu and sigma with x fixed factor effects: COVID stage and random factor effects rnd: Sex:age\n sink(\"/dev/null\")\n\n m0 = gNBI.RS(COVID, f1, f2)\n\n if(is.null(m0)) { m0 = gNBI.CG(COVID, f1, f2) }\n\n sink()\n\n # results:\n # mu_mild - mean gene expression for mild COVID19\n # mu_severe - mean gene expression for severe COVID19\n # bcv_mild - biological coefficient of variation of gene expression for mild COVID19\n # bcv_severe - biological coefficient of variation of gene expression for severe COVID19\n # p_mu - significance of COVID19 effect (mild vs severe) on mean gene expression\n # p_bcv - significance of COVID19 effect (mild vs severe) on gene expression noise (bcv - biological coefficient of variation)\n\n res = data.frame(mu_mild = NA, mu_severe = NA, bcv_mild = NA, bcv_severe = NA, p_mu = NA, p_bcv=NA)\n\n if(!is.null(m0)) {\n sink(\"/dev/null\")\n m0s = summary(m0, \"qr\", save = T)\n mu = exp(cumsum(m0s$mu.coef.table[,1]))*1e06\n bcv = sqrt(exp(cumsum(m0s$sigma.coef.table[,1])))\n p_mu = m0s$mu.coef.table[2,4]\n p_bcv = m0s$sigma.coef.table[2,4]\n res = data.frame(mu_mild = mu[[1]], mu_severe = mu[[2]],\n bcv_mild = bcv[[1]], bcv_severe = bcv[[2]],\n p_mu = p_mu, p_bcv=p_bcv)\n sink()\n }\n\n res\n\n}, mc.cores = 4 )\n\ngene_noise_COVID <- do.call(rbind, gene_noise_COVID)\nrm(f1, f2, gNBI.CG, gNBI.RS)\n\nsetwd(\"/media/yuri/Data/home1/GNI_data/infection/ResultsSciRep\")\nsave.image(\"COVID19_gene_noise_Figure6A.Rdat\")\n", "meta": {"hexsha": "60ea97e3d8b653152c117af7acba571e65ec805a", "size": 3406, "ext": "r", "lang": "R", "max_stars_repo_path": "ScriptsSciRep/Gene_noise_analysis_Fig1_Fig6A/Figure6A_COVID19_gene_noise_analysis.r", "max_stars_repo_name": "Vityay/GeneEnsembleNoise", "max_stars_repo_head_hexsha": "6a85feb9bd3fea7ae465905383d7c0396a59af76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ScriptsSciRep/Gene_noise_analysis_Fig1_Fig6A/Figure6A_COVID19_gene_noise_analysis.r", "max_issues_repo_name": "Vityay/GeneEnsembleNoise", "max_issues_repo_head_hexsha": "6a85feb9bd3fea7ae465905383d7c0396a59af76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScriptsSciRep/Gene_noise_analysis_Fig1_Fig6A/Figure6A_COVID19_gene_noise_analysis.r", "max_forks_repo_name": "Vityay/GeneEnsembleNoise", "max_forks_repo_head_hexsha": "6a85feb9bd3fea7ae465905383d7c0396a59af76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.06, "max_line_length": 130, "alphanum_fraction": 0.6379917792, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49326529689524357}} {"text": "valoreAtteso <- 2.81\r\n\r\nn <- 5\r\n\r\ndomanda1 <- 4\r\n\r\ndomanda2 <- 4\r\n\r\nrisposta1 <- 1 - (ppois(domanda1, valoreAtteso) ^ n);\r\n\r\nrisposta2 <- 1- ppois(domanda2*n, valoreAtteso*n);\r\n\r\nprint(risposta1)\r\n\r\nprint(risposta2)", "meta": {"hexsha": "9196b1ce8dd1406ec475e5c95b78b5e22e7fccd8", "size": 215, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 55.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 55.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 55.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3333333333, "max_line_length": 54, "alphanum_fraction": 0.6325581395, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49326529689524345}} {"text": "# ver 2.0 -- marc, 11, 2020\r\n# naiv, egyerszeru modell a magyar COVID-19 fertozott betegek szamanak rovidtavu alakulasara\r\n\r\n# a modell azért naiv, mert NEM veszi figyelembe \r\n# kezdo gocpontok es azok tavolsaganak hatasak\r\n# a mar valamennyire tisztazott parametereket: onset delay, incubation period (5-8nap), reprodukcios szam (2,5), overdispersion stb.\r\n# orszagok egymasra hatasat, infrastrukturalis valtozokat es a beavatkozasok hatasat\r\n# SIR modell korlatait. stb.\r\n# valamint determinisztikus.\r\n\r\n#memoria uritese \r\nrm(list = ls()) \r\n\r\n\r\n# parameterek\r\nmin_fert <- 19 #honnantol veszi figyelembe az adatsort\r\nmin_hossz <- 4 #milyen hosszo adatsort tekint elemezhetonek min\r\nshossz <- 21 # hany napra vetitse elore az eredmenyeket a modell\r\n\r\n\r\n#BETOLTES\r\n#adatok betoltese Johns Hopkins egyetem folyamatos frissitesu online adataibol\r\nrawcovid <- read.csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\", header=TRUE, as.is=T, sep=\",\", fileEncoding = \"UTF-8\") \r\n\r\n#OECD orszagok alapadatai\r\noecdraw <- read.csv(\"https://raw.githubusercontent.com/bricoler/naiv_COVID19_HU/R_code/OECD_2019.csv\", header=TRUE, as.is=T, sep=\",\", fileEncoding = \"UTF-8\") \r\n\r\n\r\n#AGGREGALAS\r\n#aggregalas orszagokra \r\n#E: itt eldobjuk a GEO-t, de a jovoben lehetne kezdeni valamit a tavolsagi adatokkal, ketdimenzioban (ido, ter)\r\nl2 <- dim(rawcovid)[2] # napok hossza\r\n\r\nrcovid <- aggregate(rawcovid[5:l2], by = list(rawcovid$Country.Region), FUN = sum) # orszagok szerinti aggregalas rcovid\r\nrownames(rcovid) <- rcovid[,1] #sornevek javitasa rcovidban\r\ncolnames(rcovid)[1] <- \"cname\"\r\n\r\nrownames(oecdraw) <- oecdraw[,1] #sornevek oecdrawban is\r\n\r\n\r\n# OECD orszagok vizsgalata csak\r\n\r\nrrcovid <- rcovid[(rcovid$cname %in% oecdraw$cname),] ##rrcovid: csak OECD orszagok\r\nrrcovid <- rrcovid[,-1] # elso oszlop a cname torlese rrcovidban\r\n\r\n\r\n#dif matrix eloallitasa (delta elozo nap)\r\nd_covid <- rrcovid[1:dim(rrcovid)[1],2:dim(rrcovid)[2]] - rrcovid[1:dim(rrcovid)[1],(1:(dim(rrcovid)[2]-1))]\r\n\r\n#az OECD lakossagszam leosztas\r\n#covid : lakossagszamaranyos fertozottek aranya OECD orszagokban\r\n\r\ncovid <- rrcovid\r\n\r\nfor (i in 1:dim(rrcovid)[1]) \r\n{\r\ncovid[i,] <- rrcovid[i,] / oecdraw[rownames(rrcovid)[i],\"pop\"]\r\n} \r\n\r\n#SZAMITAS\r\n# kulonbozo orszagok metaadatok szamitas, exp es log fuggvenyillesztes\r\n# hianyzik: orszaglakossag es lakossagaranyos emelkedesszamitas\r\n\r\ncovid[covid==0]<-NA #0-kbol NA \r\n\r\ncname <- NULL\r\nchossz <-NULL\r\ncmin <- NULL\r\ncmax <- NULL\r\ncmean <- NULL\r\ncmedian <-NULL\r\ncsd <- NULL\r\n\r\ntempv <-NULL\r\ntempv2 <- NULL\r\n\r\nc_expC <- NULL\r\nc_expbeta <- NULL\r\nc_expR2 <- NULL\r\n\r\nc_logC <- NULL\r\nc_logbeta <- NULL\r\nc_logR2 <- NULL\r\n\r\nc_tend <- NULL\r\n\r\nfor (i in 1:dim(covid)[1]) \r\n{\r\ncname[i] <- rownames(covid)[i] # orszag neve\r\ncmin[i] <- min(as.numeric(covid[i,]), na.rm=T) * oecdraw[rownames(rrcovid)[i],\"pop\"] # minimum fertozottszam emberben\r\ncmax[i] <- max(as.numeric(covid[i,]), na.rm=T) * oecdraw[rownames(rrcovid)[i],\"pop\"] # maximum fertozottszam\r\ncmean[i] <- mean(as.numeric(covid[i,]), na.rm=T) * oecdraw[rownames(rrcovid)[i],\"pop\"] # atlagos fertozottszam\r\ncmedian[i] <- median(as.numeric(covid[i,]), na.rm=T) * oecdraw[rownames(rrcovid)[i],\"pop\"] #median fertozottszam\r\ncsd[i] <- sd(as.numeric(covid[i,]), na.rm=T) * oecdraw[rownames(rrcovid)[i],\"pop\"] #sd fertozottszam emberben\r\n\r\ntempv <- NULL \r\ntempv2 <- NULL\r\n\r\ntempv <- na.omit(as.numeric(covid[i,])) # atmeneti vektor a nullak kidobalasa\r\n\r\ntempv2 <- tempv[which( tempv * oecdraw[rownames(rrcovid)[i],\"pop\"] > min_fert) ] # 17-nel kisebbek kidobalasa - (tempv * vissza kell szorozni lakossagszamra)\r\nchossz[i] <- length(tempv2) # hany nap van tobb mint min_fert fertozott\r\n\r\n#ha minhossznak kevesebb a megfigyeles akkor nem szamolunk\r\n#utana exp illesztes\r\n#utana log illesztes\r\n\r\nif (length(tempv2)>min_hossz) {\r\n#exp\r\nc_expC[i] <- coef(summary(lm(log(tempv2)~c(1:(length(tempv2))))))[1,1]\r\nc_expbeta[i] <- coef(summary(lm(log(tempv2)~c(1:(length(tempv2))))))[2,1]\r\nc_expR2[i] <- summary(lm(log(tempv2)~c(1:(length(tempv2)))))$adj.r.squared \r\n#log\r\nc_logC[i] <- coef(summary(lm((tempv2)~log(c(1:(length(tempv2)))))))[1,1]\r\nc_logbeta[i] <- coef(summary(lm((tempv2)~log(c(1:(length(tempv2)))))))[2,1]\r\nc_logR2[i] <- summary(lm((tempv2)~log(c(1:(length(tempv2))))))$adj.r.squared \r\n\r\n\r\nif (c_logR2[i] eps && n < maxit && abs(fc) > eps && abs(ac) >= 1.e-35)\n {\n n<-n+1\n xnew<-xc-fc/ac\n xold<-xc\n fold<-fc\n xc<-xnew\n fc<-pchisq(X2Observed, Df, xnew)-CumP\n ac<-(fold-fc)/(xold-xc)\n if(ErrorCondition)\n {\n return(NA)\n }\n \n }\n ##iteration complete\n if( (n >= maxit)||(abs(fc) > eps))\t \n {\n ErrorCondition <- TRUE\n print(\"Percentage point convergence failure.\")\n return(NA)\n }\n else\n {\n return(xc)\t\n }\n}\nChiSquare.Lambda.CI <- function(X2Observed,Df,Confidence=.90){\n p <- (1. - Confidence)/2.\n if( pchisq(X2Observed, Df) <= p)\n{\n Upper <- 0.\n Lower <- 0.\n return(c(Lower,Upper))\n }\n Upper <- FindLambda(X2Observed,Df,p)\n if(pchisq(X2Observed, Df) <= 1.-p)\n {\n Lower <- 0\n return(c(Lower,Upper))\n }\n Lower <- FindLambda(X2Observed,Df,1-p)\n return(c(Lower,Upper))\n}\n\nrmsea.ci <- function(chisq,df,n,conf=.90){\n options(warn=-1)\n sample.rmsea <- sqrt(max(((chisq-df)/(n-1)),0)/df)\n# out <- conf.limits.nc.chisq(Chi.Square=chisq,conf.level=conf,df=df,Jumping.Prop=0.001)\n out<-ChiSquare.Lambda.CI(chisq,df,conf)\n lower <- if(is.na(out[1])) 0 else out[1]\n upper <- if(is.na(out[2])) 0 else out[2]\n lower <- sqrt(lower/(n-1)/df)\n upper <- sqrt(upper/(n-1)/df)\n results <- list(Lower.Limit= lower, \n Point.Estimate = sample.rmsea,\n Upper.Limit = upper,\n Confidence.Level = conf)\n return((results))\n}\n\ncompute_CFI <- function(chi_null,df_null,chi_model,df_model){\n d_null <- chi_null - df_null\n d_model <- chi_model - df_model\n (cfi <- (d_null - d_model) / d_null)\n return(cfi)\n}\n\ncompute_TLI <- function(chi_null,df_null,chi_model,df_model){\n (r_null <- chi_null/df_null)\n (r_model <- chi_model/df_model)\n (tli <- (r_null - r_model)/((r_null)-1))\n return(tli)\n}\n\nfa_stats <- function(Correlation.Matrix,n.obs,n.factors,conf=.90,\n maxit=1000,RMSEA.cutoff=NULL,\n main=\"RMSEA Plot\",sub=NULL){\n # browser()\n runs <- length(n.factors) \n R <- Correlation.Matrix\n maxfac <- max(n.factors)\n res <- matrix(NA,runs,10)\n roots <- eigen(R)$values\n for(i in 1:runs){\n # i <- 3\n # R <- R0\n # n.obs = 643\n # n.factors=3:5\n # maxit = 1000\n output <- factanal(covmat=R,n.obs=n.obs,factors=n.factors[i],maxit=maxit)\n fit <- psych::fa(R,nfactors=n.factors[i],n.obs=n.obs,fm=\"ml\")\n X2 <- output$STATISTIC\n df <- output$dof\n ci <- rmsea.ci(X2,df,n.obs,conf)\n pvar <- sum(roots[1:n.factors[i]])\n # cfi <- compute_CFI(fit$null.chisq,fit$null.dof,fit$chi, fit$dof)\n # tli <- compute_TLI(fit$null.chisq,fit$null.dof,fit$chi, fit$dof)\n cfi <- compute_CFI(fit$null.chisq,fit$null.dof,X2, df)\n tli <- compute_TLI(fit$null.chisq,fit$null.dof,X2, df)\n v <- c(n.factors[i],pvar,X2,df,1-pchisq(X2,df),ci$Point.Estimate,\n ci$Lower.Limit,ci$Upper.Limit, cfi,tli)\n \n res[i,] <- v\n }\n colnames(res)=c(\"Factors\",\"Cum.Eigen\",\"Chi-Square\",\"Df\",\"p.value\",\n \"RMSEA.Pt\",\"RMSEA.Lo\",\"RMSEA.Hi\",\"CFI\",\"TLI\")\n plotCI(n.factors,res[,6],li = res[,7],ui=res[,8],\n ylab=\"RMSEA\",xlab=\"Number of Factors\",main=main,\n sub=sub)\n lines(n.factors,res[,6],col=\"blue\")\n abline(h=0,col=\"black\",lty=3)\n abline(h=RMSEA.cutoff,col=\"red\",lty=2)\n \n return(res)\n}\n\nFA.Stats <- function(\n Correlation.Matrix,\n n.obs,\n n.factors,\n conf=.90,\n maxit=1000,\n RMSEA.cutoff=NULL,\n main=\"RMSEA Plot\",\n sub=NULL\n){\n # browser()\n runs <- length(n.factors) \n R <- Correlation.Matrix\n maxfac <- max(n.factors)\n res <- matrix(NA,runs,8)\n roots <- eigen(R)$values\n for(i in 1:runs){\n output <- stats::factanal(\n covmat=R,\n n.obs=n.obs,\n factors=n.factors[i],\n maxit=maxit\n )\n X2 <- output$STATISTIC\n df <- output$dof\n ci <- rmsea.ci(X2,df,n.obs,conf)\n pvar <- sum(roots[1:n.factors[i]])\n v <- c(\n n.factors[i],\n pvar,\n X2,\n df,\n 1-pchisq(X2,df),\n ci$Point.Estimate,\n ci$Lower.Limit,\n ci$Upper.Limit\n )\n res[i,] <- v\n }\n colnames(res)=c(\"Factors\",\"Cum.Eigen\",\"Chi-Square\",\"Df\",\"p.value\",\n \"RMSEA.Pt\",\"RMSEA.Lo\",\"RMSEA.Hi\")\n plotCI(n.factors,res[,6],li = res[,7],ui=res[,8],\n ylab=\"RMSEA\",xlab=\"Number of Factors\",main=main,\n sub=sub)\n lines(n.factors,res[,6],col=\"blue\")\n abline(h=0,col=\"black\",lty=3)\n abline(h=RMSEA.cutoff,col=\"red\",lty=2)\n return(res)\n}\n\nScree.Plot <- function(R,main=\"Scree Plot\",sub=NULL){\n roots <- eigen(R)$values\n x <- 1:dim(R)[1]\n plot(x,roots,type=\"b\",col='blue',ylab=\"Eigenvalue\",\n xlab=\"Component Number\",main=main,sub=sub) \n abline(h=1,lty=2,col=\"red\")\n \n}\n# Scree.PlotGG <- function(R, main=\"Scree Plot\",sub=NULL){\n# roots <- eigen(R)$values\n# x <- 1:dim(R)[1]\n# # plot(x,roots,type=\"b\",col='blue',ylab=\"Eigenvalue\",\n# # xlab=\"Component Number\",main=main,sub=sub) \n# # abline(h=1,lty=2,col=\"red\")\n# \n# ds <- data.frame(x=x, roots=roots)\n# g <- ggplot(ds, aes(x=x, y=roots)) +\n# geom_rect(ymax=1, ymin=-Inf, xmin=-Inf, xmax=Inf, fill=\"red\") +\n# geom_line(size=1.5, color=\"blue\", na.rm = TRUE) +\n# geom_point(size=5, color=\"darkblue\", na.rm = TRUE) +\n# labs(title=main, x=\"Component Number\", y=\"Eigenvalue\") +\n# theme_bw()\n# \n# print(g)\n# }\n\nFindBifactor <- function(A,reps){\n warn=-1\n results <- rep( list(list()), reps ) \n criterion <- rep(NA,reps)\n m <- dim(A)[2]\n for(i in 1:reps) {\n x <- GPForth(A,method=\"bifactor\",Tmat = Random.Start(m))\n criterion[i] <- min(x$Table[,2])\n results[[i]] <- x\n }\n j <- order(criterion)[1]\n warn=1\n return(results[[j]])\n}\n\nFindBestPattern <- function(A,method,is.oblique=FALSE,reps=15){\n results <- rep( list(list()), reps ) \n criterion <- rep(NA,reps)\n m <- dim(A)[2]\n for(i in 1:reps) {\n if(!is.oblique)x <- GPForth(A,method=method,Tmat = Random.Start(m))else\n x <- GPFoblq(A,method=method,Tmat=Random.Start(m))\n criterion[i] <- min(x$Table[,2])\n results[[i]] <- x\n }\n j <- order(criterion)[1]\n return(results[[j]])\n}\n\nFixPattern <- function(res,sort=TRUE){\n F <- res$Lh\n p <- dim(F)[1]\n m <- dim(F)[2]\n factor.names <- paste(\"Factor\",1:m,sep=\"\")\n one.prime <- matrix(1,1,p)\n F.sign <- as.vector(sign(one.prime %*% F))\n # cat(\"\\nLoadings:\\n\")\n# fx <- format(round(Lambda, digits))\n# names(fx) <- NULL\n# nc <- nchar(fx[1L], type=\"c\")\n# fx[abs(Lambda) < cutoff] <- paste(rep(\" \", nc), collapse = \"\")\n# print(fx, quote = FALSE, ...) \n# F <- Lambda\n#fix signs\n Lambda <- F\n Lambda <- Lambda %*% diag(F.sign)\n#sort columns by SS loadings\n mx <- diag(t(Lambda)%*%Lambda)\n ind <- order(mx,decreasing=TRUE)\n Lambda <- Lambda[,ind]\n# browser()\n# print(res$orthogonal)\n# print(res$Phi)\n if(!res$orthogonal)\n {\n# fix up Phi\n Phi <- diag(F.sign) %*% res$Phi %*% diag(F.sign)\n Phi <- Phi[ind,]\n Phi <- Phi[,ind]\n }\n if (sort) {\n mx <- max.col(abs(Lambda))\n ind <- cbind(1L:p, mx)\n mx[abs(Lambda[ind]) < 0.4] <- m + 1\n Lambda <- Lambda[order(mx, 1L:p),]\n }\n colnames(Lambda) <- factor.names\n res$Lh <- Lambda\n if(!res$orthogonal)\n {\n colnames(Phi) <- factor.names\n rownames(Phi) <- factor.names\n res$Phi <- Phi\n }\n return(res)\n}\n\n# FindBifactorPattern is not used anywhere else in this code\nFindBifactorPattern <- function(A,reps,digits=2) {\n options(warn=-1)\n p<-dim(A)[1]\n out <- FindBifactor(A,reps)\n F <- out$Lh\n one.prime <- matrix(1,1,p)\n F.sign <- as.vector(sign(one.prime %*% F))\n F <- F %*% diag(F.sign)\n options(warn=1)\n return(round(F,digits))\n} \n\nGPromax <- function(A,pow=3){\n method <- \"Promax\"\n # Initial rotation: Standardized Varimax\n xx <- promax(A,pow)\n Lh <- xx$loadings\n Th <- xx$rotmat\n orthogonal <- F\n Table <- NULL\n Tinv <- solve(Th)\n Phi <- Tinv %*% t(Tinv)\n return(list(Lh=Lh,Phi=Phi,Th=Th,Table=NULL,method,orthogonal=orthogonal))\n}\n\nprint.FLS <- function(x, sort=TRUE, num.digits=3, cutoff=.25, ...)\n{\n Lambda <- unclass(x$F)\n \n p <- nrow(Lambda)\n factors <- ncol(Lambda)\n if (sort) {\n mx <- max.col(abs(Lambda))\n ind <- cbind(1L:p, mx)\n mx[abs(Lambda[ind]) < 0.5] <- factors + 1\n Lambda <- Lambda[order(mx, 1L:p),]\n }\n fx <- format(round(Lambda, num.digits))\n names(fx) <- NULL\n nc <- nchar(fx[1L], type=\"c\")\n fx[abs(Lambda) < cutoff] <- paste(rep(\" \", nc), collapse = \"\")\n print(fx, quote = FALSE, ...)\n vx <- colSums(Lambda^2)\n varex <- rbind(\"SS loadings\" = vx)\n if(is.null(attr(x, \"covariance\"))) {\n varex <- rbind(varex, \"Proportion Var\" = vx/p)\n if(factors > 1)\n varex <- rbind(varex, \"Cumulative Var\" = cumsum(vx/p))\n }\n cat(\"\\n\")\n print(round(varex, num.digits))\n \nif(!is.null(x$Phi)){\n cat(\"\\nFactor Intercorrelations\\n\")\n cat(\"------------------------\\n\")\n print(round(unclass(x$Phi),num.digits)) \n }\n invisible(x)\n}\n\nprint.MLFA<-function(x,num.digits=3,cutoff=0.25,sort_=TRUE,...)\n{\ncat(\"\\n## Unrotated\\n------------------\\n\")\nprint.FLS(x$Unrotated,num.digits=num.digits,cutoff=cutoff,sort=sort_)\ncat(\"\\n## Varimax (T)\\n------------------\\n\")\nprint.FLS(x$Varimax,num.digits=num.digits,cutoff=cutoff,sort=sort_)\ncat(\"\\n## Promax (Q)\\n-----------------\\n\")\nprint.FLS(x$Promax,num.digits=num.digits,cutoff=cutoff,sort=sort_)\ncat(\"\\n## Quartimin (Q)\\n-----------------\\n\")\nprint.FLS(x$Quartimin,num.digits=num.digits,cutoff=cutoff,sort=sort_)\ncat(\"\\n## Bifactor (T)Loadings\\n---------------------------\\n\")\nprint.FLS(x$Bifactor,num.digits=num.digits,cutoff=cutoff,sort=sort_)\ncat(\"\\n## Bifactor (Q)\\n-------------------------\\n\")\n# print.FLS(x$BifactorOblique,num.digits=num.digits,cutoff=cutoff,sort=sort_)\n# # the last element must be invisible for proper output in R\ninvisible(print.FLS(x$BifactorOblique,num.digits=num.digits,cutoff=cutoff,sort=sort_))\n\n\n# # Crawford-Ferguson added by Koval\n# cat(\"\\nCF Loadings\\n-------------------------\\n\")\n# print.FLS(x$CF,num.digits=num.digits,cutoff=cutoff,sort=sort_)\n# cat(\"\\nCFQ Loadings\\n-------------------------\\n\")\n# # the last element must be invisible for proper output in R\n# invisible(print.FLS(x$CFQ,num.digits=num.digits,cutoff=cutoff,sort=sort_))\n\n}\n\nMLFA <- function(Correlation.Matrix=NULL,\n n.factors=NA,\n n.obs=NA,\n data=NULL,\n Factor.Pattern=NULL,\n random.starts=15,\n maxit=1000,\n num.digits=3,\n cutoff=0.30,\n promax.m=3,\n sort = TRUE)\n{\ncat(\"This will take a moment.\")\nif(!is.null(Correlation.Matrix)&&is.null(data)){\n R <- Correlation.Matrix\n p <- dim(R)[1]\n A <- factanal(covmat=R,n.obs=n.obs,factors=n.factors,maxit=maxit,rotation=\"none\")$loadings[1:p,]\n }\nif(!is.null(data)){\n R <- cor(data)\n n.obs <- dim(data)[1]\n p <- dim(R)[1]\n A <- factanal(covmat=R,n.obs=n.obs,factors=n.factors,maxit=maxit,rotation=\"none\")$loadings[1:p,]\n}\nif(is.null(data)&&is.null(Correlation.Matrix)){ \n A <- Factor.Pattern\n p <- dim(A)[1]\n}\n\nm <- dim(A)[2]\nfactor.labels <- paste(\"Factor\",1:m,sep=\"\")\n# browser()\n# Variamx\nA.varimax <- varimax(A)$loadings[1:p,]\nres <- list(Lh=A.varimax,orthogonal=TRUE)\nres <- FixPattern(res, sort = sort)\nA.varimax <- list(F=res$Lh)\n# Promax\nres <- GPromax(A,pow=promax.m)\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\nres <- FixPattern(res, sort = sort)\nPhi.promax <- res$Phi\nA.promax <- list(F=res$Lh,Phi=Phi.promax,orthogonal=FALSE)\ncat(\".\")\n# Quartimin\nres <- FindBestPattern(A,\"quartimin\",reps=random.starts,is.oblique=TRUE)\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\nres <- FixPattern(res, sort = sort)\nPhi.quartimin <- res$Phi\nA.quartimin <- list(F=res$Lh,Phi = Phi.quartimin)\ncat(\".\")\n# Bifactor\nres <- FindBestPattern(A,\"bifactor\",reps=random.starts)\northogonal=TRUE\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=orthogonal)\nres <- FixPattern(res, sort = sort)\nPhi=NULL\nA.bifactor <- list(F=res$Lh,Phi=Phi)\ncat(\".\")\n# Bifactor Oblique\nres <- FindBestPattern(A,\"bifactor\",reps=random.starts,is.oblique=TRUE)\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\nres <- FixPattern(res, sort = sort)\ncat(\".\")\nPhi.bifactor.oblique <- res$Phi\nA.bifactor.oblique <- list(F=res$Lh,Phi=Phi.bifactor.oblique)\ncat(\".\")\n\n\n\n#### ADDitional rotations \n\n# Geomin (orthogonal)\nres <- FindBestPattern(A,\"geomin\",reps=random.starts)\northogonal=TRUE\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=orthogonal)\nres <- FixPattern(res, sort = sort)\nPhi=NULL\nA.geominT <- list(F=res$Lh,Phi=Phi)\ncat(\".\")\n# Geomin (Oblique)\nres <- FindBestPattern(A,\"geomin\",reps=random.starts,is.oblique=TRUE)\nres <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\nres <- FixPattern(res, sort = sort)\ncat(\".\")\nPhi.bifactor.oblique <- res$Phi\nA.geominQ <- list(F=res$Lh,Phi=Phi.bifactor.oblique)\ncat(\".\")\n\n# # Oblimin\n# res <- FindBestPattern(A,\"oblimin\",reps=random.starts,is.oblique=TRUE)\n# res <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\n# res <- FixPattern(res, sort = sort)\n# Phi.oblimin <- res$Phi\n# A.oblimin <- list(F=res$Lh,Phi = Phi.oblimin)\n# cat(\".\")\n\n# # CF added by Koval\n# # Crawford-Ferguson\n# res <- FindBestPattern(A,\"cf\",reps=random.starts,is.oblique=FALSE)\n# res <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=TRUE)\n# res <- FixPattern(res, sort = sort)\n# Phi=NULL\n# A.cf <- list(F=res$Lh,Phi=Phi)\n# cat(\".\")\n# # Crawford-Ferguson Oblique\n# res <- FindBestPattern(A,\"cf\",reps=random.starts,is.oblique=TRUE)\n# res <- list(Lh=res$Lh,Phi=res$Phi,orthogonal=FALSE)\n# res <- FixPattern(res, sort = sort)\n# cat(\".\")\n# Phi.cfq <- res$Phi\n# A.cfq <- list(F=res$Lh,Phi=Phi.cfq)\n# cat(\".\")\n# browser()\n# reconstruct the unrotated solution\nA <- list(F=A,Phi=NULL) # line moved from end of the BifactorOblique section\n# cat(\".\")\n#\nclass(A)=\"FLS\"\nclass(A.varimax)=\"FLS\"\nclass(A.promax)=\"FLS\"\nclass(A.quartimin)=\"FLS\"\ncat(\".exiting\\n\") # what is this for?\nclass(A.bifactor)=\"FLS\"\nclass(A.bifactor.oblique)=\"FLS\"\nclass(A.geominT) =\"FLS\"\nclass(A.geominQ) =\"FLS\"\n\n# additional rotations\n# class(A.cf)=\"FLS\"\n# class(A.cfq)=\"FLS\"\n# class(A.oblimin) = \"FLS\"\n\noutput<-list(\n Unrotated = A, \n Varimax = A.varimax,\n GeominT = A.geominT,\n Bifactor = A.bifactor,\n Promax = A.promax,\n Quartimin = A.quartimin,\n GeominQ = A.geominQ,\n BifactorOblique = A.bifactor.oblique \n # Oblimin = A.oblimin\n # CF=A.cf,\n # CFQ=A.cfq\n )\nclass(output) = \"MLFA\"\nreturn(output)\n}\n# end of MLFA function definition\n\nLoadings <- function(x,num.digits=3,cutoff=.25){\n invisible(print.MLFA(x,cutoff=cutoff,num.digits=num.digits))\n}\n\nFAtoCFA <- function(\n x,\n model.name = \"fit\",\n cutoff = 0.30,\n factor.names = colnames(x$F),\n reference.indicators = FALSE,\n covs = paste(factor.names, collapse=\",\")\n){\n # browser()\n F <- x$F\n fname <- paste(model.name,\".r\",sep=\"\")\n file.create(fname)\n rn <- rownames(F)\n p <- dim(F)[1]\n m <- dim(F)[2]\n line <- rep(\" \",m)\n for (j in 1:m) {\n prefix <- paste(factor.names[j],\":\",sep=\"\")\n count <- sum(abs(F[,j]>cutoff))\n postfix <- rep(\" \",count)\n i.postfix <- 0\n for(i in 1:p){\n if(abs(F[i,j])> cutoff){\n i.postfix <- i.postfix + 1\n if(i.postfix \",sep=\"\")\n for(i in 1:p){\n postfix <- rn[i]\n non.fixed=TRUE\n line.out=FALSE\n for(jj in 1:m)\n {\n if(i == ref.position[jj]&&jj==j)\n {\n non.fixed=TRUE\n line.out=TRUE}\n if(i == ref.position[jj]&&jj!=j)\n non.fixed=FALSE\n } \n if(non.fixed){\n \n par.number <- par.number + 1\n par.name <- paste(\"Theta\",as.character(par.number),sep=\"\")\n if(make.start.values)\n sv<-paste(c(\", \",as.character(round(F[i,j],num.digits)),\"\\n\"),collapse=\"\")else sv <- \", NA\\n\"\n postfix <- paste(c(postfix,\", \",par.name,sv),collapse=\"\")\n line.out=TRUE\n }\n \n \n if(line.out){\n line <- paste(c(prefix,postfix),collapse=\"\") \n cat(line,file=fname,append=TRUE)\n }\n }\n }\n for(j in 1:m)\n {\n cat(paste(c(factor.names[j],\" <-> \",factor.names[j],\", NA, 1\\n\"),collapse=\"\"),file=fname,append=TRUE)\n }\n if(cov.matrix && m>1 ) \n {\n ok <- !is.null(Phi)\n for(i in 2:m)\n for(j in 1:(i-1))\n { \n par.number <- par.number + 1\n prefix <- paste(factor.names[i], \"<-> \",sep=\"\")\n postfix <- factor.names[j]\n if(make.start.values&&ok)\n sv<-paste(c(\", \",as.character(round(Phi[i,j],num.digits)),\"\\n\"),collapse=\"\") else sv <- \", NA\\n\"\n par.name <- paste(\"Theta\",as.character(par.number),sep=\"\")\n postfix <- paste(c(postfix,\", \",par.name,sv),collapse=\"\")\n cat(paste(c(prefix,postfix),collapse=\"\"),file=fname,append=TRUE) \n }\n } \n## add unique variances\n if(is.null(Phi))Phi <- diag(p)\n U2 <- diag(R - F %*% Phi %*% t(F))\n for(i in 1:p){\n par.number <- par.number+1\n prefix <- paste(c(rn[i],\" <-> \",rn[i],\", \"),collapse=\"\")\n par.name <- paste(\"Theta\",as.character(par.number),sep=\"\")\n if(make.start.values)\n sv<-paste(c(\", \",as.character(round(U2[i],num.digits)),\"\\n\"),collapse=\"\") else sv <- \", NA\\n\"\n cat(paste(c(prefix,par.name,sv),collapse=\"\"),file=fname,append=TRUE) \n }\n \n cat(\"\\n\",file=fname,append=TRUE)\n cstring <- paste( c(\"specifyModel(file=\\\"\",fname,\"\\\")\"),collapse=\"\")\n sem.model <- eval(parse(text=cstring))\n return(sem.model)\n}\n\nFAtoSEM <- function(\n x,\n model.name = \"fit\",\n cutoff = 0.30,\n factor.names = colnames(x$F),\n make.start.values = FALSE,\n cov.matrix = FALSE,\n num.digits = 4,\n par.prefix = c(\"Theta\",\"Theta\"),\n reference.variables = FALSE\n){\n F <- round(x$F,num.digits)\n fname <- paste(model.name,\".r\",sep=\"\")\n file.create(fname)\n cat(\"\\n\")\n Phi <- x$Phi\n rn <- rownames(F)\n p <- dim(F)[1]\n m <- dim(F)[2]\n # cat(paste(model.name,\"<- cfa(reference.indicators=FALSE)\\n\"))\n line <- rep(\" \",p-(m-1))\n par.number <- 0\n for (j in 1:m) {\n prefix <- paste(factor.names[j],\" -> \",sep=\"\")\n var.count <- 0\n for(i in 1:p){\n postfix <- rn[i]\n if(abs(F[i,j])>cutoff)\n { var.count <- var.count + 1\n if(var.count>1 || !reference.variables){\n par.number <- par.number + 1\n par.name <- paste(par.prefix[1],as.character(par.number),sep=\"\")\n if(make.start.values)\n {sv<-paste(c(\", \",as.character(F[i,j]),\"\\n\"),collapse=\"\")}else sv <- \", NA\\n\"\n postfix <- paste(c(postfix,\", \",par.name,sv),collapse=\"\")\n }else{\n postfix <- paste(postfix,\",NA,1\\n\",sep=\"\")\n }\n line <- paste(c(prefix,postfix),collapse=\"\") \n cat(line,file=fname,append=TRUE)\n } \n }\n }\n for(j in 1:m)\n {\n if(!reference.variables){\n cat(paste(c(factor.names[j],\" <-> \",factor.names[j],\", NA, 1\\n\"),collapse=\"\"),\n file=fname,append=TRUE)}\n}\nif(cov.matrix && m>1 ) \n {\n ok <- !is.null(Phi)\n for(i in 2:m)\n for(j in 1:(i-1))\n { \n par.number <- par.number + 1\n prefix <- paste(factor.names[i], \"<-> \",sep=\"\")\n postfix <- factor.names[j]\n if(make.start.values&&ok)sv<-paste(c(\", \",as.character(Phi[i,j]),\"\\n\"),collapse=\"\") else sv <- \", NA\\n\"\n par.name <- paste(par.prefix[2],as.character(par.number),sep=\"\")\n postfix <- paste(c(postfix,\", \",par.name,sv),collapse=\"\")\n cat(paste(c(prefix,postfix),collapse=\"\"),file=fname,append=TRUE) \n }\n } \n cat(\"\\n\",file=fname,append=TRUE)\n cstring <- paste( c(\"specifyModel(file=\\\"\",fname,\"\\\")\"),collapse=\"\")\n sem.model <- eval(parse(text=cstring))\n return(sem.model)\n}\n\nGetPattern <- function(sem.object){\n A <- sem.object$A\n P <- sem.object$P\n p <- sem.object$n\n m <- sem.object$m - p\n F <- A[1:p,(p+1):sem.object$m]\n Phi <- P[(p+1):sem.object$m,(p+1):sem.object$m]\n return(list(F=F,Phi=Phi))\n}\n\nSetupCFAPattern <- function(\n R,\n n.factors = NA,\n factor.names = NULL\n){\n p <- dim(R)[1]\n m <- n.factors\n Fp <- matrix(0,p,m)\n rownames(Fp) <- colnames(R)\n if(is.null(factor.names))factor.names <- paste(\"Factor\",1:m,sep=\"\")\n colnames(Fp) <- factor.names\n Fp <- edit(Fp)\n return(list(F=Fp))\n} # return Factor pattern that was manually set up in the editor\n\nUseMod <- function(sem.object,loadings.only=TRUE){\n options(warn=-1)\nnew.path <- CheckMod(sem.object,row.form=TRUE,loadings.only=loadings.only)$NewPath\nold.model <- sem.object$semmod\nR <- sem.object$S\nn.obs <- sem.object$N\nnew.model <- rbind(old.model,new.path)\nclass(new.model) <- class(old.model)\nfit.object <- sem(new.model,R,n.obs)\nreturn(fit.object)\n}\n\nCFAModel <- function(\n R,\n model.name = \"fit\",\n n.factors = NULL,\n factor.names = NULL,\n cutoff = 0.30,\n covs = TRUE,\n reference.indicators = FALSE\n){\n if(is.null(n.factors))n.factors=length(factor.names)\n x <- SetupCFAPattern(R,n.factors,factor.names)\n factor.names <- colnames(x$F)\n if(covs){\n covariances=paste(factor.names, collapse=\",\")\n }else{covariances=NULL}\n # browser()\nmodel <- FAtoCFA(\n x = x,\n model.name = model.name,\n cutoff = cutoff,\n factor.names = factor.names,\n reference.indicators = reference.indicators,\n covs = covariances\n)\nreturn(model)\n}\n\nQuickCFA <- function(\n R,\n n.factors = NULL,\n n.obs,\n model.name = \"Model0\",\n factor.names = NULL,\n cutoff =0.30,\n factor.correlations = FALSE,\n reference.indicators = FALSE)\n{\n if(is.null(factor.names))factor.names <- paste(\"Factor\",1:n.factors,sep=\"\")\n model <- CFAModel(\n R,\n model.name,\n n.factors,\n factor.names,\n cutoff,\n covs=factor.correlations,\n reference.indicators\n )\n fit.object <- sem(model,R,n.obs)\n return(fit.object)\n}\n\nCheckMod <- function(sem.object,row.form=FALSE,loadings.only=TRUE){\n options(warn=-1)\n mi <- modIndices(sem.object)\n A <- mi$mod.A\n P <- mi$mod.P\n p <- sem.object$n\n m <- sem.object$m - p\n F <- A[1:p,(p+1):sem.object$m]\n par.number <- sem.object$t + 1\n par.name <- paste(\"AddedTheta\",par.number,sep=\"\")\n largest.F <- max(F,na.rm=TRUE)\n largest.P <- 0\n largest.Q <- 0\n if(!loadings.only){\n Q <- P\n P <- P[(p+1):sem.object$m,(p+1):sem.object$m]\n Q <- Q[1:p,1:p]\n largest.P <- max(P,na.rm=TRUE)\n largest.Q <- max(Q,na.rm=TRUE)\n }\n maxes <- c(largest.F,largest.P,largest.Q)\n for(i in 1:3)if(maxes[i]==-Inf)maxes[i]<-0\n max.mod.pos <- order(maxes,decreasing=TRUE)[1]\n if(max.mod.pos == 1){\n arrow <- \"->\"\n F.pos <- which(F==largest.F,arr.ind=TRUE)\n if(length(F.pos[,1])>1)F.pos <- F.pos[1,]\n postfix <- rownames(F)[F.pos[1]]\n prefix <- colnames(F)[F.pos[2]]\n value <- F[F.pos[1],F.pos[2]]\n }\n if(max.mod.pos==2){\n arrow=\"<->\"\n P.pos <- which(P==largest.P,arr.ind=TRUE)\n if(length(P.pos[,1])>1)P.pos <- P.pos[1,]\n prefix <- colnames(P)[P.pos[1]]\n postfix <- colnames(P)[P.pos[2]]\n value <- P[P.pos[1],P.pos[2]]\n }\n if(max.mod.pos==3){\n arrow=\"<->\"\n Q.pos <- which(Q==largest.Q,arr.ind=TRUE)\n if(length(Q.pos[,1])>1)Q.pos <- Q.pos[1,]\n prefix <- colnames(Q)[Q.pos[1]]\n postfix <- colnames(Q)[Q.pos[2]]\n value <- Q[Q.pos[1],Q.pos[2]]\n }\n path <- paste(c(prefix,arrow,postfix),collapse=\"\")\n if(!row.form)line <- paste(c(path,\",\",par.name,\", NA\"),collapse=\"\")else line <- c(path,par.name,\", NA\")\n fname=\"added.r\"\n file.create(fname)\n cat(line,file=fname)\n output <- list(NewPath=line,ModIndex=value)\n return(output) \n}\nCullModel<-function(fit.object,alpha,cull.Phi=FALSE){\n model <- fit.object$semmod\n zcrit <- qnorm(1-alpha/2)\n zval <- summary(fit.object)$coeff$'z value'\n sig <- abs(zval)>zcrit\n par.posn <- fit.object$par.posn\n new.model <- model\n model.length <- dim(model)[1]\n pos<-1\n to.cull <- 0\n is.ok <- rep(TRUE,model.length)\n if(!cull.Phi){\n do.not.cull <- grep(\"<->\",model)\n for(i in 1:length(do.not.cull)){\n is.ok[do.not.cull[i]]<-FALSE\n }\n }\n for(i in 1:length(sig)){\n if(!sig[i]&&is.ok[par.posn[i]]){\n to.cull[pos] <- par.posn[i]\n pos <- pos+1\n }\n }\nnew.model <- new.model[-to.cull,]\nclass(new.model) <- class(model)\nreturn(new.model)\n} \n\nQuickJoreskog <- function(R,n.factors,n.obs,model.name=\"model.0\",\n alpha=0.05,use.promax=TRUE,promax.m=3){\n mlfa.object <- MLFA(R,n.factors,n.obs,promax.m=promax.m)\n if(use.promax)x <- mlfa.object$Promax else x <- mlfa.object$Varimax\n ref.model <- FAtoREF(x,R,model.name)\n ref.fit <- sem(ref.model,R,n.obs)\n culled.model <- CullModel(ref.fit,alpha)\n culled.fit <- sem(culled.model,R,n.obs)\n return(culled.fit)\n}\n\nGetPrettyPattern <- function(fit.object,cutoff=0.10){\n print.FLS(GetPattern(fit.object),cutoff=cutoff)}\n\nRMSEA <- function(fit.object,conf=0.90){\n n.obs <- fit.object$N\n X2 <- (n.obs-1)*fit.object$criterion\n p <- fit.object$n\n t <- fit.object$t\n df <- p*(p+1)/2 - t\n rmsea.ci(X2,df,n.obs,conf)\n}\nQuickEFAtoCFA <- function(\n R,\n n.factors,\n n.obs,\n rotation=\"Varimax\",\n model.name=\"model.0\",\n cutoff=0.30,\n alpha=0.05,\n make.start.values=TRUE,\n cov.matrix=TRUE,\n num.digits=4,\n promax.m=3\n){\n rotation.list <- c(\"Varimax\",\"Promax\",\"Quartimin\",\"Bifactor\", \"BifactorOblique\")\n rot <- 0\n for(i in 1:5)\n if(rotation==rotation.list[i]){rot<-i;break} \n if(rot==0){print(\"Illegal Rotation Method\");return()}\n x <- MLFA(R,n.factors,n.obs,cutoff=cutoff,num.digits=num.digits,promax.m=promax.m) \n cstring <- paste( c(\"rot.pattern <-x$\",rotation),collapse=\"\")\n eval(parse(text=cstring))\n model <- FAtoSEM(rot.pattern,model.name=model.name,cutoff=cutoff,\n factor.names=colnames(rot.pattern$F),\n make.start.values=make.start.values,cov.matrix=cov.matrix,num.digits=num.digits)\n fit <- sem(model,R,n.obs)\n return(fit)\n}\nQuickSEM <- function(S = NULL,n.obs=NULL,max.latents = dim(S)[1]){\nx <- data.frame(Latent.Variable.Names = rep(\"\",max.latents))\nx <- edit(x)\np <- dim(S)[1]\nLV <- x$Latent.Variable.Names\nLV <- as.character(LV[LV!=\"\"])\nn.LV <- length(LV)\nF <- matrix(0,n.LV,n.LV)\nLx <-NULL\nLn <-NULL\nrownames(F) <- LV\ncolnames(F) <- LV\nF <- edit(F)\ncs <- colSums(F)\nfor(i in 1:n.LV)if(cs[i]==0)F <- F[1:n.LV,-i]\nrs <- rowSums(F)\nnc <- dim(F)[2]\nfor(i in 1:n.LV)if(rs[i]==0){\n Lx <- c(Lx,rownames(F)[i])\n F <- F[-i,1:nc]\n}\nLn <- rownames(F)\nn.Ln <- length(Ln)\nn.Lx <- length(Lx)\nLambda.x <- matrix(0,p,n.Lx)\nrownames(Lambda.x) <- colnames(S)\ncolnames(Lambda.x) <- Lx\nLambda.x <- edit(Lambda.x)\ncly <- colnames(S)\nrs <- rowSums(Lambda.x)\nrn <-NULL\nfor(i in 1:p)if(rs[i]==0)rn <- c(rn,cly[i])\nrows.Lambda.y <- length(rn)\nLambda.y <- matrix(0,rows.Lambda.y,n.Ln)\nrownames(Lambda.y) <- rn\ncolnames(Lambda.y) <- Ln\nLambda.y <- edit(Lambda.y)\nq <- dim(Lambda.x)[2]\nrs <- rowSums(Lambda.x)\nLL<-NULL\nRR<-NULL\nRN<-rownames(Lambda.x)\nfor(i in 1:p)if(rs[i]>0){\n LL <- rbind(LL,Lambda.x[i,])\n RR <- c(RR,RN[i])\n}\nLambda.x <- LL\ncolnames(Lambda.x)<- Lx\nrownames(Lambda.x)<- RR\nxxx <- list(F=Lambda.x)\nyyy <- list(F=Lambda.y)\nmm1 <- FAtoSEM(xxx,\"xxx\",par.prefix=c(\"Lamdax\",\"Phi\"))\nmm2 <- FAtoSEM(yyy,\"yyy\",reference.variables=TRUE,par.prefix=c(\"Lambday\",\"Delta\"))\nstruc.model <- FtoSEM(F,Lx,Ln,\"sss\")\nmy.model <- rbind(mm1,mm2,struc.model)\nclass(my.model) <- class(mm1)\nsem(my.model,S,n.obs)\n}\n\nFtoSEM <- function(F,Lx,Ln,model.name){\n fname <- paste(model.name,\".r\",sep=\"\")\n file.create(fname)\n cat(\"\\n\")\n#Get Betas \n #Are there any?\n if(dim(F)[2]>length(Lx)){\n par.prefix <- \"Beta\"\n lnlist <- colnames(F)\n for(k in 1:length(Lx)){\n for(j in 1:length(lnlist))\n if(Lx[k]==lnlist[j])lnlist[k]<-\" \"}\n lns <- lnlist[lnlist!=\" \"]\n bbb=0\n## List of prefix names for Betas is in lns\n for(j in 1:length(lns)){\n for(i in 1:length(Ln)){\n# browser()\n if(F[Ln[i],lns[j]]>0){bbb<-bbb+1\n prefix <- paste(c(lns[j],\"->\",Ln[i]),collapse=\"\")\n par.name <- paste(c(\",\",par.prefix,as.character(bbb)),collapse=\"\")\n postfix <- \",NA\\n\"\n }\n }\n line <- paste(c(prefix,par.name,postfix),collapse=\"\") \n cat(line,file=fname,append=TRUE)\n }\n }\n#Get Gammas \n gamma<-0\n par.prefix <- \"Gamma\"\n for(i in 1:length(Lx)){\n for(j in 1:length(Ln))\n {\n if(F[Ln[j],Lx[i]]>0){gamma<-gamma+1\n prefix <- paste(Lx[i],\"->\",sep=\"\")\n prefix <- paste(prefix,Ln[j],sep=\"\")\n par.name <- paste(c(\",\",par.prefix,as.character(gamma)),sep=\"\")\n postfix <- \",NA\\n\"\n \n line <- paste(c(prefix,par.name,postfix),collapse=\"\") \n cat(line,file=fname,append=TRUE)\n }}}\n cat(\"\\n\",file=fname,append=TRUE)\n cstring <- paste( c(\"specifyModel(file=\\\"\",fname,\"\\\")\"),collapse=\"\")\n sem.model <- eval(parse(text=cstring))\n return(sem.model)\n\n \n}\n\nEditSEM<- function(sem.object){\n old.model <- sem.object$semmod\n new.model <- edit(old.model)\n return(sem(new.model,sem.object$S,sem.object$N))\n}", "meta": {"hexsha": "653c9c0f77aff7e11fdbba2286e13205b6e6f3cc", "size": 42563, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/AdvancedFactorFunctions_CF.r", "max_stars_repo_name": "dss-hmi/pdtsun-2020-survey", "max_stars_repo_head_hexsha": "d218889ae6f81848bd1a1588eb08eea44600288c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/AdvancedFactorFunctions_CF.r", "max_issues_repo_name": "dss-hmi/pdtsun-2020-survey", "max_issues_repo_head_hexsha": "d218889ae6f81848bd1a1588eb08eea44600288c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/AdvancedFactorFunctions_CF.r", "max_forks_repo_name": "dss-hmi/pdtsun-2020-survey", "max_forks_repo_head_hexsha": "d218889ae6f81848bd1a1588eb08eea44600288c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6742522757, "max_line_length": 125, "alphanum_fraction": 0.5819138689, "num_tokens": 14550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143953, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4925489860360645}} {"text": "[[[[[\n Show that a real r is Solovay random\n iff it is strong Chaitin random.\n\n An effective covering A_k of k is a function\n of k that enumerates bit strings s,\n which are the initial bits of the covered\n reals. We assume that no s in A_k is a\n proper prefix or extension of another.\n Thus the measure of the cover A_k of k is\n exactly Sum_{s in A_k} of 2^{-|s|},\n where |s| is the length of the bit string s.\n]]]]]\n\n[Second part: not Ch random ===> not Sol random] \n\ndefine (is-in? x l) [is x an element of list l?]\n if atom l false\n if = x car l true\n (is-in? x cdr l)\n\ndefine is-in?\nvalue (lambda (x l) (if (atom l) false (if (= x (car l))\n true (is-in? x (cdr l)))))\n\ndefine (union x y) [set-theoretic union of two sets x y]\n if atom x y\n if (is-in? car x y) (union cdr x y)\n cons car x (union cdr x y)\n\ndefine union\nvalue (lambda (x y) (if (atom x) y (if (is-in? (car x) y\n ) (union (cdr x) y) (cons (car x) (union (cdr x) y\n )))))\n\ndefine (is-bit-string? x) [is x a list of 0's and 1's?]\n if = x nil true\n if atom x false\n if = 0 car x (is-bit-string? cdr x)\n if = 1 car x (is-bit-string? cdr x)\n false\n\ndefine is-bit-string?\nvalue (lambda (x) (if (= x nil) true (if (atom x) false \n (if (= 0 (car x)) (is-bit-string? (cdr x)) (if (= \n 1 (car x)) (is-bit-string? (cdr x)) false)))))\n\ndefine C [test computer---real thing is eval read-exp]\n let (loop x y) [xx yy zz 01 ===> xyz]\n if = x y cons x (loop read-bit read-bit)\n nil\n (loop read-bit read-bit)\n\ndefine C\nvalue ((' (lambda (loop) (loop (read-bit) (read-bit)))) \n (' (lambda (x y) (if (= x y) (cons x (loop (read-b\n it) (read-bit))) nil))))\n\n[\n The hypothesis that\n the real number r is not Chaitin random\n means that there is a K such that\n for infinitely many values of n\n H(r_n) < n + K, \n where r_n is the first n bits of r.\n\n For this example, let's suppose that K = 5.\n]\n\ndefine K 5\n\ndefine K\nvalue 5\n\n[\n Our proof depends on the fact that there is a c such that\n the probability that an n-bit string s has\n H(s) < n + K \n is less than 2^{-H(n) + K + c}.\n]\n\n[\n Now let's do stage N of A_n = n-bit strings s with H(s) < |s| + K. \n At stage N we look at all programs p less than n + K bits in size for time up to N.\n]\n\ndefine (quasi-compressible N n)\n (look-at nil)\n\ndefine quasi-compressible\nvalue (lambda (N n) (look-at nil))\n\n[this routine has free parameters N, n, K, C]\n\ndefine (look-at p) [produces quasi-compressible strings of length n]\n if = length p + n K [p too long?]\n nil\n let v try N C ['eval read-exp] p\n if = success car v\n let w cadr v \n if (is-bit-string? w)\n if = n length w\n cons w nil\n nil\n nil\n [\n Also works with append below instead of union\n because duplicates are removed later by (process interval).\n ]\n (union (look-at append p cons 0 nil)\n (look-at append p cons 1 nil))\n\ndefine look-at\nvalue (lambda (p) (if (= (length p) (+ n K)) nil ((' (la\n mbda (v) (if (= success (car v)) ((' (lambda (w) (\n if (is-bit-string? w) (if (= n (length w)) (cons w\n nil) nil) nil))) (car (cdr v))) (union (look-at (\n append p (cons 0 nil))) (look-at (append p (cons 1\n nil))))))) (try N C p))))\n\n[\n List of intervals in covering so far.\n used to avoid overlapping intervals in covering.\n\n This is easy to do because here because\n all intervals are the same length.\n]\ndefine intervals ()\n\ndefine intervals\nvalue ()\n\ndefine (process-all x) [process list of intervals x]\n if atom x intervals\n let intervals append (process car x) intervals\n (process-all cdr x)\n\ndefine process-all\nvalue (lambda (x) (if (atom x) intervals ((' (lambda (in\n tervals) (process-all (cdr x)))) (append (process \n (car x)) intervals))))\n\ndefine (process interval) [process individual interval]\n if (is-in? interval intervals) \n [then don't need to repeat it]\n nil\n [else interval is fine as is]\n cons display interval nil \n\ndefine process\nvalue (lambda (interval) (if (is-in? interval intervals)\n nil (cons (display interval) nil)))\n\n[\n Put it all together---Here is cover A_n\n covering all reals r having n-bit prefix r_n \n with H(r_n) < n + K.\n\n And we have measure \\mu A_n <= 2^{-H(n)+K+c}\n so that Sum_n \\mu A_n <= \\Omega 2^{K+c} <= 2^{K+c} < infinity .\n\n Hence a real r which is not strongly Chaitin random\n will be in infinitely many of the A_n, \n which have convergent total measure,\n and hence will not be Solovay random.\n]\ndefine (A n)\n let intervals nil\n let (stage N)\n if = N 7 stop! [to stop test run---remove if real thing]\n let quasi-compressible-strings (quasi-compressible N n)\n let intervals (process-all quasi-compressible-strings) \n (stage + 1 N)\n [go!!!!!]\n (stage 0)\n\ndefine A\nvalue (lambda (n) ((' (lambda (intervals) ((' (lambda (s\n tage) (stage 0))) (' (lambda (N) (if (= N 7) stop!\n ((' (lambda (quasi-compressible-strings) ((' (lam\n bda (intervals) (stage (+ 1 N)))) (process-all qua\n si-compressible-strings)))) (quasi-compressible N \n n)))))))) nil))\n\n[n = 2, i.e., quasi-compressible 2-bit strings]\n(A 2)\n\nexpression (A 2)\ndisplay (0 0)\ndisplay (0 1)\ndisplay (1 0)\ndisplay (1 1)\nvalue stop!\n", "meta": {"hexsha": "739eda6ece9c763b14c2964505748379d2a35e82", "size": 5544, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/chaitin2.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/chaitin2.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/chaitin2.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 28.5773195876, "max_line_length": 84, "alphanum_fraction": 0.5865800866, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.492489053318675}} {"text": "#' IREQ\n#'\n#' Calculation of Required Clothing Insulation IREQ.\n#'\n#' @param t numeric Air temperature in degC.\n#' @param rh numeric Relative humidity in percentage.\n#' @param wind numeric Windspeed in meter per second.\n#' @param tr numeric Mean radiant temperature in degC.\n#' @param M numeric Metabolic work in Watt per mq of the subject.\n#' @param W numeric Mechanical work rate in Watt per mq of the subject.\n#' @param clo numeric Available basic clothing insulation in clo.\n#' @param p numeric Air permeability of clothing ensemble lt on meters per second.\n#' @param w numeric Walking speed in meters per second.\n#' @param param character Parameter of IREQ ISO 11079: \"IREQ_neutral\",\"IREQ_min\",\"ICL_neutral\",\"ICL_min\",\"DLE_neutral\",\"DLE_min\",\"ICL_ISO11079\"\n#' @return IREQ value\n#' @references ISO 11079, 2007-12-15, ERGONOMICS OF THE THERMAL ENVIRONMENT - DETERMINATION AND INTERPRETATION OF COLD STRESS WHEN USING REQUIRED CLOTHING INSULATION (IREQ) AND LOCAL COOLING EFFECTS.\n#' @author Istituto per la Bioeconomia CNR Firenze Italy Alfonso Crisci \\email{alfonso.crisci@@ibe.cnr.it}\n#' @keywords IREQ \n#' @export \n#'\n#'\n#'\n#'\n\nIREQ=function(t,rh,wind,tr,M,W,clo,p,w,param=\"IREQ_neutral\") {\n if ( length(param)==1) {param=rep(param,length(t))}\n ct$assign(\"t\", as.array(t))\n ct$assign(\"rh\", as.array(rh))\n ct$assign(\"v\", as.array(wind))\n ct$assign(\"Tr\", as.array(tr))\n ct$assign(\"M\", as.array(M))\n ct$assign(\"W\", as.array(W))\n ct$assign(\"Icl\", as.array(clo))\n ct$assign(\"p\", as.array(p))\n ct$assign(\"w\", as.array(w))\n ct$assign(\"param\", as.array(param))\n ct$eval(\"var res=[]; for(var i=0, len=t.length; i < len; i++){ res[i]=IREQ(t[i],rh[i],v[i],Tr[i],M[i],W[i],Icl[i],p[i],w[i],param[i])};\")\n res=ct$get(\"res\")\n return(ifelse(res==9999,NA,res))\n}\n\n", "meta": {"hexsha": "eb4c7794eee73e48015dcddbf5b7493a803d4835", "size": 2114, "ext": "r", "lang": "R", "max_stars_repo_path": "R/IREQ.r", "max_stars_repo_name": "alfcrisci/rBiometeo", "max_stars_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-23T13:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:36.000Z", "max_issues_repo_path": "R/IREQ.r", "max_issues_repo_name": "alfcrisci/rBiometeo", "max_issues_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/IREQ.r", "max_forks_repo_name": "alfcrisci/rBiometeo", "max_forks_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-19T15:28:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T19:35:47.000Z", "avg_line_length": 50.3333333333, "max_line_length": 199, "alphanum_fraction": 0.5818353832, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49234485220733104}} {"text": "\n################################################################################\n#\n# Simplified script for example analysis for \"A Simple Way to\n# Incorporate Uncertainty and Risk into Forest Harvest Scheduling\".\n#\n# Andrew Robinson 22 September 2015\n#\n################################################################################\n\n## Set run parameters\n\nset.seed(1)\n\nn.coupes <- 1000\n\nnsim <- 10000\n\n################################################################################\n\n## Call libraries\n\nlibrary(ggplot2)\nlibrary(gridExtra)\nlibrary(splines)\nlibrary(gamlss)\nlibrary(lpSolveAPI)\nlibrary(parallel)\n\n################################################################################\n\n## Generate fake albeit realistic data\n\ncoupes <-\n data.frame(HARVYEAR = sample(\n 2003:2013,\n size = n.coupes,\n replace = TRUE),\n ForestQualityClass = sample(\n c(\"MAT_hq\",\"MAT_lq\",\"MIX_hq\",\"MIX_lq\"),\n size = n.coupes,\n replace = TRUE),\n grossArea = rweibull(n = n.coupes,\n shape = 1.74,\n scale = 70))\n\nparameters <-\n data.frame(ForestQualityClass = c(\"MAT_hq\",\"MAT_lq\",\"MIX_hq\",\"MIX_lq\"),\n x.shapes = c(1.70, 1.45, 1.7, 0.90),\n x.scales = c(6800, 2400, 6000, 2600),\n recovery = c(0.5, 0.3, 0.5, 0.3),\n y.scales = c(1, 1.5, 2, 1.2))\n\ncoupes <- merge(coupes, parameters, all.x = TRUE)\n\ncoupes$grossHQSLest <- rweibull(n = nrow(coupes),\n shape = coupes$x.shapes,\n scale = coupes$x.scales)\n\ncoupes$SalesHQSL.s <-\n with(coupes, 200 * y.scales)\ncoupes$SalesHQSL.a <-\n with(coupes, grossHQSLest * recovery / SalesHQSL.s)\n\ncoupes$SalesHQSL <- rgamma(n = nrow(coupes),\n shape = coupes$SalesHQSL.a,\n scale = coupes$SalesHQSL.s)\n\npdf(file = \"Figure 1 ex.pdf\", height = 4, width = 4)\nqplot(x = grossHQSLest / 1000,\n y = SalesHQSL / 1000,\n geom = c(\"point\",\"smooth\"),\n se = FALSE,\n xlab = expression(paste(\"Assessed HQ Sawlog ('000 \", m^3, \")\")),\n ylab = expression(paste(\"Actual HQ Sawlog ('000 \", m^3, \")\")),\n method = \"lm\",\n alpha = I(0.4),\n data = coupes) +\n geom_abline(aes(slope = 1, intercept = 0), linetype = 4, colour = \"darkgrey\") +\n geom_smooth(se = FALSE, linetype = 2)\ndev.off()\n\nstr(coupes)\n\ntable(coupes$HARVYEAR)\ntable(coupes$ForestQualityClass)\n\ncoupes$fit <- TRUE\ncoupes$fit[coupes$HARVYEAR > 2007] <- FALSE\n\n################################################################################\n################################################################################\n################################################################################\n\n## Generate helper functions\n\nsummary.lpExtPtr <- function(x, target, ...) {\n cut.me <- get.variables(x)\n num.coupes.cut <- sum(cut.me)\n area.cut <- sum(cut.me * target$grossArea)\n volume.cut <- sum(cut.me * target$SalesHQSL)\n volume.cut.hat <- sum(cut.me * target$mu.hat)\n out <- list(cut.me = cut.me,\n num.coupes.cut = num.coupes.cut,\n area.cut = area.cut,\n volume.cut = volume.cut,\n volume.cut.hat = volume.cut.hat)\n class(out) <- \"summary.lpExtPtr\"\n return(out)\n}\n\nsimulate.summary.lpExtPtr <-\n function(object, nsim = 1, seed = NULL, ...) {\n sim.volume <-\n lapply(1:nsim,\n function(x)\n with(to.cut[object$cut.me == 1, ],\n sum(rGA(sum(object$cut.me),\n mu = mu.hat,\n sigma = sigma.hat))))\n return(unlist(sim.volume))\n }\n\n################################################################################\n################################################################################\n################################################################################\n\n## Fit and compare some models\n\ntest.0 <- gamlss(SalesHQSL ~ log(grossHQSLest),\n sigma.formula = ~ 1,\n sigma.link = \"log\",\n family = GA(),\n data = coupes)\n\ntest.1 <- gamlss(SalesHQSL ~ log(grossHQSLest),\n sigma.formula = ~ log(grossHQSLest),\n sigma.link = \"log\",\n family = GA(),\n data = coupes)\n\nLR.test(test.0, test.1)\n\nsummary(test.1)\n\ntest.2 <- gamlss(SalesHQSL ~ pb(log(grossHQSLest)),\n sigma.formula = ~ 1,\n sigma.link = \"log\",\n family = GA(),\n data = coupes)\n\nLR.test(test.0, test.2)\n\ntest.3 <- gamlss(SalesHQSL ~ log(grossHQSLest) * ForestQualityClass,\n sigma.formula = ~ 1,\n sigma.link = \"log\",\n family = GA(),\n data = coupes)\n\nsummary(test.3)\nLR.test(test.0, test.3)\n\ntest.5 <- gamlss(SalesHQSL ~ poly(log(grossHQSLest), 2) * ForestQualityClass,\n sigma.formula = ~ ForestQualityClass,\n sigma.link = \"log\",\n family = GA(),\n data = coupes)\n\nsummary(test.5)\nLR.test(test.0, test.5)\n\n## Modest difference.\n\ntrajectory.5 <-\n with(coupes,\n expand.grid(grossHQSLest =\n seq(from = min(grossHQSLest),\n to = max(grossHQSLest),\n length.out = 100),\n ForestQualityClass = levels(coupes$ForestQualityClass)))\n\nnew.dist.5 <- predictAll(test.5, newdata = trajectory.5)\n\ntrajectory.5$mu <- new.dist.5$mu\ntrajectory.5$sigma <- new.dist.5$sigma\ntrajectory.5$upper.2 <- with(new.dist.5, qGA(0.95, mu = mu, sigma = sigma))\ntrajectory.5$lower.2 <- with(new.dist.5, qGA(0.05, mu = mu, sigma = sigma))\ntrajectory.5$upper.1 <- with(new.dist.5, qGA(0.67, mu = mu, sigma = sigma))\ntrajectory.5$lower.1 <- with(new.dist.5, qGA(0.33, mu = mu, sigma = sigma))\n\n# setEPS()\n# postscript(\"model.eps\", height=6, width=6)\npdf(\"Figure 2 ex.pdf\", height=6, width=6)\n\np.5 <-\n ggplot(coupes,\n aes(x = grossHQSLest / 1000,\n y = SalesHQSL / 1000)) +\n# geom_point(aes(shape = fit)) +\n geom_point(alpha=0.4) +\n# scale_colour_discrete(name = \"Source\", labels = c(\"Test\",\"Fit\")) +\n facet_wrap(~ ForestQualityClass) +\n xlab(expression(paste(\"Assessed HQ Sawlog ('000 \", m^3, \")\"))) +\n ylab(expression(paste(\"Actual HQ Sawlog ('000 \", m^3, \")\"))) +\n# geom_smooth(aes(colour = fit),\n# method = \"lm\", formula = y ~ pb(x), se = FALSE) +\n geom_line(aes(y = mu / 1000, x = grossHQSLest / 1000),\n data = trajectory.5) +\n geom_line(aes(y = lower.2 / 1000, x = grossHQSLest / 1000),\n linetype = \"dashed\", data = trajectory.5) +\n geom_line(aes(y = upper.2 / 1000, x = grossHQSLest / 1000),\n linetype = \"dashed\", data = trajectory.5) +\n geom_line(aes(y = lower.1 / 1000, x = grossHQSLest / 1000),\n linetype = \"dotted\", data = trajectory.5) +\n geom_line(aes(y = upper.1 / 1000, x = grossHQSLest / 1000),\n linetype = \"dotted\", data = trajectory.5) +\n ylim(c(0,10))\nplot(p.5)\n\ndev.off()\n\n################################################################################\n################################################################################\n\n# Settle on model 5. Obtain predictions for withheld stands\n\nto.cut <-\n droplevels(subset(coupes, !fit &\n ForestQualityClass %in%\n levels(coupes$ForestQualityClass)))\n\nto.cut.hat.cut <- predictAll(test.5, newdata = to.cut)\n\nto.cut$mu.hat <- to.cut.hat.cut$mu\nto.cut$sigma.hat <- to.cut.hat.cut$sigma\n\npar(mfrow=c(1,3))\nplot(SalesHQSL ~ mu.hat, data = to.cut)\nplot(SalesHQSL ~ grossHQSLest, data = to.cut)\nplot(mu.hat ~ grossHQSLest, data = to.cut)\n\n################################################################################\n################################################################################\n\n### Now use LP to optimize. This script portion benefits from prior\n### work at\n### http://fishyoperations.com/r/linear-programming-in-r-an-lpsolveapi-example\n### see also\n### http://www.r-bloggers.com/linear-programming-in-r-an-lpsolveapi-example/\n\n## Here's an example that cuts le 15 stands, total area le 1000 ha,\n## one year, max volume.\n\n## ops creates the annual constraints\n\nops <- data.frame(year = c('y1'),\n area = c(1000),\n equip = c(30))\n\nlpmodel.harvest <- make.lp(2*NROW(ops) + NROW(to.cut), NROW(ops) * NROW(to.cut))\n\ncolumn <- 0\nrow <- 0\n\n# build the model column by column\n\nfor(wg in ops$year){\n row <- row + 1\n for(coupe in seq(1, NROW(to.cut))){\n column <- column + 1\n# this takes the arguments 'column','values' & 'indices' (as in where\n# these values should be placed in the column)\n set.column(lpmodel.harvest,\n column,\n c(1, to.cut[coupe,'grossArea'], 1),\n indices = c(row, NROW(ops) + row, NROW(ops)*2 + coupe))\n }}\n\n# set rhs weight constraints - first triplet\nset.constr.value(lpmodel.harvest, # The lp model\n rhs = ops$equip, # The values\n constraints = seq(1, NROW(ops))) # Where to put them\n\n# set rhs volume constraints - second triplet\nset.constr.value(lpmodel.harvest,\n rhs = ops$area,\n constraints = seq(NROW(ops)+1, NROW(ops)*2))\n\n# set rhs availability constraints - last quadruplet\n\nset.constr.value(lpmodel.harvest,\n rhs = rep(1, NROW(to.cut)),\n constraints = seq(NROW(ops)*2+1, NROW(ops)*2+NROW(to.cut)))\n\n# set objective coefficients - here the simulated average\n\nset.objfn(lpmodel.harvest, rep(to.cut$mu.hat, NROW(ops)))\n\n# set objective direction\n\nlp.control(lpmodel.harvest, sense = 'max')\n\n# Ensure integers - works!\n\nget.type(lpmodel.harvest)\nset.type(lpmodel.harvest, 1:length(get.type(lpmodel.harvest)), \"integer\")\n\n# solve the model; if this returns 0 then an optimal solution has been found\n\nsolve(lpmodel.harvest)\n\n# this returns the proposed solution\n\nget.objective(lpmodel.harvest)\n\n# Coupe choices\n\n(base <- summary(lpmodel.harvest, target = to.cut))\n\npar(mfrow=c(1,3))\nplot(SalesHQSL ~ mu.hat, data = to.cut,\n pch=c(1,19)[base$cut.me + 1])\nplot(SalesHQSL ~ grossHQSLest, data = to.cut,\n pch=c(1,19)[base$cut.me + 1])\nplot(mu.hat ~ grossHQSLest, data = to.cut,\n pch=c(1,19)[base$cut.me + 1])\n\n#########################################################################################\n#\n# FTM I have a stand prescription. I should generate a bunch of random volumes\n# corresponding to these predictions.\n#\n#########################################################################################\n\nbase.sim.volume <-\n sapply(1:10000,\n function(x)\n with(to.cut[base$cut.me == 1,],\n sum(rGA(sum(base$cut.me), # if n = 1 then randoms are correlated!\n mu = mu.hat,\n sigma = sigma.hat)))) / 1000\n\n## Graphical summary.\n\npar(mfrow=c(1,2), mar=c(5,4,3,2), las=1)\nplot(density(base.sim.volume), xlim = c(50,300), main=\"Distribution\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nabline(v = base$volume.cut/1000, lty = 2)\nabline(v = base$volume.cut.hat/1000)\nabline(v = quantile(base.sim.volume, p = c(0.05, 0.95)), col = \"darkgrey\")\n#qqnorm(base.sim.volume); qqline(base.sim.volume)\nplot(ecdf(base.sim.volume), xlim = c(0,500), main=\"CDF\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nabline(v = base$volume.cut/1000, lty = 2)\nabline(v = base$volume.cut.hat/1000)\nabline(v = quantile(base.sim.volume, p = c(0.05, 0.95)), col = \"darkgrey\")\n\n## This provides us with, as hoped for, probabilistic information\n## about the expected return.\n\n## For example, what is the mean expected return?\n\nmean(base.sim.volume)\n\n## What is the probability of achieving the mean objective?\n\nmean(base.sim.volume > base$volume.cut.hat / 1000)\n\n## What is the 90% prediction interval?\n\nquantile(base.sim.volume, p = c(0.05, 0.95))\n\n## How can this be related back to headroom? 10%? 20%? 30%?\n\nmean(base.sim.volume > base$volume.cut.hat * 0.9 / 1000) # 10% HR\nmean(base.sim.volume > base$volume.cut.hat * 0.8 / 1000) # 20% HR\nmean(base.sim.volume > base$volume.cut.hat * 0.7 / 1000) # 30% HR\n\n## We could compare this with a clearly inadequate correction, such as\n## a straight ratio, somehow.\n\n## What is the proportion reduced relative to expectations?\n\n(base$volume.cut.hat - base$volume.cut) / base$volume.cut.hat\n\n################################################################################\n################################################################################\n\n# Now penalize optimization by uncertainty. Start simply: use the 0.1\n# quantile as the objective, and analyze as above.\n\nset.objfn(lpmodel.harvest,\n rep(with(to.cut, qGA(0.1, mu = mu.hat, sigma = sigma.hat)),\n NROW(ops)))\n\nsolve(lpmodel.harvest)\n\nget.objective(lpmodel.harvest)\n\n# Coupe choices\n\n(q10 <- summary(lpmodel.harvest, target = to.cut))\n\ncor(base$cut.me, q10$cut.me)\n\nq10.sim.volume <-\n sapply(1:10000,\n function(x)\n with(to.cut[q10$cut.me == 1,],\n sum(rGA(sum(q10$cut.me), # if n = 1 then randoms are correlated!\n mu = mu.hat,\n sigma = sigma.hat)))) / 1000\n\n## Graphical summary.\n\npar(mfrow=c(1,2), mar=c(5,4,3,2), las=1)\nplot(density(q10.sim.volume), xlim = c(0,100), main=\"Distribution\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nlines(density(base.sim.volume), col = \"darkgrey\")\nabline(v = q10$volume.cut/1000, lty = 2)\nabline(v = q10$volume.cut.hat/1000)\nabline(v = quantile(q10.sim.volume, p = c(0.05, 0.95)))\n#qqnorm(base.sim.volume); qqline(base.sim.volume)\nplot(ecdf(q10.sim.volume), xlim = c(0,100), main=\"CDF\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nlines(ecdf(base.sim.volume), col = \"darkgrey\")\nabline(v = q10$volume.cut/1000, lty = 2)\nabline(v = q10$volume.cut.hat/1000)\nabline(v = quantile(q10.sim.volume, p = c(0.05, 0.95)))\n\n## This provides us with, as hoped for, probabilistic information\n## about the expected return. For example, what is the probability of\n## achieving the implied objective?\n\nmean(q10.sim.volume > q10$volume.cut / 1000)\n\n## How can this be related back to headroom? 10%? 20%? 30%?\n\nmean(q10.sim.volume > q10$volume.cut * 0.9 / 1000) # 10% HR\nmean(q10.sim.volume > q10$volume.cut * 0.8 / 1000) # 20% HR\nmean(q10.sim.volume > q10$volume.cut * 0.7 / 1000) # 30% HR\n\nquantile(q10.sim.volume, p = c(0.05, 0.95))\n\n#### Compare with Base in Figure 3 (below)\n\n\n################################################################################\n\n## Try to minimize variance given constraints on volume\n\nsum(to.cut$grossArea)\n\nsum(to.cut$mu.hat)\n\nto.cut$variance <- with(to.cut, mu.hat^2 * sigma.hat^2)\n\nops <- data.frame(year = c('y1'),\n area = c(1000),\n cut.out = c(17100))\n\n# create an LP model\n\nlpmodel.harvest <- make.lp(2*NROW(ops) + NROW(to.cut), NROW(ops) * NROW(to.cut))\n\n# I used this to keep count within the loops, I admit that this could\n# be done a lot neater\n\ncolumn <- 0\nrow <- 0\n\n# build the model column per column\n\nfor(wg in ops$year){\n row <- row + 1\n for(coupe in seq(1, NROW(to.cut))){\n column <- column + 1\n# this takes the arguments 'column','values' & 'indices' (as in where\n# these values should be placed in the column)\n set.column(lpmodel.harvest,\n column,\n c(to.cut[coupe, 'mu.hat'], to.cut[coupe, 'grossArea'], 1),\n indices = c(row, NROW(ops) + row, NROW(ops)*2 + coupe))\n }}\n\n# set rhs equipment constraints - first triplet\nset.constr.value(lpmodel.harvest, # The lp model\n rhs = ops$cut.out, # The values\n constraints = seq(1, NROW(ops))) # Where to put them\n\n# set rhs area constraints - second triplet\nset.constr.value(lpmodel.harvest,\n rhs = ops$area,\n constraints = seq(NROW(ops)+1, NROW(ops)*2))\n\n# set rhs availability constraints - last quadruplet\n\nset.constr.value(lpmodel.harvest,\n rhs = rep(1, NROW(to.cut)),\n constraints = seq(NROW(ops)*2+1, NROW(ops)*2+NROW(to.cut)))\n\nset.constr.type(lpmodel.harvest,\n c(rep(\">=\", NROW(ops)),\n rep(\"<=\", NROW(ops)),\n rep(\"<=\", NROW(to.cut))))\n\n# set objective coefficients - here the simulated average\n\nset.objfn(lpmodel.harvest, rep(to.cut$variance, NROW(ops)))\n\n# set objective direction\n\nlp.control(lpmodel.harvest, sense='min')\n\n# Ensure integers - works!\n\nset.type(lpmodel.harvest, 1:length(get.type(lpmodel.harvest)), \"integer\")\n\n# I in order to be able to visually check the model, I find it useful\n# to write the model to a text file\n\nwrite.lp(lpmodel.harvest, 'harvest.lp', type = 'lp')\n\n# solve the model, if this return 0 an optimal solution is found\n\nsolve(lpmodel.harvest)\n\n# this returns the proposed solution\n\nget.objective(lpmodel.harvest)\n\n# Coupe choices\n\n(port.1 <- summary(lpmodel.harvest, target = to.cut))\n\nout.1 <- simulate(port.1, nsim = 1000)\n\nplot(density(out.1))\n\n\n#########################################################################################\n#########################################################################################\n#########################################################################################\n#########################################################################################\n\n## Write a portfolio function\n\nportfolio <- function(min.vol, target = to.cut, area = 2000) {\n ops <- data.frame(year = c('y1'),\n area = c(area),\n cut.out = c(min.vol))\n lpmodel.harvest <- make.lp(2*NROW(ops) + NROW(to.cut), NROW(ops) * NROW(to.cut))\n column <- 0\n row <- 0\n for(wg in ops$year){\n row <- row + 1\n for(coupe in seq(1, NROW(to.cut))){\n column <- column + 1\n set.column(lpmodel.harvest,\n column,\n c(to.cut[coupe, 'mu.hat'], to.cut[coupe, 'grossArea'], 1),\n indices = c(row, NROW(ops) + row, NROW(ops)*2 + coupe))\n }}\n set.constr.value(lpmodel.harvest, # The lp model\n rhs = ops$cut.out, # The values\n constraints = seq(1, NROW(ops))) # Where to put them\n set.constr.value(lpmodel.harvest,\n rhs = ops$area,\n constraints = seq(NROW(ops)+1, NROW(ops)*2))\n set.constr.value(lpmodel.harvest,\n rhs = rep(1, NROW(to.cut)),\n constraints = seq(NROW(ops)*2+1, NROW(ops)*2+NROW(to.cut)))\n set.constr.type(lpmodel.harvest,\n c(rep(\">=\", NROW(ops)),\n rep(\"<=\", NROW(ops)),\n rep(\"<=\", NROW(to.cut))))\n set.objfn(lpmodel.harvest, rep(to.cut$variance, NROW(ops)))\n lp.control(lpmodel.harvest, sense='min')\n set.type(lpmodel.harvest, 1:length(get.type(lpmodel.harvest)), \"integer\")\n solve(lpmodel.harvest)\n return(summary(lpmodel.harvest, target = target))\n}\n\n\n\n################################################################################\n\nminima <- (15:25)*1000\n\nreturns <- mclapply(minima, portfolio, mc.cores = 4)\n\nlapply(returns, function(x) sum(x$cut.me))\n\nsim.returns <- mclapply(returns, simulate, nsim = nsim, mc.cores = 4)\n\nsimexp <- data.frame(volume.cut = do.call(c, sim.returns),\n minima = rep(minima, each = nsim))\n\nggplot(simexp,\n aes(x = factor(minima), y = volume.cut)) +\n geom_violin() +\n xlab(expression(paste(\"Minimum prescribed cut (\", m^3, \")\"))) +\n ylab(expression(paste(\"Achieved cut (\", m^3, \")\"))) +\n geom_point(aes(x = factor(minima), y = minima))\n\nggplot(simexp,\n aes(x = factor(minima), y = volume.cut)) +\n geom_boxplot() +\n xlab(expression(paste(\"Minimum prescribed cut (\", m^3, \")\"))) +\n ylab(expression(paste(\"Achieved cut (\", m^3, \")\")))\n\nlapply(sim.returns, function (x) (var(x)) / mean(x))\n\ncv <- function (x) (sd(x)) / mean(x)\n\nsapply(sim.returns, cv)\n\nsapply(sim.returns, sd)\n\nsapply(sim.returns, mean)\n\nsim.results <- data.frame(minima = minima,\n mean = sapply(sim.returns, mean),\n sd = sapply(sim.returns, sd),\n cv = sapply(sim.returns, cv))\n\nwrite.csv(sim.results, file = \"simresults.csv\", row.names = FALSE)\n\n################################################################################\n\n## What if we now try to achieve the same volume with min variance?\n\ncf.base <- portfolio(mean(base.sim.volume)*1000)\n\ncf.sim.volume <-\n sapply(1:10000,\n function(x)\n with(to.cut[cf.base$cut.me == 1,],\n sum(rGA(sum(cf.base$cut.me), # if n = 1 then randoms are correlated!\n mu = mu.hat,\n sigma = sigma.hat)))) / 1000\n\n## Graphical summary.\n\npar(mfrow=c(1,2), mar=c(5,4,3,2), las=1)\nplot(density(base.sim.volume), xlim = c(20, 90), main=\"Distribution\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nlines(density(cf.sim.volume), col = \"darkgrey\")\nabline(v = base$volume.cut/1000, lty = 2)\nabline(v = base$volume.cut.hat/1000)\nabline(v = quantile(base.sim.volume, p = c(0.05, 0.95)), lty = 3)\n#qqnorm(base.sim.volume); qqline(base.sim.volume)\nplot(ecdf(base.sim.volume), xlim = c(20, 90), main=\"CDF\",\n xlab = expression(paste(\"Assessed Sawlog ('000 \", m^3, \")\")))\nlines(ecdf(q10.sim.volume), col = \"grey\")\nlines(ecdf(cf.sim.volume), col = \"darkgrey\")\n#abline(v = base$volume.cut/1000, lty = 2)\n#abline(v = base$volume.cut.hat/1000)\n#abline(v = quantile(base.sim.volume, p = c(0.05, 0.95)))\n\n\n\nqq.base <- qqnorm(base.sim.volume, plot.it = FALSE)\nqq.q10 <- qqnorm(q10.sim.volume, plot.it = FALSE)\nqq.cf <- qqnorm(cf.sim.volume, plot.it = FALSE)\n\ngrain <- 1000\n\nx.range <- (min(base.sim.volume) * 10):(max(base.sim.volume) * 10) / 10\n\nflip <- function(object) return(list(x = object$y, y = object$x))\n\npdf(file = \"Figure 3 ex.pdf\", height = 3.5, width = 8)\n\npar(mfrow=c(1,2), mar=c(5,4,1,2), las=1)\nplot(density(base.sim.volume), main = \"\",\n xlab = expression(paste(\"Assessed HQ Sawlog ('000 \", m^3, \")\")))\n#lines(density(q10.sim.volume), col = \"darkgrey\")\nabline(v = base$volume.cut/1000, lty = 2)\nabline(v = base$volume.cut.hat/1000)\nabline(v = quantile(base.sim.volume, p = c(0.05, 0.95)), lty = 3)\n\nplot(with(flip(qq.base), predict(smooth.spline(x, y), x = x.range)),\n type = \"l\", axes = FALSE,\n ylim = c(-4, 4),\n xlab = expression(paste(\"Assessed HQ Sawlog ('000 \", m^3, \")\")),\n ylab = expression(paste(F[x](X))))\nbox()\naxis(1)\naxis(2, at = c(-4:4), label = c(\"0\", formatC(pnorm(-3:4))), cex.axis=0.8)\nlines(with(flip(qq.q10), predict(smooth.spline(x, y), x = x.range)),\n type=\"l\", lty = 2)\nlines(with(flip(qq.cf), predict(smooth.spline(x, y), x = x.range)),\n type=\"l\", lty = 3)\nlegend(\"bottomright\", lty = 1:3, bty = \"n\", cex = 0.9,\n legend=c(\"Maximize Mean\",\"Maximize Q10\",\"Minimize Variance\"))\n\ndev.off()\n\n\n\n", "meta": {"hexsha": "eaca288662ede2f76157a7250005149edd604d3c", "size": 23096, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Params/Robinson_Moss_uncertainty_harvest_scheduling.r", "max_stars_repo_name": "bcgov/clus", "max_stars_repo_head_hexsha": "e0d4e49f031126ee40f36b338651b9fddc180f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-07-26T23:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:55:46.000Z", "max_issues_repo_path": "R/Params/Robinson_Moss_uncertainty_harvest_scheduling.r", "max_issues_repo_name": "ElizabethKleynhans/clus", "max_issues_repo_head_hexsha": "a02aef861712ab62bb5b5877208a138e0074e365", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2018-04-25T19:31:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:08:36.000Z", "max_forks_repo_path": "R/Params/Robinson_Moss_uncertainty_harvest_scheduling.r", "max_forks_repo_name": "ElizabethKleynhans/clus", "max_forks_repo_head_hexsha": "a02aef861712ab62bb5b5877208a138e0074e365", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-04-25T17:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:53:23.000Z", "avg_line_length": 32.9002849003, "max_line_length": 89, "alphanum_fraction": 0.5422583997, "num_tokens": 6351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4923376642688862}} {"text": "model_leafnumber <- function (deltaTT = 23.5895677277199,\n phyllochron_t1 = 0.0,\n hasFlagLeafLiguleAppeared = 0,\n leafNumber_t1 = 0.0,\n phase = 1.0){\n #'- Name: LeafNumber -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: CalculateLeafNumber Model\n #' * Author: Pierre MARTRE\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: calculate leaf number. LeafNumber increase is caped at one more leaf per day\n #'- inputs:\n #' * name: deltaTT\n #' ** description : daily delta TT \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -20\n #' ** max : 100\n #' ** default : 23.5895677277199\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: phyllochron_t1\n #' ** description : phyllochron\n #' ** variablecategory : state\n #' ** inputtype : variable\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 0\n #' ** unit : °C d leaf-1\n #' * name: hasFlagLeafLiguleAppeared\n #' ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber)\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** inputtype : variable\n #' * name: leafNumber_t1\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 0\n #' ** unit : leaf\n #' ** inputtype : variable\n #' * name: phase\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** default : 1\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : variable\n #'- outputs:\n #' * name: leafNumber\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : leaf\n #' ** uri : some url\n leafNumber <- leafNumber_t1\n if (phase >= 1.0 && phase < 4.0)\n {\n if (hasFlagLeafLiguleAppeared == 0)\n {\n if (phyllochron_t1 == 0.0)\n {\n phyllochron_ <- 0.0000001\n }\n else\n {\n phyllochron_ <- phyllochron_t1\n }\n leafNumber <- leafNumber_t1 + min(deltaTT / phyllochron_, 0.999)\n }\n }\n return (list('leafNumber' = leafNumber))\n}", "meta": {"hexsha": "130ff2350a8cdbddf1bd94798fd992bae8e469c6", "size": 4059, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Leafnumber.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Leafnumber.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Leafnumber.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 46.125, "max_line_length": 116, "alphanum_fraction": 0.3535353535, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4920904307676351}} {"text": "# MIT License\n# Copyright (c) 2020 Abhinav Prakash, Vijay Panchang, Yu Ding, and Lewis Ntaimo\n \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nsource(\"function.r\")\ninputfile = \"hackensack.csv\"\noutputfile = \"Results/hackensack_constrained_MCMC_\"\noutputplot = \"Hackensack River\"\ndata_col = 3\nyear_col = 1\nReferenceYear = 2018\nReturnPeriod = 100\nburn_in = 500\nCSVFile = read.csv(file = inputfile, header = T)\nData = CSVFile[,data_col]\nYear = CSVFile[,year_col]\ntime_index = time.index(Year,ReferenceYear)\nparameters = draw.MCMC.samples(Data,time_index,InitialValues = c(50,1,20,0.8),LocationInterceptPrior = c(0,200),LocationSlopePrior = c(-5,5),ScalePrior = c(-50,50),ShapePrior = c(-1,1),ProposalWidth = c(2,0.15,1,0.05),n_samples=10000)\nparameters = parameters[-c(1:burn_in),]\nmu_post = parameters[,1]\nmuslope_post = parameters[,2]\nscale_post = parameters[,3]\nshape_post = parameters[,4]\n\n\n### Expected and MAP Values of the parameters and the return event \nbw = c(2,0.02,0.75,0.020,10)\nd_mu = density(mu_post, bw = bw[1])\nd_muslope = density(muslope_post, bw = bw[2])\nd_scale = density(scale_post, bw= bw[3])\nd_shape = density(shape_post, bw = bw[4])\nmu_exp = mean(mu_post)\nmu_map = d_mu$x[which.max(d_mu$y)]\nmuslope_exp = mean(muslope_post)\nmuslope_map = d_muslope$x[which.max(d_muslope$y)]\nscale_exp = mean(scale_post)\nscale_map = d_scale$x[which.max(d_scale$y)]\nshape_exp =mean(shape_post)\nshape_map = d_shape$x[which.max(d_shape$y)]\nNLLH_exp = likelihood.val(Data,time_index,mu_exp,muslope_exp,scale_exp,shape_exp)\nNLLH_map = likelihood.val(Data,time_index,mu_map,muslope_map,scale_map,shape_map)\ncat(\"Expected Values of the Parameters:\",'\\n')\ncat(\"Location Intercept:\", mu_exp, '\\n')\ncat(\"Location Slope:\", muslope_exp, '\\n')\ncat(\"Scale:\",scale_exp, '\\n')\ncat(\"Shape:\", shape_exp, '\\n')\ncat(\"NLLH:\", NLLH_exp, '\\n')\ncat('\\n',\"MAP values of the Parameters:\",'\\n')\ncat(\"Location Intercept:\", mu_map, '\\n')\ncat(\"Location Slope:\", muslope_map, '\\n')\ncat(\"Scale:\",scale_map, '\\n')\ncat(\"Shape:\", shape_map, '\\n')\ncat(\"NLLH:\", NLLH_map, '\\n')\n\n", "meta": {"hexsha": "6f4158eeaf7d31b949313422a43ac67bd0117a4d", "size": 3054, "ext": "r", "lang": "R", "max_stars_repo_path": "UCBM_Hackensack.r", "max_stars_repo_name": "abhinavprakash2006/SCBM-R", "max_stars_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:24:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:24:28.000Z", "max_issues_repo_path": "UCBM_Hackensack.r", "max_issues_repo_name": "abhinavprakash2006/SCBM-R", "max_issues_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UCBM_Hackensack.r", "max_forks_repo_name": "abhinavprakash2006/SCBM-R", "max_forks_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4166666667, "max_line_length": 234, "alphanum_fraction": 0.7442698101, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4919400467578895}} {"text": "# 산술연산 \n\ntot1 <- -5\ntot2 <- 10\n\ntot1+tot2\ntot1-tot2\ntot1*tot2\ntot1/tot2\ntot1^tot2\n\n# 마지막 것은 제곱 **로 해도 됨", "meta": {"hexsha": "98a76a9580463eef7fc52aea6c880532a54a7826", "size": 103, "ext": "r", "lang": "R", "max_stars_repo_path": "ch01 - 기초/03. 산술연산.r", "max_stars_repo_name": "Lee-changyul/Rstudy_Lee", "max_stars_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch01 - 기초/03. 산술연산.r", "max_issues_repo_name": "Lee-changyul/Rstudy_Lee", "max_issues_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch01 - 기초/03. 산술연산.r", "max_forks_repo_name": "Lee-changyul/Rstudy_Lee", "max_forks_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 8.5833333333, "max_line_length": 20, "alphanum_fraction": 0.640776699, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4919287469006521}} {"text": "subroutine crossutil(i,j,k,x,y,ntot,eps,collin)\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot)\ndimension xt(3), yt(3)\nlogical collin\n\nxt(1) = x(i)\nyt(1) = y(i)\nxt(2) = x(j)\nyt(2) = y(j)\nxt(3) = x(k)\nyt(3) = y(k)\n\n# Create indicator telling which of i, j, and k are ideal points.\n# The point being added, i, is never ideal.\ni1 = 0\nif(j<=0) j1 = 1\nelse j1 = 0\nif(k<=0) k1 = 1\nelse k1 = 0\nijk = i1*4+j1*2+k1\n\ncall cross(xt,yt,ijk,cprd)\ncollin = (abs(cprd) < eps)\nreturn\nend\n", "meta": {"hexsha": "f8bdf5a5f7c643b89b6154ed9357c0d01c82eb92", "size": 492, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/ratfor/crossutil.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/ratfor/crossutil.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/ratfor/crossutil.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 18.2222222222, "max_line_length": 65, "alphanum_fraction": 0.6300813008, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4916880766429436}} {"text": "# Returns Lambda, or P(+|S=t)\nEstLambda = function(S, X, t, idx, h = NULL){\n \n tryCatch({\n Sorder <- order(S, decreasing=TRUE)\n m <- length(S)\n idx.range <- c(max(1, idx - 1000), min(length(S), idx + 1000))\n \n S.ordered <- S[Sorder][idx.range[1]:idx.range[2]]\n X.ordered <- X[Sorder][idx.range[1]:idx.range[2]]\n \n ## --1 Kernsmooth bandwidth estimator\n ## more accurate, but prone to errors\n # if(is.null(h)) h <- KernSmooth::dpill(x = S.ordered, y = X.ordered, gridsize = 100)\n \n ## --2 Rule of thumb estimator\n ## Should not throw an error\n if(is.null(h)) h <- (m^{-1/5}) * sd(S)\n \n lp0 <- KernSmooth::locpoly(x = S.ordered, y = X.ordered, bandwidth = h, degree = 0,\n range.x = range(S.ordered), gridsize = 1000)\n \n lp0.idx <- which.min(abs(lp0$x - t))\n lam <- lp0$y[lp0.idx]\n }, error = function(e) {\n stop(\"Lambda estimate failed. Try setting h manually.\")\n }\n )\n \n return(lam)\n}\n\n#' Perform a hypothesis test for the difference between two performance curves.\n#' \n#' \\code{PerfCurveTest} takes score vectors for two scoring algorithms and an activity vector.\n#' A performance curve is created for the two scoring algorithms and hypothesis tests are performed\n#' at the selected testing fractions. \n#' \n#' @param S1 a vector of scores for scoring algorithm 1.\n#' @param S2 a vector of scores for scoring algorithm 2.\n#' @param X a vector of activities.\n#' @param r a vector of testing fractions.\n#' @param metric the performance curve to use. Options are recall (\"rec\") and precision (\"prec\").\n#' @param method the method to use. Recall options are \n#' c(\"EmProc\", \"binomial\", \"JZ ind\", \"mcnemar\", \"binomial ind\"). Precision options are\n#' c(\"EmProc\", \"binomial\", \"JZ ind\", \"stouffer\", \"binomial ind\").\n#' @param plus should plus correction be used or not?\n#' @param pool use pooling for hypothesis tests or not? (only relevant to \"EmProc\")\n#' @param alpha the significance level.\n#' \n#' @export\nPerfCurveTest <- function(S1, S2, X, r, metric = \"rec\", method = \"EmProc\",\n plus = T, pool = F, alpha = .05, h = NULL, seed = 111){\n \n # TODO need some more error checking here\n if(pool & method != \"EmProc\") warning(\"Pooling only relevant to EmProc and will not be applied\")\n \n \n set.seed(seed)\n m <- length(S1) #total sample size\n r.all <- (1:m)/m\n idx <- which(r.all %in% r)\n \n # Z Quantile for CIs\n quant <- qnorm(1-alpha/2)\n \n # Convert fractions in r to thresholds, for both sets of scores\n # Also accumulate the number of actives, for each score and jointly\n F1cdf <- ecdf(S1); yyobs <- sort(unique(S1))\n F1inv <- stepfun(x = F1cdf(yyobs), y = c(yyobs, max(yyobs)), right=TRUE, f=1)\n F2cdf <- ecdf(S2); yyobs <- sort(unique(S2))\n F2inv <- stepfun(x = F2cdf(yyobs), y = c(yyobs, max(yyobs)), right=TRUE, f=1)\n hits1 <- hits2 <- hits12 <- ntest12 <- vector(length = length(r))\n for(i in 1:length(r)) {\n t1 <- F1inv(1-r[i])\n t2 <- F2inv(1-r[i])\n hits1[i] <- sum(X*(S1 > t1))\n hits2[i] <- sum(X*(S2 > t2))\n hits12[i] <- sum(X*(S1 > t1 & S2 > t2))\n ntest12[i] <- sum(S1 > t1 & S2 > t2)\n }\n nact <- sum(X) #total number of actives\n ntest <- (m*r) #number of compounds tested\n \n # Uncorrected parameters\n r <- ntest/m\n pi.0 <- nact/m\n k1 <- (hits1)/nact\n k2 <- (hits2)/nact\n k12 <- (hits12)/nact\n pi1 <- pi.0/r*k1\n pi2 <- pi.0/r*k2\n r12 <- ntest12/m\n pi12 <- hits12/ntest12\n pi12 <- ifelse(is.na(pi12), 0, pi12)\n # pooled estimates\n pi <- (pi1 + pi2)/2\n k <- (k1 + k2)/2\n \n if(plus) {\n hits1.c <- hits1 + 1\n hits2.c <- hits2 + 1\n nact.c <- nact + 2 \n ntest.c <- ntest + 1\n m.c <- m + 2\n } else {\n hits1.c <- hits1\n hits2.c <- hits2\n nact.c <- nact \n ntest.c <- ntest\n m.c <- m\n }\n \n # Corrected parameters\n r.c <- ntest.c/m.c\n pi.0.c <- nact.c/m.c\n k1.c <- (hits1.c)/nact.c\n k2.c <- (hits2.c)/nact.c\n k12.c <- (hits12)/nact.c\n pi1.c <- (hits1.c)/(ntest.c)\n pi2.c <- (hits2.c)/(ntest.c)\n r12.c <- ntest12/m.c\n pi12.c <- hits12/ntest12\n pi12.c <- ifelse(is.na(pi12.c), 0, pi12.c)\n \n \n Lam1.vec <- vector(length = length(k1))\n Lam2.vec <- vector(length = length(k1))\n for(j in seq_along(k1)){\n Lam1.vec[j] <- EstLambda(S1, X, t = F1inv(1-r[j]), idx = idx[j], h)\n Lam2.vec[j] <- EstLambda(S2, X, t = F2inv(1-r[j]), idx = idx[j], h)\n }\n \n CI.int <- matrix(ncol = 2, nrow = length(k1))\n se.p <- se.np <- p.val <- vector(length = length(k1))\n if(metric == \"rec\") {\n if(method %in% c(\"JZ ind\", \"EmProc\")){\n for(j in seq_along(k1)) {\n \n Lam1 <- Lam1.vec[j]\n Lam2 <- Lam2.vec[j]\n \n # unpooled variances\n var1.k.np <- ((k1.c[j]*(1-k1.c[j]))/(m.c*pi.0.c))*(1-2*Lam1) +\n (Lam1^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n # Check to see if var.k.np is negative due to m.cachine precision problem.c\n var1.k.np <- ifelse(var1.k.np < 0, 0, var1.k.np)\n var2.k.np <- ((k2.c[j]*(1-k2.c[j]))/(m.c*pi.0.c))*(1-2*Lam2) +\n (Lam2^2*(1-r.c[j])*r.c[j])/(m.c*pi.0.c^2)\n var2.k.np <- ifelse(var2.k.np < 0, 0, var2.k.np)\n cov.k.np <- (m.c^-1*pi.0.c^-2)*(pi.0.c*(k12.c[j]-k1.c[j]*k2.c[j])*(1-Lam1-Lam2) +\n (r12.c[j]-r.c[j]^2)*Lam1*Lam2)\n \n # pooled variances \n var1.k.p <- ((k[j]*(1-k[j]))/(m*pi.0))*(1-2*Lam1) +\n (Lam1^2*(1-r[j])*r[j])/(m*pi.0^2)\n var1.k.p <- ifelse(var1.k.p < 0, 0, var1.k.p)\n var2.k.p <- ((k[j]*(1-k[j]))/(m*pi.0))*(1-2*Lam2) +\n (Lam2^2*(1-r[j])*r[j])/(m*pi.0^2)\n var2.k.p <- ifelse(var2.k.p < 0, 0, var2.k.p)\n cov.k.p <- (m^-1*pi.0^-2)*(pi.0*(k12[j]-k[j]*k[j])*(1-Lam1-Lam2) +\n (r12[j]-r[j]^2)*Lam1*Lam2)\n \n if(method == \"JZ ind\"){\n # assuming independence of k\n var.k.p <- var1.k.p + var2.k.p\n var.k.np <- var1.k.np + var2.k.np\n } else if(method == \"EmProc\") {\n var.k.p <- var1.k.p + var2.k.p - 2*cov.k.p\n var.k.np <- var1.k.np + var2.k.np - 2*cov.k.np\n }\n var.k.p <- ifelse(var.k.p < 0, 0, var.k.p)\n var.k.np <- ifelse(var.k.np < 0, 0, var.k.np)\n se.p[j] <- sqrt(var.k.p)\n se.np[j] <- sqrt(var.k.np)\n \n # Use pooled variance for tests, and unpooled for CIs\n CI.int[j, ] <- c( (k1[j]-k2[j]) - quant*se.np[j],\n (k1[j]-k2[j]) + quant*se.np[j])\n zscore <- ( (k1[j]-k2[j]) )/ifelse(pool, se.p[j], se.np[j])\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method %in% c(\"binomial ind\", \"binomial\")) {\n for(j in seq_along(k1.c)) {\n \n # unpooled variances\n var1.k.np <- (m.c*pi.0.c)^-1*(k1.c[j])*(1-k1.c[j])\n var2.k.np <- (m.c*pi.0.c)^-1*(k2.c[j])*(1-k2.c[j])\n cov.k.np <- (m.c*pi.0.c)^-1*(k12.c[j] - k1.c[j]*k2.c[j])\n \n # pooled variances\n var1.k.p <- (m*pi.0)^-1*(k[j])*(1-k[j])\n var2.k.p <- (m*pi.0)^-1*(k[j])*(1-k[j])\n cov.k.p <- (m*pi.0)^-1*(k12[j] - k[j]*k[j])\n \n if(method == \"binomial\") {\n var.k.p <- var1.k.p + var2.k.p - 2*cov.k.p\n var.k.np <- var1.k.np + var2.k.np - 2*cov.k.np\n } else if(method == \"binomial ind\") {\n var.k.p <- var1.k.p + var2.k.p\n var.k.np <- var1.k.np + var2.k.np\n }\n var.k.p <- ifelse(var.k.p < 0, 0, var.k.p)\n var.k.np <- ifelse(var.k.np < 0, 0, var.k.np)\n se.p[j] <- sqrt(var.k.p)\n se.np[j] <- sqrt(var.k.np)\n CI.int[j, ] <- c( (k1[j]-k2[j]) - quant*se.np[j],\n (k1[j]-k2[j]) + quant*se.np[j])\n \n # For CorrBinom, unpooled is always used\n zscore <- ( (k1[j]-k2[j]) )/se.np[j]\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n } \n } else if(method == \"mcnemar\") {\n for(j in seq_along(k1.c)) {\n BminusC <- hits1[j] - hits2[j]\n BplusC <- hits1[j] + hits2[j] - 2*hits12[j]\n BminusC.c <- hits1.c[j] - hits2.c[j]\n BplusC.c <- hits1.c[j] + hits2.c[j] - 2*hits12[j]\n zscore <- ifelse(BplusC>0, BminusC/sqrt(BplusC), 0)\n p.val[j] <- 2*pnorm(-abs(zscore))\n se.np[j] <- sqrt(BplusC.c - BminusC.c^2/nact.c) / nact.c\n # Using corrected difference for center point since this is the true BP corrected McNemar \n CI.int[j,] <- c( BminusC.c/nact.c - quant*se.np[j], BminusC.c/nact.c + quant*se.np[j])\n }\n }\n # difference estimates\n est <- (k1 - k2)\n } else if(metric == \"prec\") {\n \n # TODO still need to implement pooled and unpooled variances here\n if(method %in% c(\"JZ ind\", \"EmProc\")) {\n for(j in seq_along(pi1.c)) {\n Lam1 <- Lam1.vec[j]\n var1.pi <- (pi1.c[j]*(1-pi1.c[j]))/(m*r[j]) + (1-r[j])*(pi1.c[j]-Lam1)^2/(m*r[j])\n var1.pi <- ifelse(var1.pi < 0, 0, var1.pi)\n Lam2 <- Lam2.vec[j]\n var2.pi <- (pi2.c[j]*(1-pi2.c[j]))/(m*r[j]) + (1-r[j])*(pi2.c[j]-Lam2)^2/(m*r[j])\n var2.pi <- ifelse(var2.pi < 0, 0, var2.pi)\n cov.pi <- ((m^-1*r[j]^-2))*(r12[j]*pi12.c[j]*(1 - pi12.c[j]) + \n (pi12.c[j]-Lam1)*(pi12.c[j]-Lam2)*(r12[j] - r[j]^2))\n \n if(method == \"JZ ind\") {\n var.pi <- var1.pi + var2.pi\n } else if(method == \"EmProc\") {\n var.pi <- var1.pi + var2.pi - 2*cov.pi\n }\n \n # Check to see if var.k is negative due to machine precision problem\n var.pi <- ifelse(var.pi < 0, 0, var.pi)\n se <- sqrt(var.pi)\n CI.int[j, ] <- cbind((pi1[j] - pi2[j]) - quant*se, (pi1[j] - pi2[j]) + quant*se)\n zscore <- (pi1[j] - pi2[j])/se\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method %in% c(\"binomial ind\", \"binomial\")) {\n for(j in seq_along(k1.c)) {\n var1.pi <- (pi.c[j]*(1-pi.c[j]))/(m*r[j])\n var2.pi <- (pi.c[j]*(1-pi.c[j]))/(m*r[j])\n cov.pi <- (r12[j]/(m*r[j]^2))*(pi12.c[j]*(1 - pi12.c[j]))\n \n if(method == \"binomial\") {\n var.pi <- var1.pi + var1.pi - 2*cov.pi\n } else if(method == \"binomial ind\") {\n var.pi <- var1.pi + var1.pi\n }\n \n # Check to see if var.k is negative due to machine precision problem\n var.pi <- ifelse(var.pi < 0, 0, var.pi)\n se <- sqrt(var.pi)\n CI.int[j, ] <- cbind((pi1.c[j] - pi2.c[j]) - quant*se, (pi1.c[j] - pi2.c[j]) + quant*se)\n zscore <- (pi1.c[j] - pi2.c[j])/se\n p.val[j] <- 2*pnorm(-abs(zscore))\n p.val[j] <- ifelse(is.na(p.val[j]), 1, p.val[j])\n }\n } else if(method == \"stouffer\") {\n # TODO check that stouffer implemented correctly after changes\n for(j in seq_along(pi1.c)) {\n Sorder1 <- order(S1,decreasing=TRUE)\n Sorder2 <- order(S2,decreasing=TRUE)\n overlap.idx <- Sorder1[which(Sorder1[1:idx[j]] %in% Sorder2[1:idx[j]])]\n S1.unique.idx <- Sorder1[which(!Sorder1[1:idx[j]] %in% Sorder2[1:idx[j]])]\n S2.unique.idx <- Sorder2[which(!Sorder2[1:idx[j]] %in% Sorder1[1:idx[j]])]\n n12 <- length(overlap.idx)\n a <- sum(X[overlap.idx])\n d <- n12 - a\n n1 <- m*r[j] - n12 \n e <- sum(X[S1.unique.idx])\n g <- sum(X[S2.unique.idx])\n p.1 <- e/n1\n p.2 <- g/n1\n p.bar <- (e + g)/(2*n1)\n if(correction == \"plus\") {\n n1 <- n1 + 4\n e <- e + 2\n g <- g + 2\n }\n z1 <- (p.1 - p.2)/sqrt((2*p.bar*(1-p.bar))/n1)\n z1 <- ifelse(is.na(z1), 0, z1)\n z3 <- 0\n w <- (n1 + n1)/(2*n12 + n1 + n1)\n z5 <- (w*z1 + (1-w)*z3)/(sqrt(w^2 + (1-w)^2))\n p.val[j] <- 2*(1 - pnorm(abs(z5)))\n }\n }\n # difference estimates\n est <- pi1 - pi2\n }\n list(diff_estimate = est, std_err = se.np, ci_interval = CI.int, p_value = p.val)\n}", "meta": {"hexsha": "e6ff5d7660635558024acc0f8e06351536eda390", "size": 11990, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation_files/hypothesis_test.r", "max_stars_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_stars_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation_files/hypothesis_test.r", "max_issues_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_issues_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_files/hypothesis_test.r", "max_forks_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_forks_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3067092652, "max_line_length": 99, "alphanum_fraction": 0.5056713928, "num_tokens": 4330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.49091517783910776}} {"text": "######################################## FUNCOES UTILITARIAS #######################################\n\n#' Gera Grade \\code{dhl} x \\code{dpot} No Dominio Da Curva Colina\n#' \n#' Funcao auxiliar para gerar grades de pontos nos quais interpolar a curva colina\n#' \n#' Os argumentos \\code{dhl} e \\code{dpot} especificam a grade de maneira mais simples: se forem \n#' inteiros, as coordenadas de queda e potencia da grade sao geradas segmentando a faixa de quedas\n#' e potencias contidas na colina em \\code{dhl} e \\code{dpot} respectivamente. Caso sejam vetores,\n#' a grade sera construida com as posicoes contidas nestes vetores. Veja os Exemplos.\n#' \n#' \\code{byhl} e \\code{bypot} permitem uma especificacao mais detalhada. Estes argumentos sao \n#' interpretados como o intervalo de separacao entre cada divisao de queda e potencia na grade. Para\n#' manter a consistencia, a faixa de quedas e potencias usada nessa construcao nao sao exatamente \n#' aquelas contidas na colina, como quando gerando grades a partir de \\code{dhl} e \\code{dpot} (pois\n#' muito provavelmente uma sequencia comecando em min(hl) andando de byhl em byhl nao terminaria em\n#' max(hl)). Os minimos e maximos das faixas serao obtidos segundo as regras:\n#' \n#' \\itemize{\n#' \\item{minimo: o maior multiplo de \\code{byX} menor que min(X)}\n#' \\item{maximo: o menor multiplo de \\code{byX} maior que max(X)}\n#' }\n#' \n#' Se estes dois argumentos forem passados, \\code{dhl} e \\code{dpot} sao automaticamente ignorados.\n#' \n#' \\code{expande} permite montar grades que vao alem dos minimos e maximos de queda e potencia \n#' observados na curva colina. Deve ser informado como um vetor de duas posicoes indicando \n#' percentuais em formato decimal (5% = 0.05), sendo a primeira posicao para queda e a segunda para\n#' potencia. Para um dado valor em \\code{expande}, a faixa de quedas ou potencias sera expandida\n#' segundo\n#' \n#' \\eqn{faixa_hl = range(hl) + c(-range(hl) * expande[1], -range(hl) * expande[1])}\n#' \n#' O calculo para potencia e analogo. Esta expansao de faixa se aplica tanto no caso em que \n#' \\code{dhl} e \\code{dpot} sao passados quanto \\code{byhl} e \\code{bypot}. Adicionalmente, se\n#' \\code{dhl} e \\code{dpot} forem fornecidos como vetores, \\code{expande} sera ignorado.\n#' \n#' @param colina objeto da classe \\code{curvacolina} (retornado pelas funcoes de leitura)\n#' @param dhl,dpot numero de divisoes no eixo de queda liquida e potencia, respectivamente. Tambem\n#' podem ser fornecidos vetores indicando as posicoes das divisoes de queda e potencia\n#' @param byhl,bypot intervalo entre divisoes de queda e potencia, respectivamente; se forncecido\n#' \\code{dhl} e \\code{dpot} serao ignorados. Ver Detalhes\n#' @param expande vetor de duas posicoes indicando percentual de expansao do dominio. Ver Detalhes\n#' \n#' @examples\n#' \n#' # grade contemplando toda a faixa de quedas e potencias da colina, cada uma divida em 20 partes\n#' grade1 <- coordgrade(colinadummy, 20, 20)\n#' \n#' # grade com coordenadas especificadas diretamente\n#' grade2 <- coordgrade(colinadummy, 40:60, seq(150, 400, by = 10))\n#' \n#' # grade com intervalos de 1 cm em queda e 10 MW em potencia\n#' # grade3 <- coordgrade(colinadummy, byhl = .1, bypot = 10)\n#' \n#' \\dontrun{\n#' plot(colinadummy, \"2d\") + ggplot2::geom_point(data = grade, aes(hl, pot), col = 2)\n#' }\n#' \n#' @return data.frame contendo coordenadas dos pontos na grade\n#' \n#' @family curvacolina\n#' \n#' @import data.table\n#' \n#' @export\n\ncoordgrade <- function(colina, dhl, dpot, byhl, bypot, expande) UseMethod(\"coordgrade\", colina)\n\n#' @export\n\ncoordgrade.data.table <- function(colina, dhl, dpot, byhl, bypot, expande = c(0, 0)) {\n\n hl <- pot <- NULL\n\n xhl <- expande[1] * diff(range(colina$hl))\n xhl <- range(colina$hl) + c(-1, 1) * xhl\n\n xpot <- expande[2] * diff(range(colina$pot))\n xpot <- range(colina$pot) + c(-1, 1) * xpot\n\n if(!missing(byhl)) {\n if(!missing(dhl)) warning(\"Tanto 'dhl' quanto 'byhl' foram fornecidos -- ignorando 'dhl'\")\n\n minhl <- floor(xhl[1] / byhl) * byhl\n maxhl <- ceiling(xhl[2] / byhl) * byhl\n dhl <- seq(minhl, maxhl, by = byhl)\n }\n\n if(!missing(bypot)) {\n if(!missing(dpot)) warning(\"Tanto 'dpot' quanto 'bypot' foram fornecidos -- ignorando 'dpot'\")\n\n minpot <- floor(xpot[1] / bypot) * bypot\n maxpot <- ceiling(xpot[2] / bypot) * bypot\n dpot <- seq(minpot, maxpot, by = bypot)\n }\n\n dhlvetor <- length(dhl) > 1L\n dpotvetor <- length(dpot) > 1L\n\n if(dhlvetor) hl <- dhl else hl <- seq(xhl[1], xhl[2], length.out = dhl)\n if(dpotvetor) pot <- dpot else pot <- seq(xpot[1], xpot[2], length.out = dpot)\n\n grade <- expand.grid(hl = hl, pot = pot)\n\n grade <- as.data.table(grade)\n\n return(grade)\n}\n\n#' @export\n\ncoordgrade.data.frame <- function(colina, dhl, dpot, byhl, bypot, expande = c(0, 0)) {\n\n grade <- coordgrade.data.table(as.data.table(colina), dhl, dpot, byhl, bypot, expande)\n\n return(grade)\n}\n\n#' @export\n\ncoordgrade.curvacolina <- function(colina, dhl, dpot, byhl, bypot, expande = c(0, 0)) {\n\n grade <- coordgrade(colina$CC, dhl, dpot, byhl, bypot, expande)\n\n return(grade)\n}\n\n# --------------------------------------------------------------------------------------------------\n\n#' Generica Para Extrair Colina Original do Ajuste\n#' \n#' Extrai o dado ajustado corretamente dependendo do tipo de modelo. Funcao interna\n#' \n#' @param object objeto do qual extrair \\code{data.table} da curva colina. Pode ser um modelo \n#' interpolador ou objeto da classe \\code{curvacolina}\n#' \n#' @return \\code{data.table} contendo a curva colina em formato padronizado\n\ngetcolina <- function(object) UseMethod(\"getcolina\")\n\n# --------------------------------------------------------------------------------------------------\n\n#' Ordem Dos Vertices De Poligono\n#' \n#' Centraliza \\code{dat} por referencia e retorna vetor de indices dos vertices em ordem adjacente\n#' \n#' A determinacao de ordem dos vertices e feita com base no angulo entre cada um e o centro do\n#' poligono. Este centro pode ser infromado por meio dos argumentos \\code{centro_hl} e \n#' \\code{centro_pot} ou, caso estes fiquem vazios, sera calculado como a media amostral.\n#' \n#' @param dat \\code{data.table} contendo vertices de um poligono cuja ordem sera determinada\n#' @param centro_hl opcional, valor para centralizar \\code{dat$hl}. Caso vazio usa a media \n#' @param centro_pot opcional, valor para centralizar \\code{dat$pot}. Caso vazio usa a media \n#' \n#' @return vetor de inteiros indicando os indices dos vertices na ordenacao por angulo\n\norderpoly <- function(dat, centro_hl, centro_pot) {\n\n ang <- pot <- hl <- NULL\n\n if(missing(centro_hl)) centro_hl <- mean(dat$hl)\n if(missing(centro_pot)) centro_pot <- mean(dat$pot)\n\n dat$hl <- dat$hl - centro_hl\n dat$pot <- dat$pot - centro_pot\n dat[, ang := atan2(pot, hl)]\n\n angord <- order(dat$ang)\n\n return(angord)\n}\n", "meta": {"hexsha": "a783d2c3a743af67072e0a6bbd7560a1c622f960", "size": 6924, "ext": "r", "lang": "R", "max_stars_repo_path": "R/utils.r", "max_stars_repo_name": "lkhenayfis/gtdp-curvacolina", "max_stars_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/utils.r", "max_issues_repo_name": "lkhenayfis/gtdp-curvacolina", "max_issues_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-29T15:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T16:13:23.000Z", "max_forks_repo_path": "R/utils.r", "max_forks_repo_name": "lkhenayfis/gtdp-curvacolina", "max_forks_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0231213873, "max_line_length": 102, "alphanum_fraction": 0.6645002889, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.49091516574302124}} {"text": "# !#/bin/R\n# Program: Calculates LIML regression with applied Bekker variances following NEWEY 2006.\n# Author: Nicholas Potter\n# Date: 11/15/2011\n#\n# UPDATED:\n#\t20120511 - NAP: Correctly calculates bekker adjustment, clean up and finalize\n#\n# Using MROZ data set should give the following results:\n# Var\tCoef\t \tStd Err\t\tBekker\n# hours\t.00178946 \t.00114792\t.00203246\n# exper\t-.092979\t.145624\t\t.254861\n###########\nlibrary(\"foreign\")\nlibrary(\"corpcor\")\nlibrary(\"Matrix\")\nmodel_type = \"liml\"\n\ndata_raw = read.dta(\"~/data/stata/mroz.dta\")\ndata_complete = data_raw[complete.cases(data_raw),]\ndata = subset(data_complete, age < 32)\nN = nrow(data)\n\n#Dependent variable (lhs)\ny = matrix(cbind(data$lwage))\n#Instrumented (endogenous variables)\nX1 = matrix(cbind(data$hours))\n#Instruments (Z1: excluded exogenous variables)\nZ1 = as.matrix(cbind(data$educ, data$kidslt6, data$kidsge6, data$age, data$nwifeinc))\n#Exogenous (X2 = Z2: included exogenous variables)\n#X2 = matrix(cbind(1,data$exper),N,2)\nX2 = matrix(cbind(data$exper))\nZ2 = X2\n\n# Define our dimensions\nG1 = ncol(X1)\nG2 = ncol(X2)\nG = G1 + G2\nK1 = ncol(Z1)\nK2 = ncol(Z2)\nK = K1 + K2\n\n# Weight vector\n# weights = matrix(data$f_wt_totsvy)\nweights = matrix(rep(1,N))\nwt = diag(N)\nwt = as.matrix(diag(N))\n\n# create unit matrix\nI = diag(N)\n\nA = matrix(c(y,X1,X2,Z1),N,K+G1+1)\nY = matrix(c(y,X1,X2),N,1+G)\nX = matrix(c(X1,X2),N,G)\nZ = matrix(c(Z1,Z2),N,K)\n\ndf.total = N\ndf.ess = ncol(Y)-1\ndf.rss = df.total - df.ess\n\nAA = t(A) %*% wt %*% A\nM = nrow(AA)\n\n# Now define the commonly used matrices.\nYY\t\t= t(Y) %*% Y \nYYinv\t= pseudoinverse(YY)\nZZ \t\t= t(Z) %*% Z\nZZinv\t= pseudoinverse(ZZ) \nXX\t\t= t(X) %*% X\nXXinv\t= pseudoinverse(XX)\nXZ\t\t= t(X) %*% Z\nPZ\t\t= pseudoinverse(Z %*% t(Z)) %*% (Z %*% t(Z))\nMZ\t\t= I-PZ\nYPZY \t= t(Y) %*% PZ %*% Y\nXPZX\t= t(X) %*% PZ %*% X\n\n# get lambda/alpha\nHH\t\t= YYinv %*% YPZY\neigenvalues = eigen(HH)\nalpha = min(Re(eigenvalues$val))\n\n# Betas\nX.beta = pseudoinverse(XPZX- alpha*XX) %*% (XPZy - alpha*Xy)\nZ.beta = ZZinv %*% t(XZ)\n\ne = y - X %*% X.beta\nrss = t(e) %*% wt %*% e\nrss.ms = rss/df.rss\nrss.es = rss - rss.ms\nrss.V = rss/(N-df.ess)\ns2 = rss/(N-df.ess)\n\nif (model_type==\"liml\") {\n\tX.var = s2[1,1] * XMZXinv\n} else if (model_type==\"tsls\") {\n\tX.var = s2[1,1] * XPZXinv\n}\nZ.var = sigma2[1,1] * ZZinv\nZ.se = sqrt(Z.var)\nX.se = sqrt(X.var)\n\nKn = sum(diag(PZ)**2)/K\nTn = K/N\ns2 = rss/(N-G)\nS2 = matrix(c(s2),N,1)\nH = XPZX - alpha[1] * XX\nHinv = pseudoinverse(H)\nHA = sum(diag(PZ)-Tn) * t(PZX) %*% (rss[1] * MZXbar/N)\nHB = K * (Kn[1] - Tn) * sum(e*e-S2) * t(MZXbar) %*% MZXbar / (N*(1 - 2*Tn + Kn[1]*Tn))\nSigmaB = s2[1] * (((1 - alpha[1])**2)*t(Xbar)%*%PZXbar + a2[1]*t(Xbar)%*%MZXbar) \n# according to Newey, should also add HB but it only matches TSP if HB is not included \nSigma3 = SigmaB + HA + t(HA) + HB\nSigma2 = SigmaB + HA + t(HA)\n\nX.varnewey = Hinv %*% Sigma2 %*% Hinv\nX.senewey = sqrt(X.varnewey)\n\n\n\nxxx\n\n\nXy = as.matrix(AA[2:(K+1),1])\nXX = as.matrix(AA[2:(K+1), 2:(K+1)])\nif (K1 > 0) {\n X1X1 = as.matrix(AA[2:(K1+1), 2:(K1+1)])\n }\nif (L1 > 0) {\n Z1Z1 = as.matrix(AA[(K+2):M,(K+2):M])\n }\nif (L2 > 0) {\n Z2Z2 = as.matrix(AA[(K1+2):(K+1), (K1+2):(K+1)])\n X2y = as.matrix(AA[(K1+2):(K+1), 1])\n }\n\n# Get ZZ\nif ((L1 > 0) && (L2 > 0)) {\n Z2Z1 = as.matrix(AA[(K1+2):(K+1),(K+2):M])\n ZZ2 = matrix(c(Z2Z1, Z2Z2),L,L2)\n ZZ1 = matrix(c(Z1Z1, Z2Z1),L1,L)\n\tZZ = matrix(rbind(ZZ1, t(ZZ2)),L,L)\n} else if (L1>0) {\n\tZZ = Z1Z1\n} else {\n\tZZ = Z2Z2\n}\n\nif (K1>0) {\n\tX1Z1 = as.matrix(AA[(2:(K1+1)), ((K+2):M)])\n\t}\n\nif ((K1>0) && (L2>0)) {\n\tX1Z2 = as.matrix(AA[2:(K1+1), (K1+2):(K+1)])\n\tX1Z = matrix(c(X1Z1, X1Z2),1,L)\n\tXZ = matrix(rbind(X1Z, t(ZZ2)),2,L)\n} else if (K1>0) { \n\tXZ = X1Z1\n\tX1Z= X1Z1\n} else if (L1>0) {\n\tXZ = matrix(AA[2:(K+1),(K+2):M], AA[(2:K+1),(2:(K+1))])\n} else {\n\tXZ = ZZ\n}\n\nif ((L1>0) & (L2>0)) {\n\tZy = matrix(c(AA[(K+2):M, 1],AA[(K1+2):(K+1)]),L,1)\n\tZY = matrix(rbind(AA[(K+2):M, 1:(K1+1)], AA[(K1+2):(K+1), 1:(K1+1)]), L, L2+1)\n\tZ2Y = matrix(c(AA[(K1+2):(K+1), 1:(K1+1)]),L2,K1+1)\n} else if (L1>0) {\n\tZy = AA[(K+2):M, 1]\n\tZY = AA[(K+2):M, 1:(K1+1)]\n} else {\n\tZy = AA[(K1+2):(K+1), 1]\n\tZY = AA[(K1+2):(K+1), 1:(K1+1)]\n\tZ2Y = ZY\n}\n\nYY = AA[1:(K1+1), 1:(K1+1)]\nyy = AA[1,1]\nym = sum(wt %*% y)/N\nyyc = t(y %*% t(ym)) %*% wt %*% y %*% ym\n\nYYinv\t= pseudoinverse(YY)\nXXinv = pseudoinverse(XX)\nZZinv = pseudoinverse(ZZ)\nPZ = Z %*% ZZinv %*% t(Z)\nMZ = I-PZ\nXPZX = XZ %*% ZZinv %*% t(XZ)\nXPZy\t= t(X) %*% PZ %*% y\nXPZXinv = pseudoinverse(XPZX)\nYPZY\t= t(Y) %*% PZ %*% Y\n\nif (ncol(X)==ncol(Z)) {\n\tif (X==Z) {\n\t\tZZinv = XXinv\n\t\tXPZXinv = XXinv\n\t} else {\n\t\tZZinv = pseudoinverse(ZZ)\n\t\tXPZX = XZ %*% ZZinv %*% t(XZ)\n\t\tXPZXinv=pseudoinverse(XPZX)\n\t}\n}\n\nQZZ = ZZ/N\nQXX = XX/N\nQXZ = XZ/N\nQZy = Zy/N\nQZ2Z2 = Z2Z2/N\nQYY = YY/N\nQZY = ZY/N\nQZ2Y = Z2Y/N\nQXy = Xy/N\nQXPZX = XPZX/N\nQZZinv = ZZinv*N\n\n\nQWW = QYY - t(QZY) %*% QZZinv %*% QZY\nWW = (YY - t(ZY) %*% ZZinv %*% ZY)\nOmega = WW/(N-K-L)\n\nif (K2>0) {\n\tZ2Z2inv = pseudoinverse(Z2Z2)\n\tQZ2Z2inv = pseudoinverse(QZ2Z2)\n\tQWW1 = QYY - t(QZ2Y) %*% QZ2Z2inv %*% QZ2Y\n\tYPY = YY - (t(Z2Y) %*% Z2Z2inv %*% Z2Y) - WW\n} else {\n\tQWW1 = QYY\n\tYPY = YY - WW\n}\n# equivalent to YMY/N in kolesar\nQWWsym = as.matrix(forceSymmetric(QWW))\n# equivalent to YY/N in kolesar\nQWW1sym = as.matrix(forceSymmetric(QWW1))\n\nQWWsqrt = mpower(QWWsym, -0.5)\nAA2 = QWWsqrt %*% QWW1 %*% QWWsqrt\n\neigenvalues = eigen(AA2, only.values=TRUE)\nlambda = min(Re(eigenvalues$val))\n\n# for now just set C = 2\nC = 2\n# set model_type\nmodel_type = \"liml\"\nif (model_type==\"fuller\") {\n\tkclass = (lambda-lambda*C/N)/(1-lambda*C/N)\n} else if (model_type==\"liml\") {\n\tkclass = lambda\n} else if (model_type==\"tsls\") {\n\tkclass = 0\n}\n\nXMZX = t(X) %*% (I-kclass*MZ) %*% X \nXMZXinv = pseudoinverse(XMZX)\n\n\n\nQXhXh = (1-kclass) * QXX + kclass * QXPZX\nQXhXhinv = pseudoinverse(QXhXh)\n#newey :: 1/(1-kclass2) = kclass from ivreg2\nY2 = matrix(c(y,X),N,K+1)\nY2Y2 = t(Y2) %*% Y2\nY2Y2inv = pseudoinverse(Y2Y2)\nY2PZY2 = t(Y2) %*% PZ %*% Y2\nAAA = Y2Y2inv %*% Y2PZY2\neigenvalues2 = eigen(AAA)\nkclass2 = min(Re(eigenvalues2$val))\nX.beta2 = pseudoinverse(XPZX- kclass2*XX) %*% (XPZy - kclass2*Xy)\nX.beta1 = t(t(X) %*% (I-kclass*MZ) %*% y) %*% XMZXinv\nX.beta = t(QXy) %*% QXhXhinv * (1-kclass) + kclass * t(QZy) %*% QZZinv %*% t(QXZ) %*% QXhXhinv\nZ.beta = ZZinv %*% t(XZ)\ne = y - X %*% t(X.beta)\nrss = t(e) %*% wt %*% e\nrss.ms = rss/df.rss\nrss.es = rss - rss.ms\nrss.V = rss/(N-df.ess)\ns2 = rss/(N-df.ess)\n\n# LIML Variance\nX.varliml = s2[1,1] * XMZXinv\n# TSLS Variance\nX.vartsls = s2[1,1] * XPZXinv\n\nZ.var = sigma2[1,1] * ZZinv\nX.seliml = sqrt(X.varliml)\nX.setsls = sqrt(X.vartsls)\n\n# Bekker coefficients\nak = K/N\nal = L/N\nh1 = ak/(1-ak)\nh2 = ak*(1-al)/(1-ak-al)\n\n# WORKS TO THIS POINT\nPZ2 = t(Z1) %*% pseudoinverse(Z1 %*% t(Z1)) %*% Z1\nPW = t(Z2) %*% pseudoinverse(Z2 %*% t(Z2)) %*% Z2\n\n#QWW = t(Y) %*% (I - PZ - PW) %*% Y\n\nGamma = matrix(c(1, -X.beta[1,1], 0, 1), 2,2)\nSigma = t(Gamma) %*% Omega %*% Gamma\nLambda = t(Gamma) %*% (YPY/N-ak*Omega) %*% Gamma\nX.varbekker = Sigma[1,1] / Lambda[2,2] + h2 * det(Sigma)/(Lambda[2,2]**2)\nX.sebekker = sqrt(X.varbekker)\n\n# equivalent to e above\nu = y - X %*% X.beta2\n# this alpha is equivalent to kclass2 above\nalpha = t(e) %*% PZ %*% e / rss[1]\na2 = alpha * alpha\nPZX = PZ %*% X\nXbar = X - e %*% (t(e) %*% X) / rss[1]\nPZXbar = PZ %*% Xbar\nMZXbar = (I-PZ) %*% Xbar\n\nG = K\nK = 6\n\n\nX.varnewey3 = Hinv %*% Sigma3 %*% Hinv\nX.senewey3 = sqrt(X.varnewey3)\n\n", "meta": {"hexsha": "11b9f53a62303ce090b16858e881d52eb22e445d", "size": 7375, "ext": "r", "lang": "R", "max_stars_repo_path": "R/newey.r", "max_stars_repo_name": "potterzot/napr", "max_stars_repo_head_hexsha": "b0997891687b05118d46783e82fc8ee43f682b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/newey.r", "max_issues_repo_name": "potterzot/napr", "max_issues_repo_head_hexsha": "b0997891687b05118d46783e82fc8ee43f682b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/newey.r", "max_forks_repo_name": "potterzot/napr", "max_forks_repo_head_hexsha": "b0997891687b05118d46783e82fc8ee43f682b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8328173375, "max_line_length": 94, "alphanum_fraction": 0.5787118644, "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.490735791705475}} {"text": " ZPBEQU Example Program Results\n\n Matrix A\n 1 2 3\n 1 ( 9.39E+00, 0.00E+00) ( 1.08E+00, -1.73E+00)\n 2 ( 1.69E+00, 0.00E+00) ( -4.00E+08, 2.90E+09)\n 3 ( 2.64E+20, 0.00E+00)\n 4\n \n 4\n 1\n 2\n 3 ( -3.30E+09, 2.24E+10)\n 4 ( 2.17E+00, 0.00E+00)\n\n SCOND = 8.0E-11, AMAX = 2.6E+20\n\n Diagonal scaling factors\n 3.3E-01 7.7E-01 6.2E-11 6.8E-01\n\n Scaled matrix\n 1 2 3 4\n 1 ( 1.0000, 0.0000) ( 0.2711,-0.4343)\n 2 ( 1.0000, 0.0000) (-0.0189, 0.1373)\n 3 ( 1.0000, 0.0000) (-0.1379, 0.9359)\n 4 ( 1.0000, 0.0000)\n", "meta": {"hexsha": "08aa61a3dc88e716035aa4a9397993085a636286", "size": 867, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/zpbequ_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/zpbequ_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/zpbequ_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 32.1111111111, "max_line_length": 75, "alphanum_fraction": 0.324106113, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.4905128325641923}} {"text": "#' Binary item tracelines.\n#'\n#' @param p_item Vector of item parameters.\n#' @param theta Vector of theta values.\n#' @param pred_data Matrix or dataframe of DIF and/or impact predictors.\n#' @param samp_size Sample size in dataset.\n#'\n#' @return a \\code{\"matrix\"} of probability values for Bernoulli item likelihood\n#'\n#' @keywords internal\n#'\nbernoulli_traceline_pts <-\n function(p_item,\n theta,\n pred_data,\n samp_size) {\n\n traceline <-\n vapply(theta,\n function(x) {\n 1 / (1 + exp(\n -((p_item[1] + pred_data %*% p_item[3:(2+ncol(pred_data))]) +\n (p_item[2] + pred_data %*% p_item[(3+ncol(pred_data)):length(p_item)])*x)\n ))\n }, numeric(samp_size))\n\n return(traceline)\n\n }\n\n#' Binary item tracelines for proxy scores.\n#'\n#' @param p_item Vector of item parameters.\n#' @param prox_data Vector of observed proxy scores.\n#' @param pred_data Matrix or dataframe of DIF and/or impact predictors.\n#'\n#' @return a \\code{\"matrix\"} of probability values for Bernoulli item likelihood using observed\n#' proxy scores\n#'\n#' @keywords internal\n#'\nbernoulli_traceline_pts_proxy <-\n function(p_item,\n prox_data,\n pred_data) {\n\n traceline <-\n 1 / (1 + exp(\n -((p_item[1] + pred_data %*% p_item[3:(2+ncol(pred_data))]) +\n (p_item[2] + pred_data %*% p_item[(3+ncol(pred_data)):length(p_item)])*prox_data)))\n\n return(traceline)\n\n }\n\n#' Ordinal tracelines.\n#'\n#' @param p_item Vector of item parameters.\n#' @param theta Vector of theta values.\n#' @param pred_data Matrix or dataframe of DIF and/or impact predictors.\n#' @param samp_size Sample size in dataset.\n#' @param num_responses_item Number of responses for item.\n#' @param num_quad Number of quadrature points used for approximating the\n#' latent variable.\n#'\n#' @return a \\code{\"matrix\"} of probability values for categorical (cumulative) item likelihood\n#'\n#' @keywords internal\n#'\ncumulative_traceline_pts <-\n function(p_item,\n theta,\n pred_data,\n samp_size,\n num_responses_item,\n num_quad) {\n\n # Space for cumulative traceline (y >= c category).\n traceline <-\n lapply(1:(num_responses_item-1), function(x) {\n matrix(0,nrow=samp_size,ncol=num_quad)})\n\n c0_parms <- grepl(\"c0\",names(p_item),fixed=T)\n c1_parms <- grepl(\"c1\",names(p_item),fixed=T)\n a0_parms <- grepl(\"a0\",names(p_item),fixed=T)\n a1_parms <- grepl(\"a1\",names(p_item),fixed=T)\n\n # For item response 1.\n traceline[[1]] <-\n vapply(theta,\n function(x) {\n 1 / (1 + exp(-((p_item[c0_parms][1] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*x)\n )\n )\n }, numeric(samp_size))\n\n # For item response 2 to J.\n for(thr in 2:(num_responses_item-1)) {\n traceline[[thr]] <-\n vapply(theta,\n function(x) {\n 1 / (1 + exp(-((p_item[c0_parms][1] -\n p_item[c0_parms][thr] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*x)\n )\n )\n }, numeric(samp_size))\n }\n\n return(traceline)\n\n}\n\n#' Ordinal tracelines using proxy data.\n#'\n#' @param p_item Vector of item parameters.\n#' @param prox_data Vector of observed proxy scores.\n#' @param pred_data Matrix or dataframe of DIF and/or impact predictors.\n#' @param samp_size Sample size in dataset.\n#' @param num_responses_item Number of responses for item.\n#'\n#' @return a \\code{\"matrix\"} of probability values for categorical (cumulative) item likelihood\n#'\n#' @keywords internal\n#'\ncumulative_traceline_pts_proxy <-\n function(p_item,\n prox_data,\n pred_data,\n samp_size,\n num_responses_item) {\n\n # Space for cumulative traceline (y >= c category).\n traceline <- lapply(1:(num_responses_item-1), function(x) {\n matrix(0,nrow=samp_size,ncol=1)})\n\n c0_parms <- grepl(\"c0\",names(p_item),fixed=T)\n c1_parms <- grepl(\"c1\",names(p_item),fixed=T)\n a0_parms <- grepl(\"a0\",names(p_item),fixed=T)\n a1_parms <- grepl(\"a1\",names(p_item),fixed=T)\n\n # For item response 1.\n traceline[[1]] <- 1 / (1 + exp(-((p_item[c0_parms][1] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*prox_data))\n )\n\n # For item response 2 to J.\n for(thr in 2:(num_responses_item-1)) {\n traceline[[thr]] <- 1 / (1 + exp(-((p_item[c0_parms][1] -\n p_item[c0_parms][thr] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*prox_data))\n )\n }\n\n return(traceline)\n\n }\n\n\n#' Continuous tracelines.\n#'\n#' @param p_item Vector of item parameters.\n#' @param theta Vector of theta values.\n#' @param responses_item Vector of item responses.\n#' @param pred_data Matrix or data frame of DIF and/or impact predictors.\n#' @param samp_size Sample size in data set.\n#'\n#' @return a \\code{\"matrix\"} of probability values for Gaussian item likelihood\n#'\n#' @keywords internal\n#'\ngaussian_traceline_pts <-\n function(p_item,\n theta,\n responses_item,\n pred_data,\n samp_size) {\n\n c0_parms <- grepl(\"c0\",names(p_item),fixed=T)\n c1_parms <- grepl(\"c1\",names(p_item),fixed=T)\n a0_parms <- grepl(\"a0\",names(p_item),fixed=T)\n a1_parms <- grepl(\"a1\",names(p_item),fixed=T)\n s0_parms <- grepl(\"s0\",names(p_item),fixed=T)\n s1_parms <- grepl(\"s1\",names(p_item),fixed=T)\n\n mu <-\n vapply(theta,\n function(x) {\n (p_item[c0_parms] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*x\n }, numeric(samp_size))\n sigma <-\n sqrt(p_item[s0_parms][1]*exp(pred_data %*% p_item[s1_parms]))\n\n traceline <- t(sapply(1:samp_size,\n function(x) {\n dnorm(responses_item[x],mu[x,],sigma[x])\n }\n ))\n\n return(traceline)\n\n}\n\n#' Continuous tracelines using proxy data.\n#'\n#' @param p_item Vector of item parameters.\n#' @param prox_data Vector of observed proxy scores.\n#' @param responses_item Vector of item responses.\n#' @param pred_data Matrix or data frame of DIF and/or impact predictors.\n#' @param samp_size Sample size in data set.\n#'\n#' @return a \\code{\"matrix\"} of probability values for Gaussian item likelihood\n#'\n#' @keywords internal\n#'\ngaussian_traceline_pts_proxy <-\n function(p_item,\n prox_data,\n responses_item,\n pred_data,\n samp_size) {\n\n c0_parms <- grepl(\"c0\",names(p_item),fixed=T)\n c1_parms <- grepl(\"c1\",names(p_item),fixed=T)\n a0_parms <- grepl(\"a0\",names(p_item),fixed=T)\n a1_parms <- grepl(\"a1\",names(p_item),fixed=T)\n s0_parms <- grepl(\"s0\",names(p_item),fixed=T)\n s1_parms <- grepl(\"s1\",names(p_item),fixed=T)\n\n mu <- (p_item[c0_parms] +\n pred_data %*% p_item[c1_parms]) +\n (p_item[a0_parms] +\n pred_data %*% p_item[a1_parms])*prox_data\n sigma <-\n sqrt(p_item[s0_parms][1]*exp(pred_data %*% p_item[s1_parms]))\n\n traceline <- t(sapply(1:samp_size,\n function(x) {\n dnorm(responses_item[x],mu[x,],sigma[x])\n }\n ))\n\n return(traceline)\n\n }\n\n", "meta": {"hexsha": "8811abd7d02d8e1dff428c4b6d2b93d221cbf974", "size": 7939, "ext": "r", "lang": "R", "max_stars_repo_path": "R/traceline.r", "max_stars_repo_name": "wbelzak/regDIF", "max_stars_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/traceline.r", "max_issues_repo_name": "wbelzak/regDIF", "max_issues_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/traceline.r", "max_forks_repo_name": "wbelzak/regDIF", "max_forks_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6525096525, "max_line_length": 95, "alphanum_fraction": 0.5694671873, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644731945312}} {"text": "simulate_joint_HMcontinuous <- function(n=100,k=2,sepxiv=1,type=c(\"norm\",\"bino\")){\n\t\n# Simulation of the from joint model with continuous HM chain described in\n# \"A shared-parameter continuous-time hidden Markov and survival model for longitudinal data\n# with informative drop-out\"\n# by F.Bartolucci and A.Farcomeni (2018)\n#\n# INPUT:\n#\n# n = sample size\n# k = number of latent states\n# sepxiv = separation between the latent state support points \n# type = type of response variables (\"norm\" or \"bino\")\n#\n# OUTPUT:\n#\n# Y = matrix of responses (each row corresponds to an individual)\n# Y0 = matrix of all responses (without dropout)\n# W = matrix of individual covariates for the survival process\n# X = array of individual covariates on the longitudinal process\n# tv = vector of survival times\n# censv = vector of indicators of censoring\n# Q = infinitesimal transition matrix\n# piv = initial probability vector\n# bev = regression coefficients on the longitudinal process\n# nu = parameter of the Weibull distribution\n# xiv = vector of support points\n# phi = relation between longitudal and survival process\n# psiv = vector of regression paraemters on the survival process\n# si2 = variane for normal responses\n# TT = time of each longitudinal observaton\n# TT0 = time of each longitudinal observaton (without dropout)\n# tU = matrix of latent states (continuous time)\n# tT = matrix of continuous time jumps\n# U = matrix of latent states (discrete time)\n# Q = infinite transition matrix\n# dev = indicator for non-censoring time\n\n\n# set up\n\ttype = match.arg(type)\n\tcv = rep(10,n) # censoring times (v stands for vector)\n\txiv = seq(1:k)*sepxiv # support points\n\txiv = xiv-mean(xiv) \n\tpiv = rep(1/k,k) # initial probabilty vector\n\tQ = matrix(1/(k-1),k,k) # infinitesimal transition matrix\n\tdiag(Q) = -1\n\tif(type == \"norm\")\tsi2 = 0.25 else si2 = NULL # variance of continuous data\n\tX = array(0,c(n,10+1,2)) # array of covariates (AR(1))\n\tfor(i in 1:n){\n\t\tX[i,1,] = rnorm(2)\n\t\tfor(t in 2:11) X[i,t,] = 0.9*X[i,t-1,]+rnorm(2)*sqrt(0.19)\n\t}\n\tbev = c(-1,1) # corresponding regression parameters \n\tphi = 0.75 # random-effect coefficient on survival process\n\tW = cbind(1,matrix(rnorm(2*n),n)) # covariates for survival process\n\tpsiv = c(-6,-1,1) # corresponding regression parameters\n\tnu = 2 # parameter of the Weibull distribution \n\n# simulate data\n\ttU = tT = tTau = matrix(NA,n,100) # for MC process (initial t stands fro tilde)\n\ttjv = rep(0,n) # number of jumps\n\tR = Q; diag(R) = 0 # jump matrix\n\tqtot = rowSums(R) # exponential sojourn rate\n\tR = R/qtot\n\n# draw continuous MC process\n\tfor(i in 1:n){\n\t\ttT[i,1] = 0\n\t\ttU[i,1] = which(rmultinom(1,1,piv)==1)\n\t\tj = 0\n\t\twhile(tT[i,j+1]<=cv[i]){\n\t\t\tj = j+1\n\t\t\ttTau[i,j] = rexp(1,qtot[tU[i,1]])\n\t\t\ttT[i,j+1] = tT[i,j]+tTau[i,j]\n\t\t\ttU[i,j+1] = which(rmultinom(1,1,R[tU[i,j],])==1)\n\t\t}\n\t\ttjv[i] = j\n\t}\n\n# draw survival time\n\tbv = tv = rep(0,n) # vector if random draws and surivavial times\n\tcensv = rep(FALSE,n) # vector with indicators of censoring\n\tfor(i in 1:n){\n\t\tHt = rep(0,tjv[i]) # cumulative hazard function\n\t\tind = 1:(tjv[i]-1)\n\t\tif(tjv[i]>1) Ht[2:tjv[i]] = exp(as.vector(W[i,]%*%psiv))*cumsum(exp(xiv[tU[i,ind]]*phi)*\n\t\t (tT[i,ind+1]^nu-tT[i,ind]^nu))\n\t\tbv[i] = -log(runif(1))\n\t\tdi = sum(Ht<=bv[i])\n\t\ttv[i] = (tT[i,di]^nu + (bv[i]-Ht[di])/(exp(xiv[tU[i,di]]*phi+W[i,]%*%psiv)))^(1/nu)\n\t\tif(tv[i]>cv[i]){\n\t\t\tcensv[i] = TRUE\n\t\t\ttv[i] = cv[i]\n\t\t}\n\t}\n\tdev = 1-censv # indicator for non-censoring time\n\n# draw longitudinal process\n\tjv = rep(0,n) # number of observations\n\tTT = TT0 = Y = Y0 = matrix(NA,n,11) # time of each observation and value\n\tU = matrix(NA,n,100) # matrix of latent state at each observation\n\tfor(i in 1:n){\n\t\tjv[i] = floor(tv[i])+1\n\t\tTT0[i,] = 0:10\n\t\tTT[i,1:jv[i]] = 0:(jv[i]-1)\n\t\tU[i,1] = tU[i,1]\n\t\ttmp = xiv[U[i,1]]+X[i,1,]%*%bev\n\t\tif(type==\"norm\") Y0[i,1] = tmp+rnorm(1)*sqrt(si2) # continuous case\n\t\tif(type==\"bino\"){ # binary case\n\t\t\ttmp = exp(tmp)/(1+exp(tmp)) \n\t\t\tY0[i,1] = 1*(runif(1)=10)\nID3<-subset(ID2,Entra!=\"No\")\nreturn (list(FALSE,ID3))\n}, error = function(ex) {\nprint(\"Error en la carga de datos de individuos\")\nreturn (TRUE)\n})\n}\n\nCargarParcelas<-function(x){\ntryCatch({\nPL1<-read.csv2(x,enc=\"latin1\")\nreturn (list(FALSE,PL1))\n}, error = function(ex) {\nprint(\"Error en la carga de datos de parcelas\")\nreturn (TRUE)\n})\n}\n\nCargarBosques<-function(b){\ntryCatch({\nBQ1<-read.csv2(b,enc=\"latin1\")\nreturn (list(FALSE,BQ1))\n}, error = function(ex) {\nprint(\"Error en la carga de datos de bosques\")\nreturn (TRUE)\n})\n}\n\nMerge<-function(ID3,PL1){\ntryCatch({\n\nreturn (list(FALSE,DT1))\n}, error = function(ex) {\nprint(\"Error realizando el merge\")\nreturn(TRUE)\n})\n}\n\n############################################\n# Estimar la biomasa aérea de las parcelas #\n############################################\n\nCB<-function(x){\n#tryCatch({\n Bio1<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(3.652+(-1.697*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(1.285*log(Dens..g.cm3.))) # Tropical Dry (Álvarez et al. 2012)\n Bio2<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(2.406+(-1.289*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(0.445*log(Dens..g.cm3.))) # Tropical Moist (Álvarez et al. 2012)\n Bio3<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(1.662+(-1.114*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(0.331*log(Dens..g.cm3.))) # Tropical Rain (Álvarez et al. 2012)\n Bio4<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(1.960+(-1.098*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(1.061*log(Dens..g.cm3.))) # Premontane Moist (Álvarez et al. 2012)\n Bio5<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(1.836+(-1.255*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(-0.222*log(Dens..g.cm3.))) # Lower Montane Wet (Álvarez et al. 2012)\n Bio6<-function(Dens..g.cm3.,D...cm.,Alt=NULL,AB=NULL) exp(3.130+(-1.536*log(D...cm.))+(1.169*((log(D...cm.))^2))+(-0.122*((log(D...cm.))^3))+(1.767*log(Dens..g.cm3.))) # Montane Wet (Álvarez et al. 2012)\n EQ1<-c(\"Bio1\",\"Bio2\",\"Bio3\",\"Bio4\",\"Bio5\",\"Bio6\")\n BA<-get(EQ1[as.integer(x[[\"EQ\"]])])(as.numeric(x[[\"Dens..g.cm3.\"]]),\n as.numeric(x[[\"D...cm.\"]]),\n as.numeric(x[[\"Alt\"]]),\n as.numeric(x[[\"AB\"]]))\n #return(BA)\n#}, error = function(ex) {\n#print(\"Error en el calculo de la Biomasa\")\n#})\n}\n\nCBC<-function(ID3,PL1){\ntryCatch({\nDT1<-merge(ID3,PL1)\nDT1$BAKg<-apply(DT1,1,CB)\nDT2<-aggregate(DT1$BAKg/((DT1$Área*10000)/10),list(Plot=DT1[,\"Plot\"]),sum,na.rm=TRUE)\nDT2$BA<-DT2$x\nMG1<-merge(PL1,DT2)\nDT3<-subset(MG1,select=c(Plot,Área,Año,Bosque,BA))\nprint(DT3)\nprint(DT3$BA)\nOUT<-getOutliers(DT3$BA,method=\"II\",distribution=\"lognormal\")\nprint(OUT) \nDT4<-DT3[-c(OUT$iRight,OUT$iLeft),]\n\nreturn(list(FALSE,DT3))\n}, error = function(ex) {\nprint(\"Error en el calculo de la biomasa y el carbono\")\nreturn (TRUE)\n})\n}\n\n###########################################################\n# Identificar parcelas con valores biomasa aérea atípicos #\n###########################################################\n\nATP<-function(DT3){\ntryCatch({\nOUT<-getOutliers(DT3$BA,method=\"II\",distribution=\"lognormal\")\nprint(OUT) \nDT4<-DT3[-c(OUT$iRight,OUT$iLeft),]\nreturn(list(FALSE,DT4))\n},error = function(ex){\nprint(\"Error en el calculo de los valores atipicos\")\nreturn (TRUE)\n})\n}\n\n###############################################\n# Estimar la biomasa aérea por tipo de bosque #\n###############################################\n\nABC<-function(r,DT4,BQ1){\ntryCatch({\nNS1<-with(DT4,tapply(BA,list(Bosque),length))\nMN1<-with(DT4,tapply(BA,Bosque,mean))\nDS1<-with(DT4,tapply(BA,list(Bosque),sd))\nBQ2<-BQ1[order(BQ1$Bosque),]\nEST<-data.frame(Ai=BQ2$Ai, # Área que ocupa cada tipo de bosque en el país (expresado en ha) #\n n=NS1, # Número de parcelas por tipo de bosque #\n BAj=MN1, # Biomasa aérea por tipo de bosque (expresada en Mg/ha) #\n DS=DS1, # Desviación estándar asociada al promedio de biomasa aérea por tipo de bosque (expresada en Mg/ha) #\n CV=DS1/MN1*100, # Coeficiente de variación por tipo de bosque (expresado en %) #\n IC=1.96*DS1/sqrt(NS1), # Intervalo de confianza asociado al promedio de biomasa aérea por tipo de bosque (expresado en Mg/ha) #\n BAi=(MN1*BQ2$Ai)/1000000000, # Biomasa aérea total potencial por tipo de bosque (expresada en Pg) #\n Ci=((MN1*0.5)*BQ2$Ai)/1000000000, # Potencial de Carbono almacenado en la biomasa aérea por tipo de bosque (expresado en Pg) #\n CO2e=((MN1*0.5*3.67)*BQ2$Ai)/1000000000) # Dióxido de Carbono que aún no ha sido emitido a la atmósfera por tipo de bosque (expresado en Pg) #\nwrite.table(EST,file=r,row.names=TRUE,sep=\";\",dec=\",\")\n},error = function(ex){\nprint(\"Error en la escritura de los datos\")\nreturn (TRUE)\n})\n}", "meta": {"hexsha": "2ecca92356cd908e3f655a8ee330e98fb555db89", "size": 5740, "ext": "r", "lang": "R", "max_stars_repo_path": "BiomasaYCarbono-EJB/ejbModule/co/gov/ideamredd/dao/EcuacionesBiomasa.r", "max_stars_repo_name": "danielrcardenas/mapas_ideam", "max_stars_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-03T09:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T09:29:34.000Z", "max_issues_repo_path": "BiomasaYCarbono-EJB/ejbModule/co/gov/ideamredd/dao/EcuacionesBiomasa.r", "max_issues_repo_name": "danielrcardenas/mapas_ideam", "max_issues_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BiomasaYCarbono-EJB/ejbModule/co/gov/ideamredd/dao/EcuacionesBiomasa.r", "max_forks_repo_name": "danielrcardenas/mapas_ideam", "max_forks_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7948717949, "max_line_length": 212, "alphanum_fraction": 0.5804878049, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955300967576076}} {"text": "#############################\r\n# Name: Inverse Gamma Landslide Fit \r\n# Author: Faith Taylor\r\n# Last updated : 02/02/2014\r\n# Purpose: Fit inverse gamma pdf to landslide data and test gooness of fit\r\n# Copyright: (c) 2014 Faith Taylor\r\n# This program is free software under the GNU General Public Licence (>=v2). \r\n##############################\r\n\r\n\r\n\r\n# Load modules\r\nlibrary(MCMCpack)\r\nlibrary(MASS)\r\nlibrary(PearsonDS)\r\nlibrary(calibrate)\r\nlibrary(sfmisc)\r\n# Initial definitions \r\n# 1. The inverse gamma log likelihood function\r\n\r\nll = function(par){\r\n if(par[1]>0 & par[2]>0 & par[3] abs(all_d[h])) maxx = g else maxx = h\r\n max_x_d = cumulative_x[maxx]\r\n \r\n dev.new()\r\n par(mar= c(5,6,2,2))\r\n plot(cumulative_x, all_d, xlab = \"LWR\", col =\"darkgreen\", pch = 20, xlim = c(1, (max(data))+5), ylim =c(-0.2, 0.2), xaxs =\"i\", yaxs = \"i\", ann = FALSE, axes = FALSE )\r\n axis(1, lwd = 2, tck =0.03, cex.axis = 1.5, font =2, at = c(1,(seq(0, ((max(data))+10), 5))))\r\n axis(3, lwd = 2, tck =0.03, labels = FALSE, at = c(1,(seq(0, ((max(data))+10), 5))))\r\n axis(2, at = seq( -0.2, 0.2, 0.05 ), lwd = 2, cex.lab = 1.2, las = 1, tck = 0.03, cex.axis = 1.5)\r\n axis(4, at = seq(-0.2, 0.2, 0.05) , lwd = 2, labels = FALSE, tck = 0.03)\r\n title(ylab = expression(bold(\"Obs. - Theoret., \")~bolditalic(F(LWR)[obs]~ \" -\" ~F(LWR)[theo])),cex.lab = 1.5, line = 4)\r\n title(xlab = expression(bold(\"Length to Width Ratio, \" ~bolditalic(LWR))), cex.lab = 1.5)\r\n points(max_x_d, all_d[maxx], col = \"red\", pch = 8)\r\n label = round(max_x_d, 2)\r\n label = paste(\"LWR =\", label)\r\n textxy(max_x_d, all_d[maxx],label, cx = 1.3, dcol = \"red\")\r\n abline(0,0, lty = 2, lwd = 2, col =\"grey\" )\r\n legend(\"topright\", do.call(\"expression\", list(phrase, phrase2)), lty = c(NA, NA), col = c(NA, NA), pch = c(NA, NA), lwd = c(NA, NA),bty = 'o', cex = 1.1, box.lwd = 2, inset = 0.01)\r\n\r\n # Use monte carlo modelling to test goodness of fit \r\n testresult = numeric(2500)\r\n dval = numeric(2500)\r\n \r\n\r\n rm(mle)\r\n rm(params)\r\n #Set up for loop\r\n for (i in 1:2500){\r\n # Generate n random values of LWR using the parameters fit to the observed data. N should be the same as the number of observed LWRS. \r\n rand_lwrs = (rpearsonV(n, shape_rho, location_s, (1/scale_a)))\r\n rand_lwrs_cumulative = sort(rand_lwrs)\r\n # Use MLE to fit an inverse gamma to these randomly generated LWRs\r\n \r\n # Optimise the parameter values\r\n mle = optim(c(1.4,0.001,-0.0001),ll)\r\n params = mle$par\r\n shape_f = params [1]\r\n #Scale is the reciprocal of the actual scale value \r\n scale_f = 1/(params[2])\r\n location_f = params [3]\r\n parset = list(shape_f, location_f, scale_f)\r\n teo_cdf = ppearsonV(rand_lwrs_cumulative, params = parset, lower.tail = FALSE)\r\n rand_cdf = (1:n)/n\r\n rand_cdf = sort(rand_cdf, decreasing = TRUE)\r\n rand_D= max(abs(rand_cdf - teo_cdf))\r\n dval[i] = rand_D\r\n if (rand_D <= empirical_D){ testresult[i] = 0}\r\n if (rand_D > empirical_D){ testresult[i] = 1}}\r\n\r\n ### The number of times the Empirical D value is smaller than the Monte carlo D value ###\r\n sum(testresult)\r\n Proportion = sum(testresult) / 2500\r\n ### Proportion of times the D value is smaller than the Monte Carlo D value ###\r\n dev.new()\r\n par(mar= c(5,6,2,2))\r\n yupper = (round(max(dval), 2)) + 0.1\r\n yupper2 = round(yupper, 1)\r\n boxplot(dval, range = 0, lwd = 2, lty = 1, axes = FALSE, xaxs =\"i\", yaxs = \"i\", ylim = c(0, yupper2) )\r\n axis(1, tck = 0, labels = FALSE, at = c(0,2), lwd = 2)\r\n axis(2, lwd = 2, at = seq(0, yupper2, 0.05), las = 1, cex.axis = 1.5, tck = 0.03)\r\n axis(3, tck = 0, labels = FALSE, at = c(0,2), lwd = 2)\r\n axis(4, lwd = 2, at = seq(0, yupper2, 0.05), las = 1, cex.axis = 1.5, labels = FALSE, tck = 0.03)\r\n title(ylab = expression(bold(D - Value)), cex.lab = 1.5, line = 4)\r\n points(empirical_D, col = \"red\", pch = \"+\", cex = 2)\r\n abline((quantile(dval, 0.9)), 0, lty = 2, col = \"grey\", lwd = 2)\r\n abline((quantile(dval, 0.95)), 0, lty = 2, col = \"lightgrey\", lwd = 2)\r\n legend(\"topright\", do.call(\"expression\", list(phrase, phrase2)), lty = c(NA, NA), col = c(NA, NA), pch = c(NA, NA), lwd = c(NA, NA),bty = 'o', cex = 1.1, box.lwd = 2, inset = 0.01)\r\n\r\n # Now try producing bootstapped samples of the real data and fitting to each sample\r\n startshape = shape_rho\r\n startscale = scale_a\r\n startlocation = location_s\r\n\r\n\r\n estsa <- sapply(1:1000, function(i) {\r\n\r\n #Sample the data with replacement (the bootstrapping part)\r\n xi <- sample(data, size = n, replace = TRUE)\r\n ll = function(par){\r\n if(par[1]>0 & par[2]>0 & par[3] 0)/nrow(x-y),2)\n loNum <- round(colSums((x-y) < 0)/nrow(x-y),2)\n textPercent <- paste(loNum, \"% < 0 < \", hiNum, \"%\", sep=\"\")\n textXAxis <- expression(paste(mu,\"Rate1 - \",mu,\"Rate2\", sep=\"\"))\n df[\"muDiff\"] = x - y\n hpdLimits <- HPD(x-y)\n \n #Plot\n ggplot(df, aes(x=muDiff)) + \n geom_histogram(bins=50, colour=\"black\", fill=\"white\", alpha=0.6) + # Histrogram\n geom_vline(aes(xintercept=mean(x=muDiff)), color=\"red\", linetype=\"dashed\", size=1) + # Mean lines\n geom_vline(aes(xintercept=0), color=\"black\", linetype=\"solid\", size=2) + # Zero line\n geom_vline(aes(xintercept=hpdLimits[1]), color=\"blue\", linetype=\"dashed\", size=1) + # Low HPD\n geom_vline(aes(xintercept=hpdLimits[2]), color=\"blue\", linetype=\"dashed\", size=1) + # High HPD\n annotate(geom=\"text\", x=mean(x-y), y=Inf, label=textPercent, color=\"red\", fontface=\"bold\", vjust=1, hjust=0.5) +\n annotate(geom=\"text\", x=hpdLimits[1], y=0, label=hpdLimits[1], color=\"blue\", fontface=\"bold\", vjust=0, hjust=0) +\n annotate(geom=\"text\", x=hpdLimits[2], y=0, label=hpdLimits[2], color=\"blue\", fontface=\"bold\", vjust=0, hjust=1) +\n scale_x_continuous(name =textXAxis)\n}\n\n#Load in data\nsubset1 <- read.csv(\"results/subset1.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset4 <- read.csv(\"results/subset4.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset5 <- read.csv(\"results/subset5.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset6 <- read.csv(\"results/subset6.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset7 <- read.csv(\"results/subset7.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset8 <- read.csv(\"results/subset8.log.txt\", skip = 3, header = T, sep=\"\\t\")\nsubset9 <- read.csv(\"results/subset9.log.txt\", skip = 3, header = T, sep=\"\\t\")\n\n#Burn-in 10% of data\nsubset1 <- subset1[-c(1:101),]\nsubset4 <- subset4[-c(1:101),]\nsubset5 <- subset5[-c(1:101),]\nsubset6 <- subset6[-c(1:101),]\nsubset7 <- subset7[-c(1:101),]\nsubset8 <- subset8[-c(1:101),]\nsubset9 <- subset9[-c(1:101),]\n\n#Bayesian estimation suspersedes t-test\nx <- as.matrix(subset1[\"civf.meanRate\"])\ny <- as.matrix(subset1[\"d1b.meanRate\"])\n(plot1 <- plotHistogram(subset1,x,y))\n\nx <- as.matrix(subset4[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset4[\"delta1b.aln.meanRate\"])\n(plot4 <- plotHistogram(subset4,x,y))\n\nx <- as.matrix(subset5[\"alpha.aln.meanRate\"])\ny <- as.matrix(subset5[\"cluster_ivb.aln.meanRate\"])\n(plot5 <- plotHistogram(subset5,x,y))\n\nx <- as.matrix(subset6[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset6[\"alpha.aln.meanRate\"])\n(plot6 <- plotHistogram(subset6,x,y))\n\nx <- as.matrix(subset7[\"civa.aln.meanRate\"])\ny <- as.matrix(subset7[\"civb.aln.meanRate\"])\n(plot7 <- plotHistogram(subset7,x,y))\n\nx <- as.matrix(subset8[\"civa.aln.meanRate\"])\ny <- as.matrix(subset8[\"delta1a.aln.meanRate\"])\n(plot8 <- plotHistogram(subset8,x,y))\n\nx <- as.matrix(subset9[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset9[\"delta1a.aln.meanRate\"])\n(plot9 <- plotHistogram(subset9,x,y))\n\n#Pretty plot\ntiff('test.tiff', units=\"in\", width=13.5, height=9, res=300, compression = 'lzw')\n\nplot_grid(plot1, plot4, plot5, plot6, plot7, plot8, plot9,\n labels = c(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"),\n ncol = 3, nrow = 3)\ndev.off()\n\n\n###Frequentist analysis, ignore\n#Kolmogorov-Smirnov test\nx <- as.matrix(subset1[\"civf.meanRate\"])\ny <- as.matrix(subset1[\"d1b.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y)) \nchisq.test(x,y)\n\nx <- as.matrix(subset4[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset4[\"delta1b.aln.meanRate\"])\nhist(x)\nhist(y)\nhist(x-y)\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\nx <- as.matrix(subset5[\"alpha.aln.meanRate\"])\ny <- as.matrix(subset5[\"cluster_ivb.aln.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\nx <- as.matrix(subset6[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset6[\"alpha.aln.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\nx <- as.matrix(subset7[\"civa.aln.meanRate\"])\ny <- as.matrix(subset7[\"civb.aln.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\nx <- as.matrix(subset8[\"civa.aln.meanRate\"])\ny <- as.matrix(subset8[\"delta1a.aln.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\nx <- as.matrix(subset9[\"X2010.1.aln.meanRate\"])\ny <- as.matrix(subset9[\"delta1a.aln.meanRate\"])\nks.test(x,y)\nt.test(x,y)\nwilcox.test(x,y)\nkruskal.test(list(x,y))\nchisq.test(x,y)\n\n# https://rpubs.com/mharris/KSplot\n# simulate two distributions - your data goes here!\ngroup <- c(rep(\"sample1\", length(x)), rep(\"sample2\", length(y)))\ndat <- data.frame(KSD = c(x,y), group = group)\n# create ECDF of data\ncdf1 <- ecdf(x) \ncdf2 <- ecdf(y) \n# find min and max statistics to draw line between points of greatest distance\nminMax <- seq(min(x, y), max(x, y), length.out=length(x)) \nx0 <- minMax[which( abs(cdf1(minMax) - cdf2(minMax)) == max(abs(cdf1(minMax) - cdf2(minMax))) )] \ny0 <- cdf1(x0) \ny1 <- cdf2(x0) \n\nggplot(dat, aes(x = KSD, group = group, color = group))+\n stat_ecdf(size=1) +\n theme_bw(base_size = 28) +\n theme(legend.position =\"top\") +\n xlab(\"Sample\") +\n ylab(\"ECDF\") +\n #geom_line(size=1) +\n geom_segment(aes(x = x0[1], y = y0[1], xend = x0[1], yend = y1[1]),\n linetype = \"dashed\", color = \"red\") +\n geom_point(aes(x = x0[1] , y= y0[1]), color=\"red\", size=8) +\n geom_point(aes(x = x0[1] , y= y1[1]), color=\"red\", size=8) +\n ggtitle(\"K-S Test: Sample 1 / Sample 2\") +\n theme(legend.title=element_blank())\n\n\n\n#hiNum <- round(colSums((x-y) > 0)/nrow(x-y),2)\n#loNum <- round(colSums((x-y) < 0)/nrow(x-y),2)\n#textPercent <- paste(loNum, \"% < 0 < \", hiNum, \"%\", sep=\"\")\n#textXAxis <- expression(paste(mu,\"Rate1 - \",mu,\"Rate2\", sep=\"\"))\n#subset4[\"muDiff\"] = x - y\n#hpdLimits <- HPD(x-y)\n#ggplot(subset4, aes(x=muDiff)) + \n# geom_histogram(bins=50, colour=\"black\", fill=\"white\", alpha=0.6) + # Histrogram\n# geom_vline(aes(xintercept=mean(x=muDiff)), color=\"red\", linetype=\"dashed\", size=1) + # Mean lines\n# geom_vline(aes(xintercept=0), color=\"black\", linetype=\"solid\", size=2) + # Zero line\n# geom_vline(aes(xintercept=hpdLimits[1]), color=\"blue\", linetype=\"dashed\", size=1) + # Low HPD\n# geom_vline(aes(xintercept=hpdLimits[2]), color=\"blue\", linetype=\"dashed\", size=1) + # High HPD\n# annotate(geom=\"text\", x=mean(x-y), y=Inf, label=textPercent, color=\"red\", fontface=\"bold\", vjust=1, hjust=0.5) +\n# annotate(geom=\"text\", x=hpdLimits[1], y=0, label=hpdLimits[1], color=\"blue\", fontface=\"bold\", vjust=0, hjust=0) +\n# annotate(geom=\"text\", x=hpdLimits[2], y=0, label=hpdLimits[2], color=\"blue\", fontface=\"bold\", vjust=0, hjust=1) +\n# scale_x_continuous(name =textXAxis)\n", "meta": {"hexsha": "f10c69f41c3406c6393e9589957b34bbac08b606", "size": 6984, "ext": "r", "lang": "R", "max_stars_repo_path": "figureS4_credible_interval/kolmogorov_smirnov.r", "max_stars_repo_name": "mazeller/neuraminidase_diversity", "max_stars_repo_head_hexsha": "6f432a44418abca417cb181aeceaa9dbc38b39f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-08T23:32:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T23:32:27.000Z", "max_issues_repo_path": "figureS4_credible_interval/kolmogorov_smirnov.r", "max_issues_repo_name": "mazeller/neuraminidase_diversity", "max_issues_repo_head_hexsha": "6f432a44418abca417cb181aeceaa9dbc38b39f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figureS4_credible_interval/kolmogorov_smirnov.r", "max_forks_repo_name": "mazeller/neuraminidase_diversity", "max_forks_repo_head_hexsha": "6f432a44418abca417cb181aeceaa9dbc38b39f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-16T02:19:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T02:19:09.000Z", "avg_line_length": 36.5654450262, "max_line_length": 117, "alphanum_fraction": 0.6411798396, "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.488822660301742}} {"text": "\n convert.degmin2degdec = function (x, y=NULL, vnames=c(\"lon\", \"lat\") ) {\n xlon = x[,vnames[1]]\n xlat = x[,vnames[2]]\n if (is.null(y)) {\n x[,vnames[1]] = trunc(xlon) + round((xlon - trunc(xlon)) /60 * 100, 6)\n x[,vnames[2]] = trunc(xlat) + round((xlat - trunc(xlat)) /60 * 100, 6)\n } else {\n if (y==\"lon\") x = - (trunc(x/100)+(x-100*trunc(x/100))/60)\n if (y==\"lat\") x = trunc(x /100)+(x - 100*trunc(x /100))/60\n }\n return (x)\n }\n\n\n", "meta": {"hexsha": "0aff8fc34a348d31c7d88ef97af85f9ce444e2c6", "size": 471, "ext": "r", "lang": "R", "max_stars_repo_path": "R/convert.degmin2degdec.r", "max_stars_repo_name": "PEDsnowcrab/aegis", "max_stars_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/convert.degmin2degdec.r", "max_issues_repo_name": "PEDsnowcrab/aegis", "max_issues_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/convert.degmin2degdec.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4375, "max_line_length": 76, "alphanum_fraction": 0.4989384289, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.48837240106965085}} {"text": "#'@title calcHMWaveMakingRes\n#'\n#'@description Calculate wave resistance (\\code{Rw}) (kN) from the Holtrop &\n#'Mennen method.\n#'\n#'@param lwl Waterline length (vector of numericals, m) (see\n#'\\code{\\link{calclwl}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param Cp Prismatic coefficient (vector of numericals, dimensionless) (see\n#'\\code{\\link{calcCp}})\n#'@param Cwp Water plane area coefficient (vector of numericals, see\n#'\\code{\\link{calcCwp}})\n#'@param Cm Midship section coefficient (vector of numericals, dimensionless)\n#'(see \\code{\\link{calcCm}})\n#'@param maxDisplacement Maximum ship displacement (vector of numericals, m^3)\n#'@param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'@param froudeNum Froude number (vector of numericals, dimensionless) (see\n#'\\code{\\link{calcFroudeNum}})\n#'@param At Transom area (vector of numericals, m^2) (see \\code{\\link{calcAt}})\n#'@param hb Center of bulb area above keel line (vector of numericals, m) (see\n#' \\code{\\link{calchb}})\n#'@param Abt Traverse bulb area (vector of numericals, m^2) (see\n#'\\code{\\link{calcAbt}})\n#'@param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#'@param forwardDraft Forward draft (deviation from actual draft indicates trim)\n#' (vector of numericals, m)\n#'@param lcb Longitudinal position of center of buoyancy (vector of numericals,\n#'see \\code{\\link{calclcb}})\n#'\n#'@details\n#'Note: This calculates resistance, not a coefficient.Therefore, it does not\n#'need to be multiplied by wetted surface area like the frictional resistance\n#'coefficient is.\n#'\n#'Note: In \"A Statistical Re-Analysis of Resistance and Propulsion Data\" the\n#'authors re-analyze with the inclusion of Series 64 hull forms for a total of\n#'334 models included in the analysis. Their original paper insufficiently\n#'modeled high speed craft with Froude number >= 0.55, thus the original wave\n#'making resistance equation is used for \\code{froudeNum} < 0.55 and the new\n#'wave making resistance equation is used for \\code{froudeNum} >= 0.55. The\n#'authors also include wave making resistance equations in the updated paper for\n#'Froude number < 0.55, but these require more computing power and they mention\n#'that they closely resemble the original equation. Therefore, the original\n#'equation is used for \\code{froudeNum} < 0.55.\n#'\n#'Extra Info:\n#'\n#'\\code{c2}: Accounts for the reduction of the wave resistance due to action of\n#'a bulbous bow\n#'\n#'\\code{c5}: Represents the influence of a transom stern on the wave resistance\n#'\n#'\\code{i_E}: The angle of the waterline at the bow in the degrees with reference\n#' to center plane but neglecting the local shape at the stem\n#'\n#'@return \\code{Rw} (vector of numericals, kN)\n#'\n#'@references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'Holtrop, J. and Mennen, G. G. J. 1984. \"A Statistical Re-Analysis of Resistance\n#'and Propulsion Data'.\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCp}}\n#'\\item \\code{\\link{calcCwp}}\n#'\\item \\code{\\link{calcCm}}\n#'\\item \\code{\\link{calcFroudeNum}}\n#'\\item \\code{\\link{calcAt}}\n#'\\item \\code{\\link{calchb}}\n#'\\item \\code{\\link{calcAbt}}\n#'\\item \\code{\\link{calclcb}}}\n#'\n#'@family Holtrop-Mennen Calculations\n#'@family Resistance Calculations\n#'\n#' @examples\n#' calcHMWaveMakingRes(lwl=c(218.75,209.25),\n#' breadth=c(32.25,32.20),\n#' Cp=c(0.81,0.67),\n#' Cwp=c(0.91,0.84),\n#' Cm=c(0.99,0.98),\n#' maxDisplacement=c(80097,52382.04),\n#' maxDraft=c(13.57,11.49),\n#' froudeNum=c(0,0.25),\n#' At=c(22.2,18.5),\n#' hb=c(5.43,4.6),\n#' Abt=c(32.02,27.98),\n#' seawaterDensity=1.025,\n#' forwardDraft=c(13.57,11.49))\n#' @export\n\ncalcHMWaveMakingRes<- function(lwl,breadth,Cp,Cwp,\n Cm,maxDisplacement,maxDraft,\n froudeNum,\n At,\n hb,\n Abt,\n seawaterDensity,\n forwardDraft,\n lcb=0){\n\n\nc1<- ifelse(breadth/lwl<0.11,\n 2223105*(\n #c7\n (\n 0.229577*(breadth/lwl)^0.33333\n )^3.78613)*\n ((maxDraft/breadth)^1.07961)*(90-\n\n #i_E\n (\n 1+89*exp(-(lwl/breadth)^0.80856*\n ((1-Cwp)^0.30484)*\n (1-Cp-0.0225*lcb)^0.6367*\n ((#Lr\n (lwl*(1-Cp+(0.06*Cp*lcb)/(4*Cp-1)))/\n breadth\n )^0.34574)*\n (100*maxDisplacement/(lwl^3))^0.16302\n )\n )\n )^-1.37565\n,ifelse(breadth/lwl<0.25, #case 2 (<=0.11b/lwl<0.25)\n 2223105*(\n #c7\n (\n breadth/lwl\n )^3.78613)*\n ((maxDraft/breadth)^1.07961)*(90-\n\n #i_E\n (\n 1+89*exp(-(lwl/breadth)^0.80856*\n ((1-Cwp)^0.30484)*\n (1-Cp-0.0225*lcb)^0.6367*\n ((#Lr\n (lwl*(1-Cp+(0.06*Cp*lcb)/(4*Cp-1)))/\n breadth\n )^0.34574)*\n (100*maxDisplacement/(lwl^3))^0.16302\n )\n )\n )^-1.37565\n,#case #3 (b/lwl>= 0.25)\n 2223105*(\n #c7\n (\n 0.5-0.0625*(lwl/breadth)\n )^3.78613)*\n ((maxDraft/breadth)^1.07961)*(90-\n\n #i_E\n (\n 1+89*exp(-(lwl/breadth)^0.80856*\n ((1-Cwp)^0.30484)*\n (1-Cp-0.0225*lcb)^0.6367*\n ((#Lr\n (lwl*(1-Cp+(0.06*Cp*lcb)/(4*Cp-1)))/\n breadth\n )^0.34574)*\n (100*maxDisplacement/(lwl^3))^0.16302\n )\n )\n )^-1.37565\n))\n#=========================================\n#both methods\nc2<-exp(-1.89*sqrt(\n #c3\n 0.56*Abt^1.5/(breadth*maxDraft*(\n 0.31*sqrt(Abt)+forwardDraft-hb\n ))\n))\n#=========================================\n#both methods\nc5<-1-0.8*At/(breadth*maxDraft*Cm)\n#=========================================\nm1<- ifelse(Cp<0.8,#case 1\n 0.0140407*(lwl/maxDraft)-(1.75254*(maxDisplacement^(1/3))/lwl)-\n 4.79323*(breadth/lwl)-\n #c16\n (\n 8.07981*Cp-13.8673*(Cp^2)+6.984388*(Cp^3)\n ),#case 2\n 0.0140407*(lwl/maxDraft)-(1.75254*(maxDisplacement^(1/3))/lwl)-\n 4.79323*(breadth/lwl)-\n #c16\n (\n 1.73014-0.7067*Cp\n ))\n#=========================================\n#both methods\nc15<-ifelse((lwl^3/maxDisplacement)<512,\n -1.69385,\n ifelse((lwl^3/maxDisplacement)<1726.91,\n -1.69385+(\n (lwl/(maxDisplacement^(1/3)))-8\n )/2.36,\n 0\n )\n)\n#=========================================\n#orig\n\nm2<-c15*(Cp^2)*exp(-0.1*froudeNum^-2)\n#=========================================\n#both methods\nalpha<- ifelse((lwl/breadth)<12,#case 1\n 1.446*Cp-0.03*(lwl/breadth)\n,#case 2\n 1.446*Cp-0.36\n)\n#=========================================\n#Fn>0.55\n\n m4<-c15*0.4*exp(-0.034*(froudeNum^-3.29))\n#=========================================\n#Fn>0.55\nc17<-6919.3*(Cm^-1.3346)*\n ((maxDisplacement/(lwl^3))^2.00977)*\n (((lwl/breadth)-2)^1.40692)\n#=========================================\n#Fn>0.55\nm3<- -7.2035*((breadth/lwl)^0.326869)*\n ((maxDraft/breadth)^0.605375)\n#=========================================\n#Avoids causing errors by calculating with 0 Froude Num from 0 speed\nRw<-froudeNum\n\nindex<-which(froudeNum>0)\nRw[index]<- ifelse(froudeNum[index]<0.55,\n #case 1: from 'An Approximate Power Prediction Method'(Holtrop & Mennen, 1982)\n c1[index]*c2[index]*c5[index]*maxDisplacement[index]*seawaterDensity*9.81*\n exp(m1[index]*(froudeNum[index]^-0.9)+\n m2[index]*cos(alpha[index]*froudeNum[index]^-2)\n ),\n #case 2: from 'Statistical Re-Analysis of Resitance and Propulsion Data'(Holtrop,1984)\nc17[index]*c2[index]*c5[index]*maxDisplacement[index]*seawaterDensity*9.81*\n exp(m3[index]*(froudeNum[index]^-0.9)+\n m4[index]*cos(alpha[index]*froudeNum[index]^-2)\n )\n )\n\n\n return(Rw)\n}\n", "meta": {"hexsha": "1bcfd08544679c4a3dc7309a7a8d124991c323bd", "size": 9385, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMWaveMakingRes.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcHMWaveMakingRes.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcHMWaveMakingRes.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 37.2420634921, "max_line_length": 88, "alphanum_fraction": 0.4892914225, "num_tokens": 2665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4881526376993041}} {"text": "fptcdf=function(z,x0max,chi,driftrate,sddrift) {\n zs=z*sddrift; \n zu=z*driftrate;\n chiminuszu=chi-zu;\n xx=chiminuszu-x0max\n chizu=chiminuszu/zs; \n chizumax=xx/zs\n tmp1=zs*(dnorm(chizumax)-dnorm(chizu))\n tmp2=xx*pnorm(chizumax)-chiminuszu*pnorm(chizu)\n 1+(tmp1+tmp2)/x0max\n}\n\nfptpdf=function(z,x0max,chi,driftrate,sddrift) {\n zs=z*sddrift\n zu=z*driftrate\n chiminuszu=chi-zu\n chizu=chiminuszu/zs\n chizumax=(chiminuszu-x0max)/zs\n (driftrate*(pnorm(chizu)-pnorm(chizumax)) + \n sddrift*(dnorm(chizumax)-dnorm(chizu)))/x0max\n}\n\nallrtCDF=function(t,x0max,chi,drift,sdI) {\n # Generates CDF for all RTs irrespective of response.\n N=length(drift) # Number of responses.\n tmp=array(dim=c(length(t),N))\n for (i in 1:N) tmp[,i]=fptcdf(z=t,x0max=x0max,chi=chi,driftrate=drift[i],sddrift=sdI)\n 1-apply(1-tmp,1,prod)\n}\n\nn1PDF=function(t,x0max,chi,drift,sdI) {\n # Generates defective PDF for responses on node #1. \n N=length(drift) # Number of responses.\n if (N>2) {\n tmp=array(dim=c(length(t),N-1))\n for (i in 2:N) tmp[,i-1]=fptcdf(z=t,x0max=x0max,chi=chi,driftrate=drift[i],sddrift=sdI)\n G=apply(1-tmp,1,prod)\n } else {\n G=1-fptcdf(z=t,x0max=x0max,chi=chi,driftrate=drift[2],sddrift=sdI)\n }\n G*fptpdf(z=t,x0max=x0max,chi=chi,driftrate=drift[1],sddrift=sdI)\n}\n\nn1CDF=function(t,x0max,chi,drift,sdI) {\n # Generates defective CDF for responses on node #1. \n outs=numeric(length(t)) ; bounds=c(0,t)\n for (i in 1:length(t)) {\n tmp=\"error\"\n repeat {\n if (bounds[i]>=bounds[i+1]) {outs[i]=0;break}\n tmp=try(integrate(f=n1PDF,lower=bounds[i],upper=bounds[i+1],\n x0max=x0max,chi=chi,drift=drift,sdI=sdI)$value,silent=T)\n if (is.numeric(tmp)) {outs[i]=tmp;break}\n # Try smart lower bound.\n if (bounds[i]<=0) {\n\tbounds[i]=max(c((chi-0.98*x0max)/(max(mean(drift),drift[1])+2*sdI),0))\n\tnext\n }\n # Try smart upper bound.\n if (bounds[i+1]==Inf) {\n\tbounds[i+1]=0.02*chi/(mean(drift)-2*sdI)\n\tnext\n }\n stop(\"Error in n1CDF that I could not catch.\")\n }\n }\n cumsum(outs)\n}\n\nn1mean=function(x0max,chi,drift,sdI) {\n # Generates mean RT for responses on node #1. \n pc=n1CDF(Inf,x0max,chi,drift,sdI)\n fn=function(t,x0max,chi,drift,sdI,pc) t*n1PDF(t,x0max,chi,drift,sdI)/pc\n tmp=integrate(f=fn,lower=0,upper=100*chi,x0max=x0max,chi=chi,pc=pc,\n drift=drift,sdI=sdI)$value\n list(mean=tmp,p=pc)\n}\n\nactCDF=function(z,t,x0max,chi,drift,sdI) {\n # CDF for the distribution (over trials) of activation values at time t.\n zat=(z-x0max)/t ; zt=z/t ; sdi2=2*(sdI^2)\n exp1=exp(-((zt-drift)^2)/sdi2)\n exp2=exp(-((zat-drift)^2)/sdi2)\n tmp1=t*sdI*(exp1-exp2)/sqrt(2*pi)\n tmp2=pnorm(zat,mean=drift,sd=sdI)\n tmp3=pnorm(zt,mean=drift,sd=sdI)\n (tmp1+(x0max-z+drift*t)*tmp2+(z-drift*t)*tmp3)/x0max\n}\n\nactPDF=function(z,t,x0max,chi,drift,sdI) {\n # CDF for the distribution (over trials) of activation values at time t.\n tmp1=pnorm((z-x0max)/t,mean=drift,sd=sdI)\n tmp2=pnorm(z/t,mean=drift,sd=sdI)\n (-tmp1+tmp2)/x0max\n} \n \nlbameans=function(Is,sdI,x0max,Ter,chi) {\n # Ter should be a vector of length ncond, the others atomic, \n # except Is which is ncond x 2.\n ncond=length(Is)/2\n outm<-outp<-array(dim=c(ncond,2))\n for (i in 1:ncond) {\n for (j in 1:2) {\n tmp=n1mean(x0max,chi,drift=Is[i,switch(j,1:2,2:1)],sdI)\n outm[i,j]=tmp$mean+Ter[i]\n outp[i,]=tmp$p\n }}\n list(mns=c(outm[1:ncond,2],outm[ncond:1,1]),ps=c(outp[1:ncond,2],outp[ncond:1,1]))\n}\n\ndeadlineaccuracy=function(t,x0max,chi,drift,sdI,guess=.5,meth=\"noboundary\") {\n # Works out deadline accuracy, using one of three \n # methods:\n # - noboundary = no implicity boundaries.\n # - partial = uses implicit boundaries, and partial information.\n # - nopartial = uses implicit boundaries and guesses otherwise.\n meth=match.arg(meth,c(\"noboundary\",\"partial\",\"nopartial\"))\n noboundaries=function(t,x0max,chi,drift,sdI,ulimit=Inf) {\n # Probability of a correct response in a deadline experiment\n # at times t, with no implicit boundaries.\n N=length(drift)\n tmpf=function(x,t,x0max,chi,drift,sdI) {\n if (N>2) {\n\ttmp=array(dim=c(length(x),N-1))\n\tfor (i in 2:N) tmp[,i-1]=actCDF(x,t,x0max,chi,drift[i],sdI)\n\tG=apply(tmp,1,prod)*actPDF(x,t,x0max,chi,drift[1],sdI)\n } else {\n\tG=actCDF(x,t,x0max,chi,drift[2],sdI)*actPDF(x,t,x0max,chi,drift[1],sdI)\n }}\n outs=numeric(length(t))\n for (i in 1:length(t)) {\n if (t[i]<=0) {\n\touts[i]=.5\n } else {\n\touts[i]=integrate(f=tmpf,lower=-Inf,upper=ulimit,t=t[i],\n x0max=x0max,drift=drift,sdI=sdI)$value\n }\n }\n outs\n }\n if (meth==\"noboundary\") {\n noboundaries(t,x0max,chi,drift,sdI,ulimit=Inf)\n } else { \n pt=n1CDF(t=t,x0max=x0max,chi=chi,drift=drift,sdI=sdI)\n pa=allrtCDF(t=t,x0max=x0max,chi=chi,drift=drift,sdI=sdI)\n pguess=switch(meth,\"nopartial\"=guess*(1-pa),\"partial\"=\n noboundaries(t=t,x0max=x0max,chi=chi,drift=drift,sdI=sdI,ulimit=chi))\n pt+pguess \n }\n}\n", "meta": {"hexsha": "f7cdb5efca3a1d96cae63ea2f5b83d692e470193", "size": 4943, "ext": "r", "lang": "R", "max_stars_repo_path": "hddm/tests/lba-math.r", "max_stars_repo_name": "twiecki/hddm", "max_stars_repo_head_hexsha": "854513b2a04dbd43dab84d14fdede64ec64f0eab", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hddm/tests/lba-math.r", "max_issues_repo_name": "twiecki/hddm", "max_issues_repo_head_hexsha": "854513b2a04dbd43dab84d14fdede64ec64f0eab", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hddm/tests/lba-math.r", "max_forks_repo_name": "twiecki/hddm", "max_forks_repo_head_hexsha": "854513b2a04dbd43dab84d14fdede64ec64f0eab", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-04T13:54:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-04T13:54:49.000Z", "avg_line_length": 32.7350993377, "max_line_length": 91, "alphanum_fraction": 0.6574954481, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.48813994140087297}} {"text": "[[[[[\n Show that a real r is Martin-Lof random\n iff it is Chaitin random.\n\n An effective covering A_k of k is a function\n of k that enumerates bit strings s,\n which are the initial bits of the covered\n reals. We assume that no s in A_k is a\n proper prefix or extension of another.\n Thus the measure of the cover A_k of k is\n exactly Sum_{s in A_k} of 2^{-|s|},\n where |s| is the length of the bit string s.\n]]]]]\n\n[Second part: not Ch random ===> not M-L random] \n\ndefine (is-in? x l) [is x an element of list l?]\n if atom l false\n if = x car l true\n (is-in? x cdr l)\n\ndefine is-in?\nvalue (lambda (x l) (if (atom l) false (if (= x (car l))\n true (is-in? x (cdr l)))))\n\ndefine (is-prefix-of? x y) [is bit string x a prefix of bit string y?]\n if atom x true\n if atom y false\n if = car x car y (is-prefix-of? cdr x cdr y)\n false\n\ndefine is-prefix-of?\nvalue (lambda (x y) (if (atom x) true (if (atom y) false\n (if (= (car x) (car y)) (is-prefix-of? (cdr x) (c\n dr y)) false))))\n\ndefine (is-bit-string? x) [is x a list of 0's and 1's?]\n if = x nil true\n if atom x false\n if = 0 car x (is-bit-string? cdr x)\n if = 1 car x (is-bit-string? cdr x)\n false\n\ndefine is-bit-string?\nvalue (lambda (x) (if (= x nil) true (if (atom x) false \n (if (= 0 (car x)) (is-bit-string? (cdr x)) (if (= \n 1 (car x)) (is-bit-string? (cdr x)) false)))))\n\ndefine C [test computer---real thing is eval read-exp]\n let (loop) [doubles all bits up to & including first 1]\n if = 1 read-bit '(1 1)\n cons 0 cons 0 (loop)\n (loop)\n\ndefine C\nvalue ((' (lambda (loop) (loop))) (' (lambda () (if (= 1\n (read-bit)) (' (1 1)) (cons 0 (cons 0 (loop))))))\n )\n\n[Now let's do stage n of A_k = strings s with H(s) <= |s| - k.] \n[At stage n we look at programs p up to n bits in size for time up to n.]\n\ndefine (compressible-by-k n k)\n (look-at nil)\n\ndefine compressible-by-k\nvalue (lambda (n k) (look-at nil))\n\n[this routine has free parameters n, k, C]\n\ndefine (look-at p) [produces strings compressible by k within time n]\n let v try n C ['eval read-exp] p\n if = success car v\n let w cadr v \n if (is-bit-string? w)\n if >= length w + k length p\n cons w nil\n nil\n nil\n [otherwise failure]\n if = n length p nil [stop!]\n append (look-at append p cons 0 nil)\n (look-at append p cons 1 nil)\n\ndefine look-at\nvalue (lambda (p) ((' (lambda (v) (if (= success (car v)\n ) ((' (lambda (w) (if (is-bit-string? w) (if (>= (\n length w) (+ k (length p))) (cons w nil) nil) nil)\n )) (car (cdr v))) (if (= n (length p)) nil (append\n (look-at (append p (cons 0 nil))) (look-at (appen\n d p (cons 1 nil)))))))) (try n C p)))\n\n[list of intervals in covering so far]\n[used to avoid overlapping intervals in covering]\ndefine intervals ()\n\ndefine intervals\nvalue ()\n\ndefine (process-all x) [process list of intervals x]\n if atom x intervals\n let intervals append (process car x) intervals\n (process-all cdr x)\n\ndefine process-all\nvalue (lambda (x) (if (atom x) intervals ((' (lambda (in\n tervals) (process-all (cdr x)))) (append (process \n (car x)) intervals))))\n\ndefine (process interval) [process individual interval]\n if (new-interval-covered-by-previous-one? interval intervals) \n [then don't need to repeat it]\n nil\n let holes (new-interval-covers-previous-ones interval intervals)\n if atom holes\n [then interval is fine as is]\n cons display interval nil \n [get max granularity needed]\n let max (max-length holes) \n [convert everything to same granularity]\n let holes (extend-all holes max)\n [and remove overlap]\n (subtract (extend interval max) holes)\n\ndefine process\nvalue (lambda (interval) (if (new-interval-covered-by-pr\n evious-one? interval intervals) nil ((' (lambda (h\n oles) (if (atom holes) (cons (display interval) ni\n l) ((' (lambda (max) ((' (lambda (holes) (subtract\n (extend interval max) holes))) (extend-all holes \n max)))) (max-length holes))))) (new-interval-cover\n s-previous-ones interval intervals))))\n\n[returns true/false]\ndefine (new-interval-covered-by-previous-one? interval intervals)\n if atom intervals false\n if (is-prefix-of? car intervals interval) true\n (new-interval-covered-by-previous-one? interval cdr intervals)\n\ndefine new-interval-covered-by-previous-one?\nvalue (lambda (interval intervals) (if (atom intervals) \n false (if (is-prefix-of? (car intervals) interval)\n true (new-interval-covered-by-previous-one? inter\n val (cdr intervals)))))\n\n[returns set of previous intervals covered by this one]\ndefine (new-interval-covers-previous-ones interval intervals)\n if atom intervals nil\n if (is-prefix-of? interval car intervals)\n [then] cons car intervals (new-interval-covers-previous-ones interval cdr intervals)\n [else] (new-interval-covers-previous-ones interval cdr intervals)\n\ndefine new-interval-covers-previous-ones\nvalue (lambda (interval intervals) (if (atom intervals) \n nil (if (is-prefix-of? interval (car intervals)) (\n cons (car intervals) (new-interval-covers-previous\n -ones interval (cdr intervals))) (new-interval-cov\n ers-previous-ones interval (cdr intervals)))))\n\n \n[get maximum length of a list of bit strings]\ndefine (max-length list) \n if atom list 0\n let len1 length car list\n let len2 (max-length cdr list)\n if > len1 len2 \n [then] len1 \n [else] len2 \n\ndefine max-length\nvalue (lambda (list) (if (atom list) 0 ((' (lambda (len1\n ) ((' (lambda (len2) (if (> len1 len2) len1 len2))\n ) (max-length (cdr list))))) (length (car list))))\n )\n\n[produce set of all extensions of a given bit string to a given length]\n[(assumed >= to its current length)]\ndefine (extend bit-string len)\n if = len length bit-string \n [has correct length; return singleton set]\n cons bit-string nil\n append (extend append bit-string cons 0 nil len)\n (extend append bit-string cons 1 nil len)\n\ndefine extend\nvalue (lambda (bit-string len) (if (= len (length bit-st\n ring)) (cons bit-string nil) (append (extend (appe\n nd bit-string (cons 0 nil)) len) (extend (append b\n it-string (cons 1 nil)) len))))\n\n[extend all the bit strings in a given list to the same length]\ndefine (extend-all list len)\n if atom list nil\n append (extend car list len)\n (extend-all cdr list len)\n\ndefine extend-all\nvalue (lambda (list len) (if (atom list) nil (append (ex\n tend (car list) len) (extend-all (cdr list) len)))\n )\n\n[subtract set of intervals y from set of intervals x]\ndefine (subtract x y)\n if atom x nil \n if (is-in? car x y)\n [then] (subtract cdr x y)\n [else] cons debug display car x (subtract cdr x y)\n\ndefine subtract\nvalue (lambda (x y) (if (atom x) nil (if (is-in? (car x)\n y) (subtract (cdr x) y) (cons (debug (display (ca\n r x))) (subtract (cdr x) y)))))\n\n[\n Put it all together---Here is cover A_k\n covering all reals r having any n-bit prefix r_n \n with H(r_n) <= n - k.\n And we have measure \\mu A_k <= 2^{-k+c}.\n Actual proof uses A_{k+c}\n so that measure \\mu A_{k+c} <= 2^{-k}.\n Hence a real r with prefixes whose complexity\n dips arbitrarily far below their length will be\n in all the A_k and hence will not be M-L random.\n]\ndefine (A k)\n let intervals nil\n let (stage n)\n let compressible-strings (compressible-by-k n k)\n let intervals (process-all compressible-strings) \n if = n 12 stop! [to stop test run---remove if real thing]\n (stage + 1 n)\n [go!!!!!]\n (stage 0)\n\ndefine A\nvalue (lambda (k) ((' (lambda (intervals) ((' (lambda (s\n tage) (stage 0))) (' (lambda (n) ((' (lambda (comp\n ressible-strings) ((' (lambda (intervals) (if (= n\n 12) stop! (stage (+ 1 n))))) (process-all compres\n sible-strings)))) (compressible-by-k n k))))))) ni\n l))\n\n[k = compression amount = 8 bits]\n(A 8)\n\nexpression (A 8)\ndisplay (0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)\ndisplay (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)\ndisplay (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)\ndisplay (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)\nvalue stop!\n", "meta": {"hexsha": "a50ad8af737c75c46fef90fafd694679f0bd5e5a", "size": 8706, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/martin-lof2.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/martin-lof2.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/martin-lof2.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 34.5476190476, "max_line_length": 90, "alphanum_fraction": 0.596255456, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4880540012612277}} {"text": "# Synthetic Data Project\r\n# Efficient X'X construction Method for Solution of Large Observation, High Dimension Fixed Effects Models\r\n\r\n# Author:\r\n# Version: 5/14/2017\r\n\r\n# Copyright 2017\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\r\n# associated documentation files (the \"Software\"), to deal in the Software without restriction, including\r\n# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the\r\n# following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all copies or substantial\r\n# portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\r\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\nfeXTX <- function(data, Y, contX, fixedX, refLevel, interactionX=NULL, estBetaVar=\"none\", robustVarID=NULL,\r\n nCoreXTX, nCoreVar, solMethod=\"qr\") {\r\n\r\n ##############################################################################################################\r\n #### construct X'X and X'Y using variable cross products using sparse vector indices\r\n #### solve X'X*Beta = X'Y for Beta using qr decomposition\r\n #### estimate Beta standard errors using classic OLS inv(X'X), robust, or clustered based on specified ID \r\n ####\r\n #### fixed effect factors are expanded into a list of vectors, one for each non-reference level of the factor,\r\n #### each consisting of pointers to observations corresponding to the associated factor level\r\n ####\r\n #### factor level pointers are used in simple sum operations as an efficient alternative to exhaustive\r\n #### row-transpose, column products and is very efficient in high degree low density factor situations\r\n ####\r\n #### library dependencies: parallel (has been successfully tested with SNOW, also)\r\n ####\r\n #### this implementation is designed for MS Windows, which does not offer shared memory support, and involves\r\n #### (expensive execution and memory) export of objects to individual core memory for parallel operations\r\n ####\r\n #### for Unix implementation:\r\n #### create a \"forked\" type socket cluster, makeCluster(type=\"FORK\"), to enable shared access to memory and\r\n #### omit clusterExport operations that create unnecessary copies of large vectors\r\n ####\r\n #### parameters:\r\n #### data: data frame containing continuous, fixed effect, and dependent variables\r\n #### note that if fixed effects are supplied as factors then levels become factor values\r\n #### these are easily translated to original values with X[,levels(X)[i]]\r\n #### Y: name of column in data containing dependent numeric values\r\n #### contX: vector of column names of numeric data containing continuous independent values\r\n #### specify contX=NULL if there are no continuous variables in the model\r\n #### fixedX: vector of column names of data containing fixed effect independent values\r\n #### must be non-NULL (this is a fixed effects solution!)\r\n #### refLevel: vector of fixed effect reference levels, in order of fixedX columns\r\n #### interactionX: two column data frame or matrix of interaction pairs (each row constitutes a pair)\r\n #### note that if an interaction involves a continuous variable and a fixed effect then\r\n #### the continuous variable is moved to the left side if not already declared on the left\r\n #### this reduces the number of possible continuous-fixed interaction pairings from four\r\n #### (cc, cf, fc, ff) to three (cc, cf, ff)\r\n #### specify interactionX=NULL if there are no interactions in the model\r\n #### estBetaVar: beta variance estimation method\r\n #### \"stdOLS\" for standard OLS estimates [diagonal of inv(X'X)]\r\n #### \"robust\" for robust variance (independent, non-identically-distributed errors)\r\n #### \"clusterID\" for variance based on clustering around IDs specified in robustErrID\r\n #### \"i(x'x)x'uu'xi(x'x)\" to confirm analytical result of zero (see notes under variances)\r\n #### \"none\" for no variance estimates\r\n #### apologies, but robust, clustered, and i(x'x)x'uu'xi(x'x) variances are computed only\r\n #### for models with no interactions specified (this feature will be added in time)\r\n #### robustVarID: name of column in data containing vector of IDs used in clustered variance estimatation\r\n #### nCoreXTX: the number of cores to use in parallel XTX composition operations\r\n #### nCoreVar: the number of cores to use in parallel robust/clustered variance estimation operations\r\n #### solMethod: method of solving X'Xb=X'Y (\"qr\" for QR decomposition, \"chol\" for cholesky decomposition)\r\n ####\r\n #### the return object is a list with the following elements:\r\n #### status: completion status (\"\" or error message)\r\n #### Y: echo of input parameter\r\n #### contX: echo of input parameter\r\n #### fixedX: echo of input parameter\r\n #### refLevel: echo of input parameter\r\n #### interactionX: echo of input parameter\r\n #### nX: number of rows in data\r\n #### beta: OLS parameter estimates for Y ~ b0 + contX + indicator(fixedX|not ref)\r\n #### vBeta: parameter estimate variances\r\n #### estBetaVar: echo of input parameter\r\n #### XTX: X'X matrix (the primary effort of this function!)\r\n #### dimXTX: column (row) dimension of X'X\r\n #### rankXTX: rank of X'X as reported by qr() or chol()\r\n #### XTY: X'Y\r\n #### yEst: estimated Y values\r\n #### yVar: variance of observed Y's\r\n #### time: matrix of execution time, row 1 for compute, row 2 for memory export\r\n ##########################################################################################################\r\n\r\n ##########################################################################################################\r\n # to be implemented:\r\n # verify that specified fixed effect reference levels exists in supplied data\r\n # otherwise, a linear dependent condition exists between fixed effect(s) and the constant column\r\n # verify that interaction variables appear in data\r\n # verify that 0 < nCoreXTX and nCoreVar < available cores\r\n # convert order() calls in fixed effect indicator expansion to sort.list(factor(x), method=\"quick\", na.last=NA)\r\n ##########################################################################################################\r\n\r\n library(parallel)\r\n\r\n ###########################################################################################\r\n #### configure program objects and parameters\r\n ###########################################################################################\r\n\r\n tcompute <- rep(0, 5)\r\n tmem <- rep(0, 5)\r\n t0 <- proc.time()\r\n\r\n # verify that specified dependent, continuous, and fixed effect names are valid (length 1)\r\n # verify that specified dependent, continuous, and fixed effect vectors exist in supplied data\r\n # dependent var\r\n if(class(Y)==\"character\") {\r\n if(length(Y)==1) {\r\n if(length(which(colnames(data)==Y))!=0) {\r\n status <- \"\"\r\n } else {\r\n status <- paste(\"ERROR (feXTX) - Specified Y vector missing in source data (\", Y, \")\", sep=\"\")\r\n }\r\n } else {\r\n status <- \"ERROR (feXTX) - Invalid Y specification (single character string required)\"\r\n }\r\n } else {\r\n status <- \"ERROR (feXTX) - Invalid Y specification (single element character vector required)\"\r\n }\r\n # continuous vars\r\n # note that continuous vars are not a requirement (models may be specified with none)\r\n if(status==\"\" & !is.null(contX)) {\r\n if(class(contX)==\"character\") {\r\n if(length(contX)>0) {\r\n cid <- which(!contX %in% colnames(data))\r\n if(length(cid)==0) {\r\n status <- \"\"\r\n } else {\r\n status <- paste(\"ERROR (feXTX) - Specified contX vector(s) missing in source data (\",\r\n paste(contX[cid], collapse=\" \"), \")\", sep=\"\")\r\n }\r\n }\r\n } else {\r\n status <- \"ERROR (feXTX) - Invalid contX specification (vector of character names or NULL required)\"\r\n }\r\n }\r\n # fixed effects\r\n if(status==\"\") {\r\n if(class(fixedX)==\"character\") {\r\n if(length(fixedX)>0) {\r\n cid <- which(!fixedX %in% colnames(data))\r\n if(length(cid)==0) {\r\n status <- \"\"\r\n } else {\r\n status <- paste(\"ERROR (feXTX) - Specified fixedX vector(s) missing in source data (\",\r\n paste(fixedX[cid], collapse=\" \"), \")\", sep=\"\")\r\n }\r\n } else {\r\n status <- \"ERROR (feXTX) - Invalid fixedX specification (at least one fixed effect must be specified)\"\r\n }\r\n } else {\r\n status <- \"ERROR (feXTX) - Invalid fixedX specification (vector of character names required)\"\r\n }\r\n }\r\n \r\n if(status==\"\") {\r\n \r\n # count levels of fixed effects for ordering\r\n # moving high dimension effects to the end of list improves performance in paralell apply\r\n # operations since this distributes more levels to available cores in a give cross multiply\r\n fixedOrder <- order(apply(as.matrix(1:length(fixedX)), 1, function(j) length(unique(data[,fixedX[j]]))))\r\n fixedX <- fixedX[fixedOrder]\r\n refLevel <- refLevel[fixedOrder]\r\n\r\n # save input parameters (they are reported in the function output)\r\n fparams <- list(\"Y\"=Y, \"contX\"=contX, \"fixedX\"=fixedX)\r\n\r\n # save row dimension and number of continuous cols of design matrix\r\n # note that NULL contX has length of 0\r\n nX <- nrow(data)\r\n ncontX <- length(contX)\r\n \r\n # convert independent and dependent vars to numeric to avoid potential integer overflow\r\n if(length(contX)>0)\r\n contX <- apply(as.matrix(data[,contX]), 2, as.numeric)\r\n fixedX <- data.frame(data[,fixedX])\r\n colnames(fixedX) <- fparams[[\"fixedX\"]]\r\n Y <- as.numeric(data[,Y])\r\n\r\n # continue only if fixed effects declared\r\n if(ncol(fixedX)>0) {\r\n\r\n ##############################################################################################\r\n #### expand fixed effects into indicator columns for efficient (sparse, non-zero) addressing\r\n ##############################################################################################\r\n\r\n # construct sorted unique fixed effect value lists, excluding specified reference levels\r\n uFixedLevel <- lapply(1:ncol(fixedX), FUN=function(i) {\r\n x <- sort(unique(fixedX[,i]))\r\n x[which(x!=refLevel[i])]\r\n })\r\n\r\n # count levels by fixed effect\r\n nFixedLevel <- mapply(1:length(uFixedLevel), FUN=function(i) length(uFixedLevel[[i]]))\r\n\r\n # define function to execute parallel operations\r\n # this enables assigning the global environment as its env, which avoids parLapply's\r\n # insistence on exporting the entire local environment (it never exports .GlobalEnv,\r\n # why it exports anything is a puzzle since environment objects cannot be referenced\r\n # in parallel functions anway) \r\n # this is important if executing within a function with a local environment\r\n # since it prevents export of potentially large objects\r\n #plyXTX <- function(cl, ulev){\r\n # unique FE levels are distributed to cores, each sub-process returns a\r\n # vector of row positions that contain its corresponding level\r\n # parameters:\r\n # cl ............ cluster of cores on which to distribute individual lapply instances\r\n # uFixedLevel ... list of unique levels to identify observations by (using which)\r\n # levels are sequentially passed to the function as lev\r\n # function ...... apply which to fixed effects column searching for lev and return vector\r\n # of observation indices that contain lev\r\n # the return object is a list of which() results (vectors), one for each level in sequence of uFixedLevel\r\n # vector elements of the list are expected to be of non-uniform length, hence the requirement of collection\r\n # into a list, as opposed to a matrix or data frame \r\n # it is assumed that FEX has already been exported\r\n #parLapply(cl, ulev, function(lev) which(FEX==lev))\r\n #}\r\n #environment(plyXTX) <- .GlobalEnv\r\n\r\n # construct indicator indices (pointers to fixed effect entries with value of 1)\r\n # construct high dimension effect indicators in parallel (the cost of memory export and\r\n # parallel overhead is offset by efficiencies only when dimension is sufficiently high; the\r\n # chosen value of 35 is an approximate boundary based on empirical observation, converting\r\n # compute durations of several minutes into approximately one minute)\r\n # for very high dimension (thousands of levels) inefficiencies of which() become apparent and the\r\n # alternative of ordering observation indices by level sorting levels demonstrates improved\r\n # performance (note that ordering is expensive when compared to parallelized which() operations,\r\n # but is compensated for by very fast match() operations)\r\n # empirical tests have shown parallel which() operations involving millions of levels require\r\n # many hours to complete, while order() and match() require approximately 1.5 minutes for \r\n # 2.75 million levels in 25,000,000 observations (you read correctly) \r\n #cl <- makePSOCKcluster(rep(\"localhost\", nCoreXTX))\r\n kFE <- list()\r\n for(i in 1:length(uFixedLevel))\r\n # note the strict use of the sort.list(factor) method, which has been observed in all tests\r\n # to provide superior performance for all fixed effect dimensions\r\n if(nFixedLevel[i]>0) {\r\n # ordered levels with match() identify observation boundaries by level\r\n # do not index reference level observation levels\r\n #obsIndices <- intersect(order(fixedX[,i]), which(fixedX[,i]!=refLevel[i]))\r\n # sort.list, method=\"quick\" is fast, but requires numerics, hence the conversion of\r\n # fixedX[,i] to a factor then to an integer\r\n # intersect eliminates reference level observation indices\r\n obsIndices <- intersect(sort.list(as.integer(factor(fixedX[,i])), method=\"quick\", na.last=NA),\r\n which(fixedX[,i]!=refLevel[i]))\r\n # locate first observation index for each level\r\n firstObsIndex <- match(uFixedLevel[[i]], fixedX[obsIndices,i])\r\n # parse sets of observation indices for each non-reference level\r\n if(length(firstObsIndex)>1) {\r\n # first n-1 levels\r\n kFE[[i]] <- lapply(1:(length(firstObsIndex)-1),\r\n function(i) obsIndices[firstObsIndex[i]:(firstObsIndex[i+1]-1)])\r\n # last level\r\n kFE[[i]][[length(kFE[[i]])+1]] <- obsIndices[firstObsIndex[length(firstObsIndex)]:length(obsIndices)]\r\n } else {\r\n kFE[[i]] <- list(obsIndices)\r\n }\r\n #} else if(nFixedLevel[i]>35) {\r\n # parallel which() operations\r\n # creation of apparent duplicates of data frame vectors appears wasteful, but R does make\r\n # a separate copy of the referenced vectors unless modification is attempted, which we do not\r\n # tcompute <- tcompute + proc.time()-t0\r\n # t0 <- proc.time()\r\n # FEX <- fixedX[,i]\r\n # export from local environment, in case operating within a function\r\n # clusterExport(cl, \"FEX\", envir=environment())\r\n # tmem <- tmem + proc.time()-t0\r\n # t0 <- proc.time()\r\n # original parallel method - executed within a function causes export of entire local environment\r\n # we do not want to export anything beyond what has been explicitly exported above\r\n # kFE[[i]] <- parLapply(cl, uFixedLevel[[i]], function(lev) which(kFEX==lev))\r\n # lean method!\r\n # kFE[[i]] <- plyXTX(cl, uFixedLevel[[i]])\r\n #} else {\r\n # kFE[[i]] <- lapply(uFixedLevel[[i]], function(u) which(fixedX[,i]==u))\r\n }\r\n\r\n # release memory consumed by objects exported to parallel cores\r\n #stopCluster(cl)\r\n #rm(cl)\r\n gc()\r\n\r\n #############################################################################################################\r\n #### parse interaction specifications and standardize for analysis later\r\n #############################################################################################################\r\n\r\n # parse independent variables from interaction specification and identify as continuous (c) or fixed (f)\r\n # place continuous vars to left of relationship, if present\r\n # enumerate combinations of joint level values\r\n if(!is.null(interactionX)) {\r\n interactX <- do.call(rbind,\r\n mapply(1:nrow(interactionX), SIMPLIFY=F,\r\n FUN=function(i) {\r\n # classify both interacting variables as continuous or fixed effect\r\n # two possibilities for each\r\n vcl <- rbind(\r\n t(c(\"v\"=interactionX[i,1],\r\n \"cl\"=ifelse(interactionX[i,1] %in% colnames(contX), \"c\",\r\n ifelse(interactionX[i,1] %in% colnames(fixedX), \"f\", NA)))),\r\n t(c(\"v\"=interactionX[i,2],\r\n \"cl\"=ifelse(interactionX[i,2] %in% colnames(contX), \"c\",\r\n ifelse(interactionX[i,2] %in% colnames(fixedX), \"f\", NA)))))\r\n if(!is.na(vcl[1,2]) & !is.na(vcl[2,2])) {\r\n # swap v1 and v2 if v1 fixed and v2 continuous\r\n if(vcl[1,2]==\"f\" & vcl[2,2]==\"c\") {\r\n v <- vcl[1,]\r\n vcl[1,] <- vcl[2,]\r\n vcl[2,] <- v\r\n }\r\n # return col names, type, number of levels (product of number of levels of the cols)\r\n data.frame(\"x1\"=vcl[1,1], \"x2\"=vcl[2,1], \"class1\"=vcl[1,2], \"class2\"=vcl[2,2],\r\n \"nCrossLevel\"=ifelse(vcl[1,2]==\"c\", 1, nFixedLevel[which(colnames(fixedX)==vcl[1,1])]) *\r\n ifelse(vcl[2,2]==\"c\", 1, nFixedLevel[which(colnames(fixedX)==vcl[2,1])]))\r\n } else {\r\n data.frame(\"x1\"=NA, \"x2\"=NA, \"class1\"=NA, \"class2\"=NA, \"nCrossLevel\"=NA)\r\n }\r\n }))\r\n } else {\r\n interactX <- data.frame(\"x1\"=character(), \"x2\"=character(), \"class1\"=character(), \"class2\"=character(), \"nCrossLevel\"=numeric())\r\n }\r\n\r\n nInteractX <- nrow(interactX)\r\n\r\n #########################################################################################################################\r\n # begin construction of X'X\r\n # when interactions not specified or no errors in specification\r\n #########################################################################################################################\r\n\r\n if(length(which(is.na(interactX[,\"x1\"])))==0) {\r\n\r\n #######################################################################################################################\r\n #### enumerate variables in design matrix (including expanded fixed effects), generate empty X'X\r\n #### construct column names (for continuous and fixed effects vars, interactions done later)\r\n #######################################################################################################################\r\n \r\n # define pointers to beginning and ending rows and columns in X'X for each variable class\r\n # constant\r\n jb0 <- 1\r\n # continuous vars (note that if continuous vars not specified, ending column is 1)\r\n jcontX <- c(2, 1+ncontX)\r\n # fixed effects\r\n # cycle through FE specs and offset column positions from continuous prior FE levels\r\n jfixedX <- t(mapply(1:length(nFixedLevel),\r\n FUN=function(i) {\r\n # compute final position of current FE (final continuous pos + prior FE levels +\r\n # current FE levels)\r\n pos1 <- jcontX[2] + sum(nFixedLevel[1:i])\r\n # return beginning pos (final pos - number of levels + 1), ending pos\r\n c(pos1 - nFixedLevel[i] + 1, pos1)\r\n }))\r\n # interactions\r\n # cycle through interaction specs and offset column positions from fixed effects and prior interaction levels\r\n if(nInteractX>0)\r\n jinteractX <- t(mapply(1:nInteractX,\r\n FUN=function(i) {\r\n # compute final position of current interaction (final fixed effect pos + prior interaction\r\n # levels + current interaction levels)\r\n pos1 <- jfixedX[nrow(jfixedX),2] + sum(interactX[1:i,\"nCrossLevel\"])\r\n # return beginning pos (final pos - number of levels + 1), ending pos\r\n c(pos1 - interactX[i,\"nCrossLevel\"] + 1, pos1)\r\n }))\r\n\r\n # record X'X column dimension\r\n dimXTX <- 1+ncontX+sum(nFixedLevel)+sum(interactX[,\"nCrossLevel\"])\r\n\r\n # construct upper triangle of X'X\r\n # constant, continuous vars, and fixed effects\r\n\r\n # factors with greatest number of levels should appear last so that parallel ops (cores) are\r\n # distributed among longest lists\r\n XTX <- matrix(0, nrow=dimXTX, ncol=dimXTX, dimnames=list(1:dimXTX, 1:dimXTX))\r\n\r\n # col names (constant, continuous, and fixed effects)\r\n if(ncontX>0) {\r\n colnames(XTX)[1:(1+ncontX+sum(nFixedLevel))] <-\r\n c(\"b0\", paste(\"x-\", colnames(contX), sep=\"\"),\r\n unlist(lapply(1:length(uFixedLevel), FUN=function(i) paste(colnames(fixedX)[i], \"-\", uFixedLevel[[i]], sep=\"\"))))\r\n } else {\r\n colnames(XTX)[1:(1+sum(nFixedLevel))] <-\r\n c(\"b0\",\r\n unlist(lapply(1:length(uFixedLevel), FUN=function(i) paste(colnames(fixedX)[i], \"-\", uFixedLevel[[i]], sep=\"\"))))\r\n }\r\n\r\n #######################################################################################################################\r\n #### begin row-wise completion of upper triangle of X'X\r\n #### rows and cols corresponding to continuous and fixed effects variable products only\r\n #### cols corresponding to products of continuous/FE with interactions done in interaction section later\r\n #### use efficient (sparse) indicator columns for high dimension fixed effects and interactions\r\n #######################################################################################################################\r\n\r\n # row 1: sums of constant, continuous, and fixed effects columns\r\n # b0, sum of continuous vars, and count of fixed effect observations with non-0 level\r\n if(ncontX>0) {\r\n XTX[1,1:(1+ncontX+sum(nFixedLevel))] <- c( nX, apply(contX, 2, sum), unlist(lapply(kFE, function(k) lapply(k, length))))\r\n } else {\r\n XTX[1,1:(1+sum(nFixedLevel))] <- c( nX, unlist(lapply(kFE, function(k) lapply(k, length))))\r\n }\r\n\r\n # cross products of continuous vars with continuous variables and fixed effects\r\n # fixed effects indicators permit sum of var rows using pointers to indicator=1 rows\r\n if(ncontX>0)\r\n for(i in 1:ncontX) {\r\n i0 <- jcontX[1]+i-1\r\n # products of continuous vars with continuous vars\r\n # note that the cross product of individual columns (transpose of one times the other) within mapply\r\n # is significantly more efficient than multiplying the same colums as a set\r\n XTX[i0,i0:jcontX[2]] <- mapply(i:ncontX, FUN=function(j) t(contX[,i])%*%contX[,j])\r\n # products of continuous vars with fixed effects\r\n for(j in 1:length(kFE))\r\n XTX[i0,jfixedX[j,1]:jfixedX[j,2]] <- mapply(1:nFixedLevel[j], FUN=function(k) sum(contX[kFE[[j]][[k]],i]))\r\n }\r\n\r\n # cross products of fixed effects with fixed effects\r\n\r\n # define function to execute parallel operations, enabling it to be assigned to .GlobalEnv\r\n # see notes included in previous instance of function\r\n plyXTX <- function(cl, ife, ilev, jfe, njlev) {\r\n # note the following parApply parameters (example is for cross product of race and FY columns:\r\n # cl ....................... the cluster of cores\r\n # as.matrix(1:nFY) ......... a vector (but must be in matrix form) of FY indices\r\n # these are passed sequentially to the function as its first parameter\r\n # 1 ........................ pass FY indices row wise (sequentially down the single column we are supplying)\r\n # function(k, i) ........... function to execute for each k, i supplied\r\n # i ........................ the current loop index (current race)\r\n # note that a vector of length nFY is returned by parApply, one element for each k passed to the function\r\n # the jth element of this vector corresponds to the count of intersecting FY and jth bureau observations\r\n # that is, where both of current race and jth FY are 1\r\n # count of positions (observation indices) where both effects are 1\r\n # execute by fixed effect to take advantage of orthogonal properties of within effect columns\r\n parApply(cl, as.matrix(1:njlev), 1,\r\n function(jlev, ife, ilev, jfe) length(intersect(kFE[[ife]][[ilev]], kFE[[jfe]][[jlev]])), ife, ilev, jfe)\r\n }\r\n environment(plyXTX) <- .GlobalEnv\r\n\r\n # create parallel cluster and export indicator indices referenced in parallel routines\r\n # a little expensive, in time and memory, but compensated for through parallelization efficiencies\r\n tcompute <- tcompute + proc.time()-t0\r\n t0 <- proc.time()\r\n cl <- makePSOCKcluster(rep(\"localhost\", nCoreXTX))\r\n # export from local environment, in case executing within a function\r\n clusterExport(cl, \"kFE\", envir=environment())\r\n tmem <- tmem + proc.time()-t0\r\n t0 <- proc.time()\r\n # construct each row, filling columns to the right\r\n for(ife in 1:length(kFE))\r\n for(ilev in 1:nFixedLevel[ife]) {\r\n i0 <- jfixedX[ife,1]+ilev-1\r\n # within effect columns are mutually exclusive\r\n # diagonal positions (i=j) are frequencies for corresponding level, all other cross products (i<>j) are 0\r\n XTX[i0,i0] <- length(kFE[[ife]][[ilev]])\r\n # cross product with all levels of remaining fixed effects\r\n jfe <- ife+1\r\n while(jfe<=length(kFE)) {\r\n XTX[i0,jfixedX[jfe,1]:jfixedX[jfe,2]] <-\r\n # local environment export version\r\n # parApply(cl, as.matrix(1:nFixedLevel[[jfe]]), 1,\r\n # function(k, ife, ilev, jfe) length(intersect(kFE[[ife]][[ilev]], kFE[[jfe]][[k]])), ife, ilev, jfe)\r\n # replaced with non-export .GlobalEnv function\r\n plyXTX(cl, ife, ilev, jfe, nFixedLevel[[jfe]])\r\n jfe <- jfe+1\r\n }\r\n }\r\n\r\n gc()\r\n\r\n #######################################################################################################################\r\n #### continue with row-wise completion of upper triangle of X'X\r\n #### columns corresponding to continuous/FE row, interaction column cross products\r\n #### rows corresponding to interactions\r\n #### use efficient (sparse) indicator columns for high dimension fixed effects and interactions\r\n #######################################################################################################################\r\n\r\n if(nInteractX>0) {\r\n\r\n #####################################################################################################################\r\n #### construct names\r\n #####################################################################################################################\r\n\r\n colnames(XTX)[(2+ncontX+sum(nFixedLevel)):dimXTX] <-\r\n unlist(lapply(1:nInteractX,\r\n FUN=function(i)\r\n # if either of an interaction pair are continuous then v1 is continuous\r\n if(interactX[i,\"class1\"]==\"c\")\r\n if(interactX[i,\"class2\"]==\"c\")\r\n paste(interactX[i,\"x1\"], \"-\", interactX[i,\"x2\"], sep=\"\")\r\n else {\r\n # point to fixed effect levels for second x\r\n k <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n paste(interactX[i,\"x1\"], \"-\", interactX[i,\"x2\"], \"(\", uFixedLevel[[k]], \")\", sep=\"\")\r\n }\r\n else {\r\n # both must be fixed\r\n # point to fixed effect levels for both vars\r\n kf1 <- which(colnames(fixedX)==interactX[i,\"x1\"])\r\n kf2 <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n paste(sort(rep(paste(interactX[i,\"x1\"], \"(\", uFixedLevel[[kf1]], \")-\", sep=\"\"), length(uFixedLevel[[kf2]]))),\r\n paste(interactX[i,\"x2\"], \"(\", uFixedLevel[[kf2]], \")\", sep=\"\"), sep=\"\")\r\n }))\r\n\r\n #################################################################################################################\r\n #### row 1: sums of element-wise products of interaction cols\r\n #################################################################################################################\r\n\r\n # type of sum depends on whether both vars are continuous, one continuous and one fixed, or both fixed\r\n for(i in 1:nInteractX) {\r\n v11 <- interactX[i,\"x1\"]\r\n v12 <- interactX[i,\"x2\"]\r\n if(interactX[i,\"class1\"]==\"c\")\r\n if(interactX[i,\"class2\"]==\"c\")\r\n # two continuous vars, sum element-wise products\r\n XTX[1,jinteractX[i,1]:jinteractX[i,2]] <- sum(contX[,v11]*contX[,v12])\r\n else {\r\n # continuous with a fixed effect, sum continuous elements corresponding to non-zero elements of fixed eff\r\n # identify index of fixed effect\r\n kf1 <- which(colnames(fixedX)==v12)\r\n XTX[1,jinteractX[i,1]:jinteractX[i,2]] <-\r\n mapply(1:nFixedLevel[kf1], FUN=function(klev1) sum(contX[kFE[[kf1]][[klev1]],v11]))\r\n }\r\n else {\r\n # both must be fixed, count observations with 1 in both effects (intersection)\r\n # point to fixed effect levels for both vars\r\n kf1 <- which(colnames(fixedX)==v11)\r\n kf2 <- which(colnames(fixedX)==v12)\r\n # note that sums are produced for each FE 2 level nested within each FE 1 level\r\n XTX[1,jinteractX[i,1]:jinteractX[i,2]] <-\r\n unlist(lapply(1:nFixedLevel[kf1],\r\n FUN=function(klev1) unlist(lapply(1:nFixedLevel[kf2],\r\n FUN=function(klev2, klev1) length(intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])), klev1))))\r\n }\r\n }\r\n\r\n gc()\r\n\r\n #################################################################################################################\r\n #### cross products of continuous vars and interactions\r\n #### rows corresponding to continuous vars, cols corresponding to interactions\r\n #### these cols were left incomplete in continuous cross product section, above\r\n #################################################################################################################\r\n\r\n if(ncontX>0)\r\n for(i in 1:ncontX) {\r\n i0 <- jcontX[1]+i-1\r\n # compute cross-product of current continuous var with each interaction \r\n # type of multiply operation depends on whether both interaction vars are continuous,\r\n # one continuous and one fixed, or both fixed\r\n for(inter1 in 1:nInteractX) {\r\n # identify interaction variables\r\n v21 <- interactX[inter1,\"x1\"]\r\n v22 <- interactX[inter1,\"x2\"]\r\n if(interactX[inter1,\"class1\"]==\"c\")\r\n if(interactX[inter1,\"class2\"]==\"c\")\r\n # interaction involves two continuous vars, sum element-wise products\r\n XTX[i0,jinteractX[inter1,1]:jinteractX[inter1,2]] <-\r\n sum(contX[,i]*contX[,v21]*contX[,v22])\r\n else {\r\n # interaction involves a continuous and a fixed effect\r\n # sum product of current continuous var with interaction continuous var where fixed effect level is non-zero\r\n # identify index of fixed effect (to filter continuous rows)\r\n kf1 <- which(colnames(fixedX)==v22)\r\n # PERFORMANCE OPPORTUNITY USING PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n XTX[i0,jinteractX[inter1,1]:jinteractX[inter1,2]] <-\r\n mapply(1:nFixedLevel[kf1],\r\n FUN=function(klev1) sum(contX[kFE[[kf1]][[klev1]],i] * contX[kFE[[kf1]][[klev1]],v21]))\r\n }\r\n else {\r\n # both interaction vars fixed, sum continuous var with 1 in both fixed effects levels (intersection)\r\n # point to fixed effect levels for both fixed vars\r\n kf1 <- which(colnames(fixedX)==v21)\r\n kf2 <- which(colnames(fixedX)==v22)\r\n # note that sums are produced for each level of fixed effect 1 intersected with fixed effect 2\r\n # PERFORMANCE OPPORTUNITY USING PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n XTX[i0,jinteractX[inter1,1]:jinteractX[inter1,2]] <-\r\n unlist(lapply(1:nFixedLevel[kf1],\r\n FUN=function(klev1) unlist(lapply(1:nFixedLevel[kf2],\r\n FUN=function(klev2, klev1)\r\n sum(contX[intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]]),i]), klev1))))\r\n }\r\n }\r\n }\r\n\r\n gc()\r\n\r\n #################################################################################################################\r\n #### cross products of fixed effects and interactions\r\n #### rows corresponding to fixed effects, cols corresponding to interactions\r\n #### these cols were left incomplete in fixed effects cross product section, above\r\n #################################################################################################################\r\n\r\n # construct each row (level) of each fixed effect in sequence\r\n # note that execution reaches this point only when fixed effects have been declared\r\n # there is no need to test for length(kFE)>0)\r\n for(ife in 1:length(kFE))\r\n for(ilev in 1:nFixedLevel[ife]) {\r\n # XTX row pointer for current level of current fixed effect (row under construction)\r\n i0 <- jfixedX[ife,1]+ilev-1\r\n # observation indicators for current level of current fixed effect\r\n klev0 <- kFE[[ife]][[ilev]]\r\n # compute cross-product of current fixed effect var with each interaction \r\n # type of multiply operation depends on whether both interaction vars are continuous,\r\n # one continuous and one fixed, or both fixed\r\n for(inter in 1:nInteractX) {\r\n # identify interaction variables\r\n v21 <- interactX[inter,\"x1\"]\r\n v22 <- interactX[inter,\"x2\"]\r\n if(interactX[inter,\"class1\"]==\"c\")\r\n if(interactX[inter,\"class2\"]==\"c\")\r\n # interaction involves two continuous vars, sum element-wise products where\r\n # fixed level is non-zero\r\n XTX[i0,jinteractX[inter,1]:jinteractX[inter,2]] <-\r\n sum(contX[klev0,v21]*contX[klev0,v22])\r\n else {\r\n # interaction involves a continuous and a fixed effect\r\n # sum continuous var elements where both fixed effect levels are non-zero\r\n # identify index of interaction fixed effect (to intersect with current fixed effect)\r\n kf1 <- which(colnames(fixedX)==interactX[inter,\"x2\"])\r\n # PERFORMANCE OPPORTUNITY USING PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n XTX[i0,jinteractX[inter,1]:jinteractX[inter,2]] <-\r\n mapply(1:nFixedLevel[kf1],\r\n FUN=function(klev) sum(contX[intersect(klev0, kFE[[kf1]][[klev]]),v21]))\r\n }\r\n else {\r\n # both interaction vars fixed, count elements in intersection of all three fixed effects\r\n # point to fixed effect levels for both interaction fixed vars\r\n kf1 <- which(colnames(fixedX)==interactX[inter,\"x1\"])\r\n kf2 <- which(colnames(fixedX)==interactX[inter,\"x2\"])\r\n # note that sums are produced for each level of fixed effect 1 intersected with fixed effect 2\r\n # PERFORMANCE OPPORTUNITY USING PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n XTX[i0,jinteractX[inter,1]:jinteractX[inter,2]] <-\r\n unlist(lapply(1:nFixedLevel[kf1],\r\n FUN=function(klev1) unlist(lapply(1:nFixedLevel[kf2],\r\n FUN=function(klev2, klev1)\r\n length(intersect(intersect(klev0, kFE[[kf1]][[klev1]]), kFE[[kf2]][[klev2]])), klev1))))\r\n }\r\n }\r\n }\r\n\r\n gc()\r\n\r\n #################################################################################################################\r\n #### cross products of interactions with interactions\r\n #### upper triangle rows and cols corresponding to cross products of interactions\r\n #### note that interaction cols of X'X were assigned in order of appearance in the interaction specification\r\n #### proceed in this order, computing cross products for an interaction with itself and trailing (to the right)\r\n #### interactions only\r\n #### note that interaction standardization, above, assures that interactions are of type\r\n #### continuous-continuous (cc), continuous-fixed (cf), or fixed-fixed (ff)\r\n #################################################################################################################\r\n\r\n # interaction cross products are the product of two interactions, each of which are the cross product of\r\n # two continuous vars, one continuous and one fixed effect, or two fixed effects vars \r\n # this gives a total of nine possible interaction cross product types: (cc, cf, ff) X (cc, cf, ff), each with\r\n # a distinct optimal addressing method \r\n\r\n # PERFORMANCE OPPORTUNITIES:\r\n # CONSOLIDATE COMMON SOLUTIONS (FOR INSTANCE, [c1Xc2]X[c3XF1] has solution structure of [c3Xf1]X[c1Xc2]\r\n # DO NOT EVALUATE OFF-DIAGONAL ELEMENTS (DIFFERING LEVELS) WHEN A FIXED EFFECT APPEARS MULTIPLE TIMES,\r\n # AS IN [c1Xf1]X[f1Xf2], SINCE WITHIN FIXED EFFECT VECTORS ARE ORTHOGONAL\r\n # PARALLELIZE!\r\n\r\n # inspect each declared interaction and execute optimal cross product methods involving current and\r\n # subsequent interactions\r\n # note that there exist nine permutations of interaction X interaction products (cc, cf, ff) X (cc, cf, ff)\r\n # identify mode of left and right operand then produce cross products exploiting intersections of non-zero\r\n # indices of all factors on either side of product\r\n # note that X'X rows to populate correspond to beginning and ending positions in jinteractX for left side\r\n # operand, while beginning and ending cols correspond to jinteractX values for right side operand\r\n\r\n # cycle through all interactions\r\n # note that, in order for processing to be at this point, the specified model includes interactions\r\n # therefore, there is no need to test nInteractX > 0 \r\n for(inter1 in 1:nInteractX)\r\n # cycle through current and all subsequent interactions\r\n # note that the first cycle involves the product of the left side interaction with itself\r\n for(inter2 in inter1:nInteractX) {\r\n\r\n # identify left (v11, v12) and right (v21 and v22) interacting vars\r\n v11 <- interactX[inter1,\"x1\"]\r\n v12 <- interactX[inter1,\"x2\"]\r\n v21 <- interactX[inter2,\"x1\"]\r\n v22 <- interactX[inter2,\"x2\"]\r\n\r\n # identify column boundaries of X'X elements to be updated\r\n # row boundaries are dependent on left side interaction type (cc, cf, ff)\r\n j0 <- jinteractX[inter2,1]\r\n j1 <- jinteractX[inter2,2]\r\n\r\n if(interactX[inter1,\"class1\"]==\"c\" & interactX[inter1,\"class2\"]==\"c\") {\r\n\r\n # interaction 1 (left operand) involves two continuous vars (cc)\r\n # use element-wise products of v11 and v12\r\n\r\n # identify X'X row offset\r\n i0 <- jinteractX[inter1,1]\r\n\r\n if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"c\") {\r\n # cc X cc\r\n # interaction 2 (right operand) involves two continuous vars, use element-wise products of v21 and v22\r\n XTX[i0,j0] <- sum(contX[,v11]*contX[,v12]*contX[,v21]*contX[,v22])\r\n } else if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"f\") {\r\n # cc X cf\r\n # right side interaction contains a fixed effect\r\n # use product of v11, v12, and v21 corresponding to non-zero indices of v22\r\n # identify position in list of non-zero FE indices corresponding to v22\r\n kf1 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <- mapply(1:nFixedLevel[[kf1]],\r\n FUN=function(klev1)\r\n # note that v11, v12, and v21 are continuous\r\n sum(contX[kFE[[kf1]][[klev1]],v11] *\r\n contX[kFE[[kf1]][[klev1]],v12] *\r\n contX[kFE[[kf1]][[klev1]],v21]))\r\n } else {\r\n # cc X ff\r\n # both vars in right side (v21, v22) interaction must be fixed effects since standardization places\r\n # any continuous combination ahead of fXf\r\n # use cross product of v11 and v12 in intersection of non-zero v21 and v22\r\n # note that X'X interaction columns have been constructed in v1-level, v2-level sequence\r\n # sums are produced for each combination of levels of v21 and v22\r\n # PERFORMANCE OPPORTUNITY: USE PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n # point to fixed effect levels for both interaction fixed vars\r\n kf1 <- which(colnames(fixedX)==v21)\r\n kf2 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <-\r\n unlist(lapply(1:nFixedLevel[kf1],\r\n FUN=function(klev1)\r\n unlist(lapply(1:nFixedLevel[kf2],\r\n FUN=function(klev2, klev1) {\r\n klev <- intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])\r\n sum(contX[klev,v11]*contX[klev,v12])\r\n }, klev1))))\r\n }\r\n\r\n } else if(interactX[inter1,\"class1\"]==\"c\" & interactX[inter1,\"class2\"]==\"f\") {\r\n\r\n # interaction 1 involves one continuous var (v11) and one fixed var (v12) (cf)\r\n # use element-wise products involving v11 where v12 non-zero\r\n\r\n # identify non-zero FE indices corresponding to fixed var in left side interaction (v12)\r\n kf1 <- which(colnames(fixedX)==v12)\r\n\r\n # cycle through all levels of v12\r\n for(klev1 in 1:nFixedLevel[kf1]) {\r\n\r\n # identify X'X row offset for current level of left side interaction FE (v12)\r\n i0 <- jinteractX[inter1,1] + klev1 - 1\r\n\r\n # update X'X cols based on right hand interaction style\r\n\r\n if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"c\") {\r\n # cf X cc\r\n # interaction 2 (right side) involves two continuous vars\r\n # use element-wise products of v11, v21, and v22 where v12 non-zero\r\n XTX[i0,j0] <- sum(contX[kFE[[kf1]][[klev1]],v11] *\r\n contX[kFE[[kf1]][[klev1]],v21] *\r\n contX[kFE[[kf1]][[klev1]],v22])\r\n } else if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"f\") {\r\n # cf X cf\r\n # right side interaction contains a fixed effect\r\n # use cross product of v11 and v21 in intersection of non-zero v12 and v22\r\n # PERFORMANCE OPPORTUNITIES:\r\n # USE PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n # DO NOT EVALUATE CROSS OFF DIAGONAL CROSS PRODUCTS WHEN LEFT AND RIGHT INTERACTIONS SHARE A FE\r\n # identify position in list of non-zero FE indices for v22\r\n kf2 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <- mapply(1:nFixedLevel[[kf2]],\r\n FUN=function(klev2) {\r\n # note that v11 and v21 are continuous\r\n klev <- intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])\r\n sum(contX[klev,v11] * contX[klev,v21])\r\n })\r\n\r\n } else {\r\n # cf X ff\r\n # both vars in right side (v21, v22) interaction must be fixed effects since standardization places\r\n # any continuous combination ahead of fXf\r\n # use v11 elements in intersection of non-zero v12, v21, and v22\r\n # note that X'X interaction columns have been constructed in v1-level, v2-level sequence\r\n # sums are produced for each combination of levels of v21 and v22\r\n # PERFORMANCE OPPORTUNITIES:\r\n # USE PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n # DO NOT EVALUATE CROSS OFF DIAGONAL CROSS PRODUCTS WHEN LEFT AND RIGHT INTERACTIONS SHARE A FE\r\n # point to fixed effect levels for both right side interaction fixed vars\r\n kf2 <- which(colnames(fixedX)==v21)\r\n kf3 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <-\r\n unlist(lapply(1:nFixedLevel[kf2],\r\n FUN=function(klev2)\r\n unlist(lapply(1:nFixedLevel[kf3],\r\n FUN=function(klev3, klev2)\r\n sum(contX[intersect(\r\n intersect(kFE[[kf1]][[klev1]],\r\n kFE[[kf2]][[klev2]]),\r\n kFE[[kf3]][[klev3]]),v11])), klev2)))\r\n }\r\n\r\n }\r\n\r\n } else if(interactX[inter1,\"class1\"]==\"f\" & interactX[inter1,\"class2\"]==\"f\") {\r\n\r\n # interaction 1 involves two fixed vars (v11 and v12) (ff)\r\n # use sums of intersections of all four vars\r\n\r\n # identify non-zero FE indices corresponding to fixed var in left side interaction (v12)\r\n kf1 <- which(colnames(fixedX)==v11)\r\n kf2 <- which(colnames(fixedX)==v12)\r\n\r\n # cycle through v11, v12 levels in X'X row order (all levels of v12 nested within all levels of v11)\r\n\r\n for(klev1 in 1:nFixedLevel[kf1])\r\n for(klev2 in 1:nFixedLevel[kf2]) {\r\n\r\n # identify X'X row offset for current level of v12 within current level of v11\r\n i0 <- jinteractX[inter1,1] + (klev1-1)*nFixedLevel[kf2] + klev2 - 1\r\n\r\n # identify joint non-zero elements of current levels of v11 and v12\r\n klev0 <- intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])\r\n\r\n # update X'X cols based on right hand interaction style\r\n\r\n if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"c\") {\r\n # ff X cc\r\n # interaction 2 (right side) involves two continuous vars\r\n # use element-wise products of v21 and v22, indices from intersection of non-zero v11, v12\r\n XTX[i0,j0] <- sum(contX[klev0,v21] * contX[klev0,v22])\r\n } else if(interactX[inter2,\"class1\"]==\"c\" & interactX[inter2,\"class2\"]==\"f\") {\r\n # ff X cf\r\n # right side interaction contains a fixed effect\r\n # use sum of v21 in intersection of non-zero v11, v12, and v22\r\n # PERFORMANCE OPPORTUNITIES:\r\n # USE PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n # DO NOT EVALUATE CROSS OFF DIAGONAL CROSS PRODUCTS WHEN LEFT AND RIGHT INTERACTIONS SHARE A FE\r\n # identify position in list of non-zero FE indices for v22\r\n kf3 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <- mapply(1:nFixedLevel[[kf3]],\r\n FUN=function(klev3) sum(contX[intersect(klev0, kFE[[kf3]][[klev3]]),v21]))\r\n } else {\r\n # ff X ff\r\n # both vars in right side (v21, v22) interaction are fixed effects\r\n # use count of observations in inteaction of v11, v12, v21, and v22\r\n # note that X'X interaction columns have been constructed in v1-level, v2-level sequence\r\n # counts are produced for each combination of levels of v21 and v22\r\n # PERFORMANCE OPPORTUNITIES:\r\n # USE PARLAPPLY IF INTERACTION LEVELS > OPTIMAL THRESHOLD\r\n # DO NOT EVALUATE CROSS OFF DIAGONAL CROSS PRODUCTS WHEN LEFT AND RIGHT INTERACTIONS SHARE A FE\r\n # point to fixed effect levels for both right side interaction fixed vars\r\n kf3 <- which(colnames(fixedX)==v21)\r\n kf4 <- which(colnames(fixedX)==v22)\r\n XTX[i0,j0:j1] <-\r\n unlist(lapply(1:nFixedLevel[kf3],\r\n FUN=function(klev3)\r\n unlist(lapply(1:nFixedLevel[kf4],\r\n FUN=function(klev4, klev3)\r\n length(intersect(intersect(klev0, kFE[[kf3]][[klev3]]),\r\n kFE[[kf4]][[klev4]])), klev3))))\r\n }\r\n\r\n }\r\n\r\n } # if inter1 cc, cf, ff\r\n\r\n } # for(inter2 in inter1:nInteractX)\r\n\r\n } # if(nInteractX>0)\r\n\r\n gc()\r\n\r\n ###################################################################################################################\r\n #### X'X upper triangle complete\r\n #### complete lower triangle (below diagonal) using transpose of upper\r\n ###################################################################################################################\r\n\r\n # note that lower triangle elements presently are all 0\r\n # note, also, the subtraction of the duplicate diagonal\r\n XTX <- XTX+t(XTX)-diag(x=diag(XTX), nrow=dimXTX)\r\n\r\n ###################################################################################################################\r\n #### construct X'Y\r\n ###################################################################################################################\r\n\r\n # intercept position\r\n XTY <- sum(Y)\r\n\r\n # transpose of continuous variables times Y\r\n # mapply of individual vector operations outperforms t(vectors)%*%Y\r\n if(ncontX>0)\r\n XTY <- c(XTY, mapply(1:ncontX, FUN=function(j) t(contX[,j])%*%Y))\r\n\r\n # fixed effects, sums of Y corresponding to FE=1 positions\r\n # compute t(FE indicator by level)%*%Y for each fixed effect\r\n # use previously constructed fixed effect indicator columns (kFE)\r\n # note that execution reaches this point only when fixed effects declared (no need to \r\n # test for non-zero length(kFE)\r\n for(i in 1:length(kFE))\r\n XTY <- c(XTY, mapply(1:nFixedLevel[i], FUN=function(k) sum(Y[kFE[[i]][[k]]])))\r\n\r\n # interactions\r\n # compute t(interaction columns)%*%Y for each interaction\r\n # there exists three possible variable combinations: continuous X continuous (cc),\r\n # continuous X fixed (cf), and fixed X fixed (ff)\r\n # use previously constructed FE indicator columns (kFE) for cf and ff cases\r\n if(nInteractX>0)\r\n for(i in 1:nInteractX)\r\n if(interactX[i,\"class1\"]==\"c\" & interactX[i,\"class2\"]==\"c\") {\r\n # interaction of type cc, simple cross product\r\n XTY <- c(XTY, sum(contX[,interactX[i,\"x1\"]] * contX[,interactX[i,\"x2\"]] * Y))\r\n } else if(interactX[i,\"class1\"]==\"c\" & interactX[i,\"class2\"]==\"f\") {\r\n # interaction of type cf, return product of elements of continuous X and Y where\r\n # fixed effect is non-zero, evaluate for each level of fixed effect\r\n # identify position of fixed effect\r\n # note that, due to interaction standardization, FE always in var 2 of interaction for type cf\r\n kf1 <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n XTY <- c(XTY, mapply(1:nFixedLevel[kf1],\r\n FUN=function(klev) sum(contX[kFE[[kf1]][[klev]],interactX[i,\"x1\"]] * Y[kFE[[kf1]][[klev]]])))\r\n } else {\r\n # interaction of type ff, return sum of Y elements where both fixed effects levels non-zero\r\n # note that one sum is produced for each level of FE2 nested within each level of FE1\r\n # identify positions of fixed effects\r\n kf1 <- which(colnames(fixedX)==interactX[i,\"x1\"])\r\n kf2 <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n XTY <- c(XTY, unlist(lapply(1:nFixedLevel[kf1], FUN=function(klev1)\r\n unlist(lapply(1:nFixedLevel[kf2], FUN=function(klev2, klev1)\r\n sum(Y[intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])]), klev1 )))) )\r\n }\r\n\r\n ###################################################################################################################\r\n #### coefficient solution\r\n ###################################################################################################################\r\n\r\n # solve X'X*Beta = X'Y, for Beta\r\n # simple, obsolete method: beta <- solve(XTX, XTY, singular.ok=T)\r\n if(tolower(solMethod==\"qr\")) {\r\n # QR decomposition - will solve for parameter estimates even when XTX is singular\r\n # return QR solution along with rank\r\n # rank < XTX dimension => non-unique estimate solution (estimates for all but one\r\n # dependent column are returned as NA)\r\n qrXTX <- qr(XTX)\r\n rankXTX <- qrXTX$rank\r\n beta <- qr.coef(qrXTX, XTY)\r\n } else if(tolower(solMethod)==\"chol\") {\r\n # Cholesky decomposition\r\n # solve Ab=Y, where C'C=A\r\n # C'Cb=Y => C'z=Y (solve for z) and Cb=z (solve for b)\r\n # note that upper.tri applied before transpose\r\n chXTX <- chol(XTX)\r\n beta <- backsolve(chXTX, forwardsolve(chXTX, XTY, upper.tri=T, transpose=T), upper.tri=T)\r\n names(beta) <- colnames(XTX)\r\n rankXTX <- dimXTX # need to adapt to rank of chol [attr(chXTX, \"rank\")]\r\n } else {\r\n status <- \"Error: Invalid solution method specified\"\r\n }\r\n \r\n ###################################################################################################################\r\n #### estimate y values\r\n ###################################################################################################################\r\n\r\n # force collinear parameters (all but one) to 0\r\n betaLI <- beta\r\n betaLI[which(is.na(beta))] <- 0\r\n\r\n # constant\r\n yEst <- rep(betaLI[1], nX)\r\n\r\n # continuous variables\r\n if(ncontX>0)\r\n yEst <- yEst + as.matrix(contX)%*%betaLI[jcontX[1]:jcontX[2]]\r\n\r\n # fixed effects\r\n # FE existence already verified\r\n for(i in 1:length(kFE))\r\n for(j in 1:nFixedLevel[[i]])\r\n yEst[kFE[[i]][[j]]] <- yEst[kFE[[i]][[j]]] + betaLI[jfixedX[i,1]+j-1]\r\n\r\n # interactions\r\n # multiply interaction coefficients by computed interaction levels and add to Y\r\n # there exists three possible variable combinations: continuous X continuous (cc),\r\n # continuous X fixed (cf), and fixed X fixed (ff)\r\n # use previously constructed FE indicator columns (kFE) for cf and ff cases\r\n if(nInteractX>0)\r\n for(i in 1:nInteractX)\r\n if(interactX[i,\"class1\"]==\"c\" & interactX[i,\"class2\"]==\"c\") {\r\n # interaction of type cc, element-wise products\r\n yEst <- yEst + betaLI[jinteractX[i,1]] * contX[,interactX[i,\"x1\"]] * contX[,interactX[i,\"x2\"]]\r\n } else if(interactX[i,\"class1\"]==\"c\" & interactX[i,\"class2\"]==\"f\") {\r\n # interaction of type cf, update Y positions corresponding to non-zero FE elements\r\n # note that, due to interaction standardization, FE always in var 2 of interaction for type cf\r\n kf1 <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n for(klev1 in 1:nFixedLevel[kf1])\r\n yEst[kFE[[kf1]][[klev1]]] <- yEst[kFE[[kf1]][[klev1]]] +\r\n betaLI[jinteractX[i,1]+klev1-1] *\r\n contX[kFE[[kf1]][[klev1]],interactX[i,\"x1\"]]\r\n } else {\r\n # interaction of type ff, update positions of Y corresponding to joint non-zero FE elements\r\n # cycle through each level of FE2 within each level of FE1\r\n # add FE1 X FE2 coefficient to joint non-zero observation positions\r\n # identify positions of fixed effects\r\n kf1 <- which(colnames(fixedX)==interactX[i,\"x1\"])\r\n kf2 <- which(colnames(fixedX)==interactX[i,\"x2\"])\r\n for(klev1 in 1:nFixedLevel[kf1])\r\n for(klev2 in 1:nFixedLevel[kf2]) {\r\n klev3 <- intersect(kFE[[kf1]][[klev1]], kFE[[kf2]][[klev2]])\r\n yEst[klev3] <- yEst[klev3] + betaLI[jinteractX[i,1] + (klev1-1)*nFixedLevel[kf2] + klev2 - 1]\r\n }\r\n }\r\n\r\n ###################################################################################################################\r\n #### estimate y-variance\r\n ###################################################################################################################\r\n\r\n yVar <- sum((Y-yEst)**2)/(nX-dimXTX)\r\n\r\n ###################################################################################################################\r\n #### X'X construction, beta solution, and y estimates are complete\r\n ###################################################################################################################\r\n\r\n status <- \"\"\r\n\r\n } else {\r\n\r\n status <- \"ERROR (feXTX) - Invalid or unknown vectors in interaction specification\"\r\n\r\n }\r\n\r\n\r\n } else {\r\n\r\n status <- \"ERROR (feXTX) - No fixed effects specified in model\"\r\n\r\n }\r\n\r\n # retain cluster if robust error option specified, sice fixed effect indicators used in parallel there\r\n if(tolower(estBetaVar)!=\"robust\") {\r\n stopCluster(cl)\r\n rm(cl)\r\n }\r\n\r\n gc()\r\n\r\n }\r\n \r\n if(status==\"\") {\r\n\r\n ###################################################################################################################\r\n #### estimate parameter variances, if requested\r\n ###################################################################################################################\r\n\r\n if(tolower(estBetaVar)==\"stdols\") {\r\n\r\n # standard OLS estimates, assuming homoskedastic, iid errors\r\n # var(beta) = (variance of y estimates) * inverse(X'X)\r\n # verify nonsingularity of X'X, report NA otherwise\r\n if(rankXTX==dimXTX) {\r\n if(solMethod==\"qr\") {\r\n vBeta <- yVar*diag(qr.solve(XTX))\r\n } else if(solMethod==\"chol\") {\r\n # note the use of prior cholesky decomposition\r\n vBeta <- yVar*diag(chol2inv(chXTX))\r\n } else {\r\n vBeta <- rep(NA,dimXTX)\r\n }\r\n } else {\r\n vBeta <- rep(NA,dimXTX)\r\n }\r\n\r\n } else if(tolower(estBetaVar)==\"robust\" & nInteractX==0) {\r\n\r\n # robust, uncorrelated, heteroskedastic (independent, non-identically-distributed) errors\r\n # estimate robust variances (square of standard errors) as v(beta) = i(X'X)*X'uu'X*i(X'X)\r\n # where i() is the inverse function and u is the vector of observation response to predicted\r\n # value errors (y - yEstimate)\r\n # this derives from the expression for parameter variances from the normal OLS equaions\r\n # uu' forms an n X n diagonal error variance-covariance matrix with all off-diagonal elements\r\n # set to 0, which asserts the assumption of independent (uncorrelated) errors\r\n # but, since the diagonal elements are expected to be non-constant, this method models\r\n # parameter standard errors in a heteroskedastic (independent, but not identically distributed)\r\n # error setting \r\n\r\n # since X'uu'X is symmetric, construct upper triangle only then copy transpose to lower triangle\r\n\r\n # verify nonsingularity of X'X, report NA otherwise\r\n if(rankXTX==dimXTX) {\r\n\r\n # create (0) X'uu'X matrix\r\n XuuX <- matrix(data=rep(0, dimXTX*dimXTX), nrow=dimXTX)\r\n\r\n # construct errors\r\n u <- (Y-yEst)**2\r\n\r\n # construct X'uu'X\r\n\r\n # row 1, constant, continuous vars, fixed effects\r\n if(ncontX>0) {\r\n XuuX[1,] <- c(sum(u), apply(as.matrix(1:ncontX), 1, function(i) sum(contX[,i]*u)),\r\n unlist(lapply(1:length(kFE), function(ife)\r\n unlist(lapply(1:nFixedLevel[ife], function(lev) sum(u[kFE[[ife]][[lev]]]))))))\r\n } else {\r\n XuuX[1,] <- c(sum(u), unlist(lapply(1:length(kFE), function(ife)\r\n unlist(lapply(1:nFixedLevel[ife], function(lev) sum(u[kFE[[ife]][[lev]]]))))))\r\n }\r\n\r\n # rows for continuous variables\r\n if(ncontX>0)\r\n for(i in 1:ncontX) {\r\n i0 <- jcontX[1]+i-1\r\n # products of continuous vars with continuous vars\r\n XuuX[i0,i0:jcontX[2]] <- mapply(i:ncontX, FUN=function(j) sum(contX[,i]*contX[,j]*u))\r\n # products of continuous vars with fixed effects\r\n for(ife in 1:length(kFE))\r\n XuuX[i0,jfixedX[ife,1]:jfixedX[ife,2]] <-\r\n apply(as.matrix(1:nFixedLevel[ife]), 1, \r\n function(lev) sum(contX[kFE[[ife]][[lev]],i]*u[kFE[[ife]][[lev]]]))\r\n }\r\n\r\n # rows for fixed effects\r\n # note that kFE has already been exported to parallel cluster (in XTX construction)\r\n clusterExport(cl, \"u\", envir=environment())\r\n # define function to execute parallel operations, enabling it to be assigned to .GlobalEnv\r\n # see notes included in previous instance of function\r\n plyVar <- function(cl, ife, ilev, jfe, njlev) {\r\n parApply(cl, as.matrix(1:njlev), 1,\r\n function(jlev, ife, ilev, jfe) sum(u[intersect(kFE[[ife]][[ilev]], kFE[[jfe]][[jlev]])]), ife, ilev, jfe)\r\n }\r\n environment(plyVar) <- .GlobalEnv\r\n # construct each row, filling columns to the right\r\n for(ife in 1:length(kFE))\r\n for(ilev in 1:nFixedLevel[ife]) {\r\n i0 <- jfixedX[ife,1]+ilev-1\r\n # within effect columns are mutually exclusive\r\n # diagonal positions (i=j) are 1 for observations in current effect and level, others (i<>j) are 0\r\n XuuX[i0,i0] <- sum(u[kFE[[ife]][[ilev]]])\r\n # cross product with all levels of remaining fixed effects\r\n jfe <- ife+1\r\n while(jfe<=length(kFE)) {\r\n XuuX[i0,jfixedX[jfe,1]:jfixedX[jfe,2]] <-\r\n # local environment export version\r\n #apply(as.matrix(1:nFixedLevel[[jfe]]), 1,\r\n # function(jlev, ife, ilev, jfe) sum(u[intersect(kFE[[ife]][[ilev]], kFE[[jfe]][[jlev]])]), ife, ilev, jfe)\r\n # parallel version\r\n plyVar(cl, ife, ilev, jfe, nFixedLevel[[jfe]])\r\n jfe <- jfe+1\r\n }\r\n }\r\n\r\n # complete lower triangle of XuuX\r\n # note that lower triangle elements presently are all 0\r\n # note, also, the subtraction of the duplicate diagonal\r\n XuuX <- XuuX+t(XuuX)-diag(x=diag(XuuX), nrow=nrow(XuuX))\r\n\r\n # finally, execute i(X'X)*X'uu'X*i(X'X)\r\n XTXi <- solve(XTX)\r\n vBeta <- diag(XTXi%*%XuuX%*%XTXi)\r\n\r\n gc()\r\n\r\n } else {\r\n\r\n vBeta <- rep(NA, dimXTX)\r\n\r\n }\r\n\r\n } else if(tolower(estBetaVar)==\"cluster\" & nInteractX==0) {\r\n\r\n # heteroskedastic, correlated within cluster, independent (uncorrelated) between cluster,\r\n # non-identically-distributed (heteroskedastic) errors\r\n # estimate clustered standard errors using v(beta) = i(X'X)*X'uu'X*i(X'X),\r\n # where i() implies inverse and uu' is the var-cov matrix of observation to estimate errors (y-yest)\r\n # this is the expression for var(beta) from ordinary least squares estimates of beta\r\n # on the assumption that X is non-stochastic and uu' is an estimate of error covariance and, further,\r\n # that covariance observed within clusters (groups) estimates that in the population while covariance between\r\n # groups is 0, uu' is altered such that all off-diagonal inter-group elements, that is uu'(ij) where\r\n # indices i and j belong to different groups, are set to 0\r\n # uu' has the form:\r\n #\r\n # uu'(g1) 0 0 0 0 0 ... 0\r\n # 0 uu'(g2) 0 0 0 0 ... 0\r\n # 0 0 uu'(g3) 0 0 0 ... 0\r\n # ... 0\r\n # 0 0 0 0 ... uu'(gk)\r\n #\r\n # where uu'(gi) is the n(gi) X n(gi) sub-matrix of the error covariace matrix corresponding to group i\r\n # note that with this construction of uu', X'uu'X is the sum (over all groups i) of (Xgi)'*uu'(gi)*Xgi,\r\n # where Xgi and uu'(gi) are the rows of X and sub-matrix of uu' corresponding to group i\r\n # [to see this, imagine multiplying X' by uu' and consider the effect of uu' elements of rows that do not\r\n # correspond to a particular group - each resulting column corresponds to products from a single group -\r\n # then multiplying that by X (each row belongs to a single group) gives a p X p sum of individual group products]\r\n\r\n # note that (Xg)'*ug = [(ug)'*Xg]', making (Xg)'*uu'(g)*Xg symmetric\r\n # also, (ug)'*Xg is a 1 X p vector, where p is the column dimension of X (the design matrix)\r\n # for each ID, construct v = (ug)'*Xg then use it to compute v'v = (Xg)'*uu'(g)*Xg\r\n\r\n # verify nonsingularity of X'X, report NA otherwise\r\n if(rankXTX==dimXTX) {\r\n\r\n # calculate errors\r\n u <- Y-yEst\r\n\r\n # generate fixed effect level indicators (pointers to levels for each observation)\r\n # note that reference levels contain NA\r\n xind <- mapply(1:ncol(fixedX), FUN=function(i) match(fixedX[,i], uFixedLevel[[i]]))\r\n colnames(xind) <- colnames(fixedX)\r\n\r\n # function to generate p X p sum of (Xg)'uu'(Xg) sub-matrices for pseudo IDs in specified range\r\n # X'uu'X = the sum of all individual (Xg)'uu'(Xg) sub-matrices\r\n # note that the upper triangle and diagonal of (symmetric) (Xg)'uu'(Xg) are returned\r\n XguuXg <- function(idboundk) {\r\n\r\n # create empty matrix to accumulate sum of group product matrices into\r\n XuuX <- matrix(data=rep(0, dimXTX*dimXTX), nrow=dimXTX)\r\n\r\n # Accumulate (Xg)'uu'(Xg) sub-matrices for individual pseudo IDs\r\n for(i in idbound[idboundk, 1]:idbound[idboundk, 2]) {\r\n\r\n # identify observations in current cluster ID group (all belonging to ith ID)\r\n # note that kg <- which(robustVarID==id) is very inefficient (hours with certain data sets) and is\r\n # replaced with the following\r\n # the first observation index for the current (ith) ID is in pidObsIndices[pidFirstObsIndex[i]]\r\n # the last observation index is in idObsIndices[idFirstObsIndex[i+1]-1] (this is the obs index\r\n # prior to the first index for ID i+1, the next ID)\r\n # the final index for the final ID is in the last position of idObsIndices since no ID follows\r\n # all observation indices between the first and final for an ID belong to that ID\r\n if(i0) {\r\n utXg <- c(sum(u[kg]), t(u[kg])%*%contX[kg,], rep(0, dimXTX-ncontX-1))\r\n } else {\r\n utXg <- c(sum(u[kg]), rep(0, dimXTX-1))\r\n }\r\n\r\n # get fixed effect level indices for each observation\r\n # note that reference levels have index NA\r\n kv <- matrix(xind[kg,], ncol=ncol(xind))\r\n\r\n # accumulate j=1..ng observation errors into positions corresponding to each FE level index\r\n # NA (reference level) indices are excluded\r\n # note that jfixedX[kv2,1]-1 are pointers into X for the first level of each fixed effect\r\n for(j in 1:length(kg)) {\r\n kv2 <- which(!is.na(kv[j,]))\r\n kv2 <- jfixedX[kv2,1]-1+kv[j,kv2]\r\n utXg[kv2] <- utXg[kv2] + u[kg][j]\r\n }\r\n\r\n # accumulate sub-matrix products\r\n # it is tempting to execute XuuX <- XuuX + utXg%*%t(utXg), but this is computationally expensive\r\n # (adds approximately 0.08 seconds per ID in trials) and involves products of which over 99% involve a factor of 0\r\n # it also calculates products in both upper and lower triangles of XuuX, when XuuX is known to be symmetric\r\n # alternative: use products of non-zero entries of utXg and accumulate by index into appropriate rows and columns of XuuX\r\n # complete the upper triangle only, it will be copied to the lower triangle later\r\n # get non-zero indices\r\n kv <- as.vector(which(utXg!=0))\r\n # permutate all non-zero indices\r\n kv <- cbind(sort(rep(kv, length(kv))), kv)\r\n # retain non-zero indices (ij) where j>=i\r\n kv <- kv[kv[,2]>=kv[,1],]\r\n # accumulate non-zero (ug)'Xg index products into cells of XuuX corresponding to those indices (upper triangle)\r\n XuuX[kv] <- XuuX[kv] + utXg[kv[,1]]*utXg[kv[,2]]\r\n\r\n }\r\n\r\n return(XuuX)\r\n\r\n }\r\n\r\n # list IDs\r\n uid <- sort(unique(data[,robustVarID]))\r\n\r\n # construct boundaries of ID indices, one for each core\r\n nid <- length(uid)\r\n nidblock <- as.integer(nid/nCoreVar)\r\n idbound <- cbind(0:(nCoreVar-1)*nidblock+1, (1:nCoreVar)*nidblock) \r\n idbound[nCoreVar,2] <- nid\r\n\r\n # generate observation pointers by ID\r\n # note that this, somewhat complicated method, replaces use of which(robustVarID==id) in the\r\n # XguuXg function due to its extreme inefficiency (adds hours to execution time with millions of observations)\r\n # the following method generates a matrix of observation indices for each ID in ID order\r\n # list observation indices in ID order\r\n # ordering of IDs requires approximately one minute (25,000,000 observations)\r\n # match requires approximately three seconds (fast, huh?)\r\n idObsIndices <- order(data[,robustVarID])\r\n # locate first observation index for each ID\r\n idFirstObsIndex <- match(uid, data[idObsIndices,robustVarID])\r\n\r\n # create parallel cluster\r\n # release existing cluser, if present\r\n tcompute <- tcompute + proc.time()-t0\r\n t0 <- proc.time()\r\n if(exists(\"cl\"))\r\n stopCluster(cl)\r\n cl <- makePSOCKcluster(rep(\"localhost\", nCoreVar))\r\n # export objects referenced in parallel instructions\r\n # from local environment, in case executing within a function\r\n clusterExport(cl, c(\"idbound\", \"xind\", \"dimXTX\", \"u\", \"ncontX\", \"jfixedX\", \"contX\", \"idObsIndices\",\r\n \"idFirstObsIndex\", \"nid\"), envir=environment())\r\n tmem <- tmem + proc.time()-t0\r\n t0 <- proc.time()\r\n\r\n gc()\r\n \r\n # define function to execute parallel operations\r\n # this enables assigning the global environment as its env, which avoids parLapply's\r\n # insistence on exporting the entire local environment (it never exports .GlobalEnv,\r\n # why it exports anything is a puzzle since environment objects cannot be referenced\r\n # in parallel functions anyway) \r\n # this is important if executing within a function with a local environment\r\n # since it prevents export of potentially large objects\r\n plyVar <- function(cl, idbound, XguuXg) parLapply(cl, 1:nrow(idbound), XguuXg)\r\n environment(plyVar) <- .GlobalEnv\r\n\r\n # call, in parallel, the ID-sub-matrix function\r\n # parLapply returns a list, the ith element containing X'uu'X sub-matrix for ID (group) i\r\n # Reduce element-wise sums the sub-matrices, giving the complete (upper triangle of) X'uu'X\r\n XuuX <- Reduce(\"+\", plyVar(cl, idbound, XguuXg))\r\n\r\n # release parallel cores and memory\r\n stopCluster(cl)\r\n rm(cl)\r\n gc()\r\n\r\n # complete lower triangle of XuuX\r\n # note that lower triangle elements presently are all 0\r\n # note, also, the subtraction of the duplicate diagonal\r\n XuuX <- XuuX+t(XuuX)-diag(x=diag(XuuX), nrow=nrow(XuuX))\r\n\r\n XTXi <- solve(XTX)\r\n vBeta <- diag(XTXi%*%XuuX%*%XTXi)\r\n\r\n } else {\r\n\r\n vBeta <- rep(NA, dimXTX)\r\n\r\n }\r\n \r\n } else if(tolower(estBetaVar)==\"i(x'x)x'uu'xi(x'x)\" & nInteractX==0) {\r\n\r\n # this option is added as a test of interior X and u=(y-yEst) structure\r\n # analytically, X'u = X'(y-yEst) = X'y - X'X*beta = X'[X*inverse(X'X)X'y) = X'y - X'y = 0\r\n # so the following should result in a vector of length p (one element for each beta) each\r\n # containing near zero entries\r\n # note that X'uu'X is (n X n) symmetric, resulting from the product of X'u (n X 1) and u'X (1 X n)\r\n # method: construct X'u then assign product of elements i and j of X'u to cell ij of X'uu'X\r\n # since X'uu'X is symmetric, construct upper triangle only then copy transpose to lower triangle\r\n\r\n # verify nonsingularity of X'X, report NA otherwise\r\n if(rankXTX==dimXTX) {\r\n\r\n # create empty X'u vector and X'uu'X matrix\r\n Xu <- vector(\"numeric\", dimXTX)\r\n XuuX <- matrix(data=rep(0, dimXTX*dimXTX), nrow=dimXTX)\r\n\r\n # construct errors\r\n u <- Y-yEst\r\n\r\n # construct X'u\r\n # position 1 of X'u, the sum of u elements since col 1 of X = 1\r\n Xu[1] <- sum(u)\r\n\r\n # continuous vars\r\n if(contX>0)\r\n Xu[jcontX[1]:jcontX[2]] <- t(contX)%*%u\r\n\r\n # fixed effect columns contain either 0 or 1 making cross products, for a given level,\r\n # the sum of u elements corresponding to non-zero elements of the fixed effect level\r\n # cycle through all fixed effects, cross multiplying each level\r\n for(i in 1:length(kFE))\r\n Xu[jfixedX[i,1]:jfixedX[i,2]] <- mapply(1:nFixedLevel[i], FUN=function(j) sum(u[kFE[[i]][[j]]]))\r\n\r\n # X'u is composed, now cross multiply X'u and u'X\r\n # compose ij pairs, where j>=i (upper triangle with diagonal)\r\n ij <- cbind(sort(rep(1:dimXTX, dimXTX)), 1:dimXTX)\r\n ij <- ij[which(ij[,2]>=ij[,1]),]\r\n\r\n # copy X'u cross products to X'uu'X\r\n XuuX[ij] <- Xu[ij[,1]]*Xu[ij[2]]\r\n\r\n # complete lower triangle of XuuX\r\n # note that lower triangle elements presently are all 0\r\n # note, also, the subtraction of the duplicate diagonal\r\n XuuX <- XuuX+t(XuuX)-diag(x=diag(XuuX), nrow=nrow(XuuX))\r\n\r\n # finally, execute i(X'X)*X'uu'X*i(X'X)\r\n XTXi <- solve(XTX)\r\n vBeta <- diag(XTXi%*%XuuX%*%XTXi)\r\n\r\n gc()\r\n\r\n } else {\r\n\r\n vBeta <- rep(NA, dimXTX)\r\n\r\n }\r\n \r\n } else {\r\n\r\n vBeta <- rep(NA, dimXTX)\r\n\r\n }\r\n\r\n names(vBeta) <- colnames(XTX)\r\n status <- \"\"\r\n\r\n }\r\n\r\n ###################################################################################################################\r\n #### processing complete\r\n #### clean up and report results\r\n ###################################################################################################################\r\n\r\n if(status==\"\") {\r\n \r\n if(exists(\"cl\")) {\r\n stopCluster(cl)\r\n rm(cl)\r\n }\r\n gc()\r\n tcompute <- tcompute+proc.time()-t0\r\n #print(paste(\"compute time (user, sys, elapsed): \", round(tcompute[\"user.self\"], 2), \", \", round(tcompute[\"sys.self\"], 2), \", \", round(tcompute[\"elapsed\"], 2), sep=\"\"))\r\n #print(paste(\"mem export time (user, sys, elapsed): \", round(tmem[\"user.self\"], 2), \", \", round(tmem[\"sys.self\"], 2), \", \", round(tmem[\"elapsed\"], 2), sep=\"\"))\r\n list(\"status\"=status, \"Y\"=fparams$Y, \"contX\"=fparams$contX, \"fixedX\"=fparams$fixedX, \"refLevel\"=refLevel,\r\n \"interactionX\"=interactionX, \"nX\"=nX, \"beta\"=beta, \"vBeta\"=vBeta, \"estBetaVar\"=estBetaVar,\r\n \"XTX\"=XTX, \"dimXTX\"=dimXTX, \"rankXTX\"=rankXTX, \"XTY\"=XTY, \"yEst\"=as.vector(yEst), \"yVar\"=yVar,\r\n \"time\"=rbind(tcompute, tmem))\r\n\r\n } else {\r\n \r\n gc()\r\n list(\"status\"=status)\r\n \r\n }\r\n \r\n}\r\n", "meta": {"hexsha": "7fa44e5ae5a32ce3a38ff4d7b2c381438fe0c453", "size": 81896, "ext": "r", "lang": "R", "max_stars_repo_path": "VerificationServer/FixedEffectsMatrixSolution.r", "max_stars_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_stars_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VerificationServer/FixedEffectsMatrixSolution.r", "max_issues_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_issues_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VerificationServer/FixedEffectsMatrixSolution.r", "max_forks_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_forks_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.6362378976, "max_line_length": 174, "alphanum_fraction": 0.5299770441, "num_tokens": 18561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48787351267263607}} {"text": "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset.seed(4)\n\n## Pad with zeros on both ends\npad = function(x, pad.size=500) {\n c(rep(0,pad.size), x, rep(0,pad.size))\n}\n\n## Create a randomized impulse by creating white noise, down-filtering and windowing\nimpulse = function(n=32, f=n/2, pad.size=500) {\n t = 1:(2*n) - n - 1 + 1e-8\n v = sin(t/f * pi)/t * cos(t/2/n*pi)^2\n n = pad(rnorm(length(t)), n * 3)\n convolve(n,v, type=\"filter\")\n}\n\n## Encode a windowed time-series using a specified dictionary\nencode = function(win, dict) {\n ## largest dot product is most aligned centroid, size gives window scale\n dot = win %*% dict\n ## return nearest centroid in column 1, scale in column 2\n t(apply(dot, 1, function(v) {\n mx = max(abs(v))\n k = which(abs(v)==mx)[1]\n c(k, v[k])\n }))\n}\n\n## Reconstructs a signal from an encoded form\ndecode = function(data, dict) {\n n = dim(data)[1]\n r = rep(0, (n+1)*16)\n ## step a window at a time\n for (i in 1:n) {\n k = data[i,1]\n v = data[i,2]\n off = (i-1)*16\n ## add in current centroid after scaling and shifting it\n r[off + 1:32] = r[off + 1:32] + dict[,k] * v\n }\n r\n}\n\n## Computes the reconstruction error by reconstructing and measuring\nreconstruction.error = function(data, dict) {\n rx = window(data)\n kx = encode(rx, dict)\n rz = decode(kx, dict)\n n = length(rz)\n mean(abs(data[15 + 1:n] - rz)) \n}\n\n## Generates a randomized time series\ngenerate = function(windows, v.1, v.2) {\n ## signal is original all zeros\n r = rep(0, 16 * windows)\n t = 0\n while (t < length(r) - length(v.1)) {\n ## next pulse start point is exponentially distributed\n t = t + -0.5 * length(v.1) * log(runif(1))\n ## flip a coin to pick which pulse we want\n flip = rnorm(1) > 0\n n1 = floor(t)\n n2 = n1 + length(v.1) - 1\n if (n2 > length(r)) {\n return(r)\n }\n r[n1:n2] = r[n1:n2] + v.1*flip + v.2*(1-flip)\n }\n r\n}\n\n## Vector magnitude\nmag = function(v) {\n sqrt(sum(v^2))\n}\n\n## Stack up a time series as overlapping window segments\nwindow = function(data, window.size=32) {\n ## how many windows?\n n = floor(2 * length(data)/window.size)\n ## the window shape\n w = sin((0:(window.size-1))/window.size * pi)^2\n ## for each row index, apply the window function to a sub-sequence\n t(apply(matrix(1:(n-window.size/2), ncol=1), 1, function(i) {\n n = i*16\n w * data[n:(n+window.size-1)]\n }))\n}\n\n## Generate the data\nv.1 = impulse(64, 8)\nv.2 = impulse(64, 8)\n\ntraining.data = generate(10000, v.1, v.2)\ntest.data = generate(10000, v.1, v.2)\n\n## Go ahead and window once to help with all the clustering\nrx = t(apply(window(training.data), 1, function(v){v/(1e-100+mag(v))}))\n\nk.10 = kmeans(rx, centers=10, nstart=10)\nc.10 = apply(k.10$centers,1,function(v){v/mag(v)})\nx.10 = reconstruction.error(training.data, c.10)\ny.10 = reconstruction.error(test.data, c.10)\nprint(10)\n\nk.100 = kmeans(rx, centers=100, nstart=10, iter.max=20)\nc.100 = apply(k.100$centers,1,function(v){v/(1e-100 + mag(v))})\nx.100 = reconstruction.error(training.data, c.100)\ny.100 = reconstruction.error(test.data, c.100)\nprint(100)\n\nk.200 = kmeans(rx, centers=200, nstart=10, iter.max=30)\nc.200 = apply(k.200$centers,1,function(v){v/(1e-100 + mag(v))})\nx.200 = reconstruction.error(training.data, c.200)\ny.200 = reconstruction.error(test.data, c.200)\nprint(200)\n\nk.500 = kmeans(rx, centers=500, nstart=10, iter.max=30)\nc.500 = apply(k.500$centers,1,function(v){v/(1e-100 + mag(v))})\nx.500 = reconstruction.error(training.data, c.500)\ny.500 = reconstruction.error(test.data, c.500)\nprint(500)\n\nk.1000 = kmeans(rx, centers=1000, nstart=5, iter.max=10)\nc.1000 = apply(k.1000$centers,1,function(v){v/(1e-100 + mag(v))})\nx.1000 = reconstruction.error(training.data, c.1000)\ny.1000 = reconstruction.error(test.data, c.1000)\nprint(1000)\n\nk.2000 = kmeans(rx, centers=2000, nstart=5, iter.max=10)\nc.2000 = apply(k.2000$centers,1,function(v){v/(1e-100 + mag(v))})\nx.2000 = reconstruction.error(training.data, c.2000)\ny.2000 = reconstruction.error(test.data, c.2000)\nprint(2000)\n\n\nreconstruct.plot = function () {\n plot(test.data[1:2000], type='l', xlab=\"Time\", ylab=NA, main=\"Time series training data (first 2000 samples)\",\n lwd=3)\n rex = window(test.data)\n re.data = decode(encode(rex, c.1000), c.1000)\n lines(15 + 1:2000, re.data[1:2000], col='red')\n lines(15 + 1:2000, test.data[15+1:2000]-re.data[1:2000]-1, col='blue')\n legend(800, 2.2, legend=c(\"Test data\", \"Reconstruction\", \"Error\"), col=c(\"black\", \"red\", \"blue\"), pch=21, lty=1, cex=0.8)\n}\n\ntime.series.error.plot = function() {\n plot(c(10,100,200,500,1000,2000), c(x.10, x.100, x.200, x.500, x.1000, x.2000), \n type='b', lwd=2, xlab=\"Centroids\", ylab=\"MAV Error\",\n ylim=c(0,0.15),\n main=\"Reconstruction error for time-series data\")\n\n lines(c(10,100,200,500,1000,2000), c(y.10, y.100, y.200, y.500, y.1000, y.2000), \n type='b', lwd=2, col='red')\n\n legend(1000, 0.15, legend=c(\"Training data\", \"Held-out data\"), col=c(\"black\", \"red\"), pch=21, lwd=2)\n}\n\ntime.series.plot = function() {\n plot(training.data[1:2000], type='l', xlab=\"Time\", ylab=NA, main=\"Time series training data (first 2000 samples)\")\n}\n\npdf(file=\"time-series-errors.pdf\", width=5, height=5)\ntime.series.error.plot()\ndev.off()\n \npng(file=\"images/time-series-errors.png\", width=400, height=400)\ntime.series.error.plot()\ndev.off()\n \npdf(file=\"time-series.pdf\", width=5, height=5)\ntime.series.plot()\ndev.off()\n\npng(file=\"images/time-series.png\", width=400, height=400)\ntime.series.plot()\ndev.off()\n\npdf(file=\"time-series-reconstruction.pdf\", width=5, height=5)\nreconstruct.plot()\ndev.off()\n\npng(file=\"images/time-series-reconstruction.png\", width=400, height=400)\nreconstruct.plot()\ndev.off()\n", "meta": {"hexsha": "9de3327514ff9230f6840e2615b6ea19f91899ff", "size": 6709, "ext": "r", "lang": "R", "max_stars_repo_path": "time-series.r", "max_stars_repo_name": "tdunning/k-means-auto-encoder", "max_stars_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-06-12T11:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T16:48:03.000Z", "max_issues_repo_path": "time-series.r", "max_issues_repo_name": "tdunning/k-means-auto-encoder", "max_issues_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-10T20:10:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-16T12:13:50.000Z", "max_forks_repo_path": "time-series.r", "max_forks_repo_name": "tdunning/k-means-auto-encoder", "max_forks_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T14:20:04.000Z", "avg_line_length": 33.3781094527, "max_line_length": 125, "alphanum_fraction": 0.6352660605, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4873437510586977}} {"text": "\nbirth_death_fishing = function( selection=\"stan_code\", fit=NULL, vn=NULL, sppoly=NULL, poly_match=NULL, time_match=NULL, catches=NULL, wgts=NULL, ... ) {\n\n message(\" \")\n message(\"todo :: use carstm estimated numbers as IOA\")\n message(\"todo :: add zero-inflation\")\n message(\" \")\n\n if (grepl(\"parameters\", selection) ) {\n\n\n return(params)\n }\n\n\n if (grepl(\"stan_code\", selection) ) {\n\n # simple discrete ode form, spatially explicit (au), birth/death separated\n # n[au,t] = n [au,t−1] + b[au] n[au,t−1] (1 − b[au,t−1] ) − c [au,t−1]\n\n out = \"\n data {\n int N; // no. years\n int U; // no. regions\n int CAT[U,N];\n int IOA[U,N];\n }\n\n transformed data {\n real eps = 1e-9;\n real IOAmin[U];\n real IOAmax[U];\n real IOAmed[U];\n real IOAerror[U];\n for (u in 1:U) {\n IOAmax[u] = 1e9;\n IOAmin[u] = 1e-9;\n for (n in 1:N) {\n real test = IOA[u,n] + CAT[u,n] ;\n if (test > IOAmax[u]) IOAmax[u] = test;\n if (test <= IOAmin[u]) IOAmin[u] = test;\n }\n IOAmed[u] = (IOAmax[u] + IOAmin[u])/2.0 ;\n IOAerror[u] = IOAmax[u] * 0.05 ; // 5% error.. estim of sd\n }\n }\n\n parameters {\n real X[U,N];\n real g[U,N];\n real m[U];\n real K[U];\n real psd[U]; // process error\n real res[U,N];\n real ressd[U]; /////\n real gsd[U]; /////\n real q[U];\n real msd; ////\n real qsd;\n }\n\n model {\n psd ~ normal(0.0, 0.2) ;\n qsd ~ normal(0.0, 0.05); // ranges from 0.5 to 1.5\n ressd ~ normal(0.0, 0.05) ;\n msd ~ normal(0.0, 0.05) ;\n gsd ~ normal(0.0, 0.05) ; // 0.1\n m ~ normal(0.0, msd);\n q ~ normal(1.0, qsd );\n\n for (u in 1:U) {\n g[u,] ~ normal( 0.0, gsd[u] );\n K[u] ~ normal( IOAmax[u], IOAerror[u] ) ;\n X[u,1] ~ normal( 0.5, psd[u] ) ;\n for (n in 1:N) {\n res[u,n] ~ normal( q[u] * (X[u,n] - CAT[u,n]/K[u] ), ressd[u] ); // no catch observation error .. keep separate to force positive value\n IOA[u,n] ~ poisson( K[u] * res[u,n] ); // survey index observation model\n if (n < N) {\n X[u,n+1] ~ normal( X[u,n] * (1.0 + g[u,n] - m[u]*X[u,n] ) - CAT[u,n]/K[u], psd[u] ) ; //process model\n }\n }\n }\n }\n \"\n\n if (grepl(\"stan_code_testing_hurdle\", selection) ) {\n\n # simple discrete ode form, spatially explicit (au), birth/death separated\n # n[au,t] = n [au,t−1] + b[au] n[au,t−1] (1 − b[au,t−1] ) − c [au,t−1]\n\n out = \"\n functions {\n int num_zero(int[] y) { // count no of zero-values\n int nz = 0;\n for (n in 1:size(y))\n if (y[n] == 0)\n nz += 1;\n return nz;\n }\n }\n\n data {\n int N; // no. years\n int U; // no. regions\n int CAT[U,N];\n int IOA[U,N];\n }\n\n transformed data {\n real eps = 1e-9;\n real IOAmin[U];\n real IOAmax[U];\n real IOAmed[U];\n real IOAerror[U];\n int N0[U]; // no of zero-values in each au\n int Ngt0[U]; // no of non-zero values in each au\n int IOA_nz[U], N - num_zero(y); // values of IOA > 0\n for (u in 1:U) {\n N0[u] = num_zero( IOA[u,] );\n Ngt0[u] = N - N0[u];\n IOAmax[u] = 1e9;\n IOAmin[u] = 1e-9;\n for (n in 1:N) {\n real test = IOA[u,n] + CAT[u,n] ;\n if (test > IOAmax[u]) IOAmax[u] = test;\n if (test <= IOAmin[u]) IOAmin[u] = test;\n }\n IOAmed[u] = (IOAmax[u] + IOAmin[u])/2.0 ;\n IOAerror[u] = IOAmax[u] * 0.05 ; // 5% error.. estim of sd\n }\n }\n\n parameters {\n real X[U,N];\n real g[U,N];\n real m[U];\n real K[U];\n real psd[U]; // process error\n real res[U,N];\n real ressd[U]; /////\n real gsd[U]; /////\n real q[U];\n real msd; ////\n real qsd;\n }\n\n model {\n psd ~ normal(0.0, 0.2) ;\n qsd ~ normal(0.0, 0.05); // ranges from 0.5 to 1.5\n ressd ~ normal(0.0, 0.05) ;\n msd ~ normal(0.0, 0.05) ;\n gsd ~ normal(0.0, 0.05) ; // 0.1\n m ~ normal(0.0, msd);\n q ~ normal(1.0, qsd );\n\n for (u in 1:U) {\n g[u,] ~ normal( 0.0, gsd[u] );\n K[u] ~ normal( IOAmax[u], IOAerror[u] ) ;\n X[u,1] ~ normal( 0.5, psd[u] ) ;\n for (n in 1:N) {\n res[u,n] ~ normal( q[u] * (X[u,n] - CAT[u,n]/K[u] ), ressd[u] ); // no catch observation error .. keep separate to force positive value\n IOA[u,n] ~ poisson( K[u] * res[u,n] ); // survey index observation model\n if (n < N) {\n X[u,n+1] ~ normal( X[u,n] * (1.0 + g[u,n] - m[u]*X[u,n] ) - CAT[u,n]/K[u], psd[u] ) ; //process model\n }\n }\n }\n }\n \"\n }\n\n return(out)\n }\n\n\n\n if (grepl(\"stochastic_simulation\", selection) ) {\n\n ellp = list(...)\n attach(ellp)\n\n Xdim = dim(X)\n nau = Xdim[1]\n ntu = Xdim[2]\n nsim = Xdim[3]\n\n if (!exists(\"ST\")) ST = c(\n \"@ -> b*X -> X\" ,\n \"X -> d*(X/K)*X -> @\",\n \"X -> f*X -> catch\"\n )\n\n if (!exists(\"SC\")) SC = c( \"X\", \"catch\" )\n\n if (!exists(\"nthreads\")) nthreads = 4\n if (!exists(\"nprojections\")) nprojections = 30\n if (!exists(\"istart\")) istart = ntu\n\n nssims = min( 10, nsim )\n iss = sample.int( nsim, nssims )\n\n sim = array( NA, dim=c( nssims, length(SC), nprojections, nau ) )\n tspan = 1:nprojections\n\n for (iau in 1:nau) {\n\n # posterior subset\n aup = data.frame(\n X = as.integer( floor(abundance[iss, iau, istart]) ),\n catch = as.integer( rep(0, length(X))),\n f = f[iss, iau, istart],\n b = g[iss, iau, istart],\n m = m[iss, iau, istart],\n K = as.integer( K[iss, iau] )\n )\n\n # simulate over each posterior subset\n for (i in 1:nssims) {\n sim[i,,iau] = slot( run( model=mparse(\n transitions = ST,\n compartments = SC,\n gdata = c( K=aup$K[i], g=aup$g[i], m=aup$m[i], f=aup$f[i] ),\n u0 = aup[i, SC],\n tspan = tspan\n ), threads=nthreads\n ), \"U\")[]\n }\n\n }\n\n detach(ellp)\n out = list( sim=sim, iss =iss)\n\n return(out)\n }\n\n\n\n if (grepl(\"posteriors\", selection) ) {\n\n ellp = list(...)\n attach(ellp)\n\n posteriors = stan_extract( as_draws_df( fit$draws() ) ) # extract all posteriors = mcmc posteriors from STAN\n\n Xdim = dim(posteriors$X)\n nsim = Xdim[1]\n nau = Xdim[2]\n ntu = Xdim[3]\n\n posteriors$numbers = posteriors$X[] * 0\n for ( i in 1:ntu ) posteriors$numbers[,,i] = posteriors$X[,,i] * posteriors$K[] # X is fraction of K\n\n posteriors$fraction.fished = posteriors$X[] * 0\n for ( i in 1:nsim ) posteriors$fraction.fished[i,,] = catches[] / posteriors$numbers[i,,]\n\n posteriors$fishing.mortality = 1.0 - posteriors$fraction.fished[]\n posteriors$fishing.mortality[ which(posteriors$fishing.mortality < 1e-6) ] = 1e-6\n posteriors$fishing.mortality = -log( posteriors$fishing.mortality )\n posteriors$fishing.mortality[ !is.finite(posteriors$fishing.mortality)] = 0\n\n # K = array( K, dim=c(dim(K), nsim) )\n # MSY = r * K / 4.0 ; # maximum height of of the latent productivity (yield)\n # aMSY = K /2.0 ; # numbers at MSY\n # FMSY = 2.0 * MSY / K ; # fishing mortality at MSY\n\n # add other params computed post-mcmc from conditional distributions\n # convert num to biomass\n posteriors$biomass = posteriors$numbers[] * NA # in kg\n for (i in 1:nsim) posteriors$biomass[i,,] = posteriors$numbers[i,,] * wgts[]\n\n detach(ellp)\n return( posteriors )\n }\n\n\n\n if (grepl(\"summary\", selection)) {\n\n sims = lapply( apply( posteriors$biomass, 1,\n function(biom) {\n biom = as.matrix(biom)\n biom[!is.finite(biom)] = NA\n o = list()\n o$cfaall = colSums( biom * sppoly$au_sa_km2/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n o$cfanorth = colSums( biom * sppoly$cfanorth_surfacearea/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n o$cfasouth = colSums( biom * sppoly$cfasouth_surfacearea/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n o$cfa23 = colSums( biom * sppoly$cfa23_surfacearea/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n o$cfa24 = colSums( biom * sppoly$cfa24_surfacearea/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n o$cfa4x = colSums( biom * sppoly$cfa4x_surfacearea/ sppoly$au_sa_km2/10^6, na.rm=TRUE )\n return(o)\n }\n ), data.frame )\n\n RES = data.frame( index = 1:dim(posteriors$biomass)[3] )\n\n RES$cfaall = apply( sapply( sims, function(x) x[,\"cfaall\"], simplify =TRUE), 1, mean)\n RES$cfaall_sd = apply( sapply( sims, function(x) x[,\"cfaall\"], simplify =TRUE), 1, sd )\n RES$cfaall_median = apply( sapply( sims, function(x) x[,\"cfaall\"], simplify =TRUE), 1, median )\n RES$cfaall_lb = apply( sapply( sims, function(x) x[,\"cfaall\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfaall_ub = apply( sapply( sims, function(x) x[,\"cfaall\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n RES$cfanorth = apply( sapply( sims, function(x) x[,\"cfanorth\"], simplify =TRUE), 1, mean )\n RES$cfanorth_sd = apply( sapply( sims, function(x) x[,\"cfanorth\"], simplify =TRUE), 1, sd )\n RES$cfanorth_median = apply( sapply( sims, function(x) x[,\"cfanorth\"], simplify =TRUE), 1, median )\n RES$cfanorth_lb = apply( sapply( sims, function(x) x[,\"cfanorth\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfanorth_ub = apply( sapply( sims, function(x) x[,\"cfanorth\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n RES$cfasouth = apply( sapply( sims, function(x) x[,\"cfasouth\"], simplify =TRUE), 1, mean )\n RES$cfasouth_sd = apply( sapply( sims, function(x) x[,\"cfasouth\"], simplify =TRUE), 1, sd )\n RES$cfasouth_median = apply( sapply( sims, function(x) x[,\"cfasouth\"], simplify =TRUE), 1, median )\n RES$cfasouth_lb = apply( sapply( sims, function(x) x[,\"cfasouth\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfasouth_ub = apply( sapply( sims, function(x) x[,\"cfasouth\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n RES$cfa23 = apply( sapply( sims, function(x) x[,\"cfa23\"], simplify =TRUE), 1, mean )\n RES$cfa23_sd = apply( sapply( sims, function(x) x[,\"cfa23\"], simplify =TRUE), 1, sd )\n RES$cfa23_median = apply( sapply( sims, function(x) x[,\"cfa23\"], simplify =TRUE), 1, median )\n RES$cfa23_lb = apply( sapply( sims, function(x) x[,\"cfa23\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfa23_ub = apply( sapply( sims, function(x) x[,\"cfa23\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n RES$cfa24 = apply( sapply( sims, function(x) x[,\"cfa24\"], simplify =TRUE), 1, mean )\n RES$cfa24_sd = apply( sapply( sims, function(x) x[,\"cfa24\"], simplify =TRUE), 1, sd )\n RES$cfa24_median = apply( sapply( sims, function(x) x[,\"cfa24\"], simplify =TRUE), 1, median )\n RES$cfa24_lb = apply( sapply( sims, function(x) x[,\"cfa24\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfa24_ub = apply( sapply( sims, function(x) x[,\"cfa24\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n RES$cfa4x = apply( sapply( sims, function(x) x[,\"cfa4x\"], simplify =TRUE), 1, mean )\n RES$cfa4x_sd = apply( sapply( sims, function(x) x[,\"cfa4x\"], simplify =TRUE), 1, sd )\n RES$cfa4x_median = apply( sapply( sims, function(x) x[,\"cfa4x\"], simplify =TRUE), 1, median )\n RES$cfa4x_lb = apply( sapply( sims, function(x) x[,\"cfa4x\"], simplify =TRUE), 1, quantile, probs=0.025 )\n RES$cfa4x_ub = apply( sapply( sims, function(x) x[,\"cfa4x\"], simplify =TRUE), 1, quantile, probs=0.975 )\n\n return(RES)\n\n }\n\n\n if (grepl(\"map\", selection) ) {\n\n require(sf)\n\n ellp =list(...) # if plotting, all ellipsis contents are expected to be sppolt args\n\n if (is.null(vn)) stop(\"must have a vn object\")\n if (is.null(spmatrix)) stop(\"must have a spmatrix object\")\n if (is.null(sppoly)) stop(\"must have an sppoly object\")\n\n sppoly[,vn] = NA\n\n # first index is spatial strata\n\n res_dim = dim( spmatrix )\n\n if (is.null(time_match)) {\n if (res_dim == 1 ) time_match = NULL\n if (res_dim == 2 ) time_match = list(year=\"2000\")\n if (res_dim == 3 ) time_match = list(year=\"2000\", dyear=\"0.8\" )\n }\n\n if (is.null(poly_match)) poly_match = sppoly[[\"AUID\"]]\n\n i_poly = match( poly_match, sppoly[[\"AUID\"]] ) # should match exactly but in case a subset is sent as sppoly\n\n data_dimensionality = length( dim(spmatrix[[vn]]) )\n if (data_dimensionality==1) {\n sppoly[, vn] = spmatrix[[vn]] [ i_poly ] # year only\n }\n\n if (!is.null(time_match)) {\n n_indexes = length( time_match )\n if (data_dimensionality==2) {\n if (n_indexes==1) sppoly[, vn] = spmatrix[[vn]] [ i_poly, time_match[[1]] ] # year only\n }\n if (data_dimensionality==3) {\n if (n_indexes==1) sppoly[, vn] = spmatrix[[vn]] [ i_poly, time_match[[1]] , ] # year only\n if (n_indexes==2) sppoly[, vn] = spmatrix[[vn]] [ i_poly, time_match[[1]], time_match[[2]] ] # year/subyear\n }\n }\n\n if (length(poly_match) > 1 ) {\n\n dev.new();\n\n if ( !exists(\"main\", ellp ) ) ellp[[\"main\"]]=vn\n ellp$obj = sppoly\n ellp$zcol=vn\n ellp$col=\"transparent\"\n\n do.call(spplot, ellp )\n\n }\n\n\n }\n\n\n}\n", "meta": {"hexsha": "20b51f0e888b9f1fd6a86a20a4bed91aeb76b337", "size": 14153, "ext": "r", "lang": "R", "max_stars_repo_path": "R/birth_death_fishing.r", "max_stars_repo_name": "jae0/aegis.odemod", "max_stars_repo_head_hexsha": "a384a0dd9dfdc2bde0690e0ae348e826edc9288f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/birth_death_fishing.r", "max_issues_repo_name": "jae0/aegis.odemod", "max_issues_repo_head_hexsha": "a384a0dd9dfdc2bde0690e0ae348e826edc9288f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/birth_death_fishing.r", "max_forks_repo_name": "jae0/aegis.odemod", "max_forks_repo_head_hexsha": "a384a0dd9dfdc2bde0690e0ae348e826edc9288f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5603015075, "max_line_length": 153, "alphanum_fraction": 0.5353635272, "num_tokens": 4919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4873258135618954}} {"text": "#' @importFrom plgp randomForest lme4\n# '\n#' inverse canonical link\n#'\n#' a simple function for inverse canonical link\n#'\n#' calculate the inverse canonical link \\code{\\link{unsae}}\n#'\n#' @param x a numeric vector\n#'\n#' @return calculated value\n#'\n#' @examples\n#' hc(1)\n#'\n#' @export\nhc <- function(x) as.numeric(1 /(1 + exp(-x))) # inverse canonical link\n\n\n#' spatial likelihood\n#'\n#' a simple (log) spatial likelihood\n#' used within multilevel_EM function of \\code{\\link{unsae}}\n#'\n#' @param par parameter values\n#'\n#' @param D distance matrix from plgp::distance\n#'\n#' @param Y \"observed\" response vector\n#'\n#' @param mu current estimate of mu\n#'\n#' @return negative log likelihood\n#'\nspatial_lik <- function(par, D, Y, mu) {\n # par: parameters (range and nugget)\n # D: coordinates\n # Y: responses\n # mu: current estimate of mu\n theta <- par[1]\n g <- par[2]\n n <- length(Y)\n K <- exp(-D/theta) + g*diag(n)\n K_inv <- solve(K)\n ldetK <- determinant(K, logarithm=TRUE)$modulus\n ll <- -(n/2)*log(t(Y - mu) %*% K_inv %*% Y - mu) - (1/2)*ldetK\n return(-ll)\n}\n\n#' multilevel EM\n#'\n#' a main function to fit multilevel em with gaussian spatial correlation. Some chunk of the code has been dedicated to handle the syntax. glmer function is called to get the initial value of the estimates.\n#'\n#' @param formula formula argument following the glmer syntax.\n#'\n#' @param tol tolerence level to control the em convergence. default value 1e-3.\n#'\n#' @param data name of the data set.\n#'\n#' @param coordinates specifying the name of coordinates within the data. These columns *should* exist within the data set provided.\n#'\n#' @return list of element that are needed for the prediction.\n#'\n#' @export\n\n\nmultilevel_EM <-\n function(formula, data, tol = 1e-3, coordinates){\n re_pattern <- \"\\\\|(.*?)\\\\)\"\n random_effect <- str_squish(str_match(formula, re_pattern)[,\n 2])\n if (!is.factor(data[[random_effect]])) {\n stop(\"area index must be a factor\")\n }\n data$area_index <- droplevels(data[[random_effect]]) %>%\n as.numeric\n M <- data$area_index %>% unique %>% length\n mod_glmer <- lme4::glmer(formula = as.formula(formula), data = data,\n family = \"binomial\")\n beta_1_t <- mod_glmer@beta\n sigma2.a_t <- as.numeric(VarCorr(mod_glmer)[1])\n a_i_vec <- ranef(mod_glmer)[[random_effect]][, 1]\n a_i.init_vec <- a_i_vec\n M <- length(a_i_vec)\n area_index_long <- data$area_index\n area_index_unique <- unique(area_index_long)\n a_i_ini_tbl <- tibble(a_i = a_i_vec, area_index = area_index_unique)\n a_i_long_tbl <- tibble(area_index = area_index_long)\n a_i_tbl <- left_join(a_i_long_tbl, a_i_ini_tbl, by = \"area_index\")\n re_form_pattern <- \"\\\\((.*?)\\\\)\"\n re_part_form <- str_match(formula, re_form_pattern)[1]\n fe_form <- str_remove_all(string = formula, pattern = coll(re_part_form)) %>%\n str_remove_all(pattern = \"\\\\)\") %>% str_remove_all(pattern = \"\\\\(\") %>%\n str_remove_all(pattern = \"\\\\|\") %>% str_squish()\n error_pattern <- \"\\\\~(.*?)\\\\+\"\n fixed_form <- ifelse(str_ends(string = fe_form, pattern = \"\\\\+\"),\n str_sub(string = fe_form, start = 1L, end = (str_length(fe_form) -\n 1)), str_replace(string = fe_form, pattern = error_pattern,\n replace = \"~\")) %>% str_squish()\n response_var <- str_squish(str_split(fixed_form, \"\\\\~\",\n simplify = TRUE)[1])\n x <- model.matrix(as.formula(fixed_form), data = data)\n y <- data[[response_var]]\n if (length(unique(y)) != 2) {\n stop(\"too many values in response\")\n }\n if (!is.numeric(y)) {\n y <- factor(y)\n }\n if (is.factor(y)) {\n y <- as.numeric(y == levels(factor(y))[2])\n }\n data$y <- y\n pred_part <- str_squish(str_split(fixed_form, \"\\\\~\",\n simplify = TRUE)[2])\n beta1.init <- rep(0, ncol(x))\n a_i.old_vec_long <- rep(0, length(y))\n change <- Inf\n beta1.old <- beta1.init\n a_i.old_vec <- a_i.init_vec\n outer_change <- Inf\n a_i.old_vec <- rep(0, M)\n cnt <- 0\n mu_hat <- 0\n tau2_hat <- 1\n params <- c(0.2, 2)\n while (outer_change > tol & cnt <= 20) {\n change <- Inf\n while (change > tol) {\n x_beta1 <- x %*% beta1.old %>% as.numeric\n eta <- x_beta1 + a_i.old_vec_long\n y.hat <- hc(eta)\n h.prime_eta <- ifelse(near(y.hat * (1 - y.hat), 0),\n 1e-04, y.hat * (1 - y.hat))\n z <- (y - y.hat)/h.prime_eta\n temp_tbl <- data\n temp_tbl$z <- z\n wls_form <- paste(\"z~\", pred_part)\n beta1.new <- beta1.old + lm(formula = as.formula(wls_form),\n weights = h.prime_eta, data = data)$coef\n change <- sqrt(sum((beta1.new - beta1.old)^2))\n beta1.old <- beta1.new\n }\n beta_1.t <- beta1.old\n wk_tbl <- data %>% rename(a_index = area_index)\n wk_tbl$w_resid <- y - x %*% beta_1.t %>% as.numeric\n wk_tbl <- wk_tbl %>% mutate(pi_w = 1 - hc(w_resid))\n a_i.new_vec <- rep(NA, length(a_i.old_vec))\n v_i_vec <- rep(NA, length(a_i.old_vec))\n for (m in 1:M) {\n wk_tbl_i <- wk_tbl %>% filter(a_index == m)\n x_i <- model.matrix(as.formula(fixed_form), data = wk_tbl_i)\n y_i <- wk_tbl_i$y\n if (length(unique(y_i))>1){a_i.old <- a_i.old_vec[m]\n change <- Inf\n inner_cnt <- 0\n while (change > tol & inner_cnt <= 100) {\n x_beta1 <- x_i %*% beta1.old\n eta <- x_beta1 + a_i.old %>% as.numeric\n y.hat_i <- hc(eta)\n h.prime_eta_i <- ifelse(near(y.hat_i * (1 - y.hat_i),\n 0), 1e-04, y.hat_i * (1 - y.hat_i))\n z_i <- (y_i - y.hat_i)/h.prime_eta_i\n a_i.new <- a_i.old + lm(z_i ~ 1, weights = h.prime_eta_i)$coef %>%\n as.numeric\n change <- sqrt(sum((a_i.new - a_i.old)^2))\n a_i.old <- a_i.new\n inner_cnt <- inner_cnt + 1\n a_i.new_vec[m] <- a_i.old\n v_i_vec[m] <- 1/sum(h.prime_eta_i)\n }\n }else{\n a_i.new_vec[m] <- a_i.old\n v_i_vec[m] <- 1e6\n }\n }\n V <- diag(v_i_vec)\n\n spat_coord <- data %>% dplyr::select(all_of(coordinates)) %>%\n unique\n D <- plgp::distance(spat_coord)\n K <- exp(-D/params[1]) + diag(params[2], nrow(spat_coord))\n Ki <- solve(K)\n mu_hat <- drop(t(rep(1, nrow(Ki))) %*% Ki %*% a_i.new_vec/sum(Ki))\n a_star <- drop(mu_hat + solve(tau2_hat * K + V) %*% (tau2_hat *\n K) %*% (a_i.new_vec - mu_hat))\n V_star <- tau2_hat * K - tau2_hat * K %*% solve(tau2_hat *\n K + V) %*% (tau2_hat * K)\n tau2_hat <- drop(sum(diag(solve(tau2_hat * K) %*% V_star)) +\n t(a_star) %*% solve(tau2_hat * K) %*% a_star)/nrow(K)\n out <- optim(c(0.1, 0.01), spatial_lik, method = \"L-BFGS-B\",\n lower = 1e-07, upper = c(10, 10), D = D, Y = a_star,\n mu = mu_hat)\n params <- out$par\n a_i_ini_tbl_new <- tibble(a_i = a_star, area_index = unique(data$area_index))\n a_i_long_tbl_new <- tibble(area_index = data$area_index)\n a_i_tbl_new <- left_join(a_i_long_tbl_new, a_i_ini_tbl_new,\n by = \"area_index\")\n a_i.old_vec_long <- a_i_tbl_new$a_i\n outer_change <- mean((a_star - a_i.old_vec)^2)\n # plot(a_i.old_vec, a_star)\n a_i.old_vec <- a_star\n cnt <- cnt + 1\n cat(\"...EM iteration:\", cnt, \"\\n\")\n }\n\n outcome <- list(cnt = cnt, area_tbl = a_i_tbl_new, area_re = a_i.old_vec,\n params = c(out$par), mu_hat = mu_hat, spat_coord = spat_coord,\n fomula = formula, V = v_i_vec, beta_hat = beta1.new,\n tau2_hat = tau2_hat, D = D, coordinates = coordinates)\n\n return(outcome)\n}\n\n#' spatial prediction\n#'\n#' to calculate the spatial random effect for a new data set.\n#'\n#' @param em_output the outcome from the multilevel_EM function.\n#'\n#' @param test_set the test set (or new data set). The data set *should* have the predictor columns as well as the coordinate columns, all with the same names with the training data set.\n#'\n#' @return predicted spatial random effect at new data set\n\nspatial_pred <- function(em_output, test_set){\n coordinates <- em_output$coordinates\n spat_coord <- em_output$spat_coord\n new_site <- test_set %>% dplyr::select(all_of(coordinates))\n if (is.null(nrow(new_site))){ # to make sure it works for a single site\n new_site <- as.data.frame(matrix(new_site, nrow = 1))\n }\n par <- em_output$params\n DXX <- plgp::distance(new_site)\n D <- em_output$D\n mu_hat <- em_output$mu_hat\n a_star <- em_output$area_re\n K <- exp(- D/par[1]) + par[2]*diag(nrow(spat_coord))\n spat_coord <- em_output$spat_coord\n KXX <- exp(-DXX/par[1]) + par[2]*diag(ncol(DXX))\n DX <- plgp::distance(new_site, spat_coord)\n KX <- exp(-DX/par[1])\n Ki <- solve(K)\n a_hat <- mu_hat + KX %*% Ki %*% (a_star - mu_hat)\n a_hat <- drop(a_hat)\n return(a_hat)\n}\n\n\n#' covariate prediction\n#'\n#' to calculate the spatial random effect for a new data set.\n#'\n#' @param em_output the outcome from the multilevel_EM function.\n#'\n#' @param test_set the test set (or new data set). The data set *should* have the predictor columns as well as the coordinate columns, all with the same names with the training data set.\n#'\n#' @return predicted covariates parts Xb at new data set\n\ncovariate_pred <- function(em_output, test_set){\n beta_hat <- em_output$beta_hat\n formula <- em_output$fomula\n re_form_pattern <- \"\\\\((.*?)\\\\)\"\n re_part_form <- str_match(formula, re_form_pattern)[1]\n fe_form <-\n str_remove_all(string = formula, pattern = coll(re_part_form)) %>%\n # coll is to force the matching the \"full expression\", not as a regex\n str_remove_all(pattern = \"\\\\)\") %>%\n str_remove_all(pattern = \"\\\\(\") %>%\n str_remove_all(pattern = \"\\\\|\") %>%\n str_squish()\n\n error_pattern <- \"\\\\~(.*?)\\\\+\"\n fixed_form <-\n ifelse(str_ends(string = fe_form, pattern = \"\\\\+\"),\n str_sub(string = fe_form, start = 1L, end = (str_length(fe_form)-1)),\n str_replace(string = fe_form, pattern = error_pattern, replace = \"~\")) %>%\n str_squish()\n\n mm_form <- str_squish(str_split(fixed_form, \"\\\\~\", simplify = TRUE)[2])\n\n x <- model.matrix(as.formula(paste(\"~\", mm_form)), data = test_set)\n out <- as.numeric(x %*% beta_hat)\n return(out)\n}\n\n#' main prediction\n#'\n#' a wrapper to calculate the spatial random effect for a new data set.\n#'\n#' @param em_output the outcome from the multilevel_EM function.\n#'\n#' @param test_set the test set (or new data set). The data set *should* have the predictor columns as well as the coordinate columns, all with the same names with the training data set.\n#'\n#' @return predicted outcome combining covariates parts Xb and spatial random effects at new data set\n#'\n#' @export\n\npredict_em <- function(em_output, test_set){\n yhat <- covariate_pred(em_output, test_set)\n spat_hat <- spatial_pred(em_output, test_set)\n combined_hat <- yhat + spat_hat\n phat <- hc(combined_hat)\n return(phat)\n}\n\n\n\n#' calculate the MSE for each area\n#'\n#' @param em_output the outcome from the multilevel_EM function.\n#'\n#' @param test_set the test set (or new data set).\n#' The data set *should* have the predictor columns as well\n#' as the coordinate columns,\n#' all with the same names with the training data set.\n#'\n#' @return simulated spatial random effect of size 100 (100 is default)\n#' at new data set\n#'\n#'\n\ncal_mse <- function(em_output, test_set, size = 100){\n coordinates <- em_output$coordinates\n spat_coord <- em_output$spat_coord\n tau2_hat <- em_output$tau2_hat\n new_site <- test_set %>% dplyr::select(all_of(coordinates))\n if (is.null(nrow(new_site))){ # to make sure it works for a single site\n new_site <- as.data.frame(matrix(new_site, nrow = 1))\n }\n par <- em_output$params\n DXX <- plgp::distance(new_site)\n D <- em_output$D\n mu_hat <- em_output$mu_hat\n a_star <- em_output$area_re\n K <- exp(- D/par[1]) + par[2]*diag(nrow(spat_coord))\n spat_coord <- em_output$spat_coord\n KXX <- exp(-DXX/par[1]) + par[2]*diag(ncol(DXX))\n DX <- plgp::distance(new_site, spat_coord)\n KX <- exp(-DX/par[1])\n Ki <- solve(K)\n a_hat <- mu_hat + KX %*% Ki %*% (a_star - mu_hat)\n a_hat <- drop(a_hat)\n\n Sigmap <- tau2_hat*(KXX - KX %*% Ki %*% t(KX))\n\n DXX <- plgp::distance(new_site)\n KXX <- exp(-DXX/par[1]) + diag(par[2], nrow(DXX))\n\n Sigmap <- tau2_hat*(KXX - KX %*% Ki %*% t(KX))\n\n Sigma.int <- tau2_hat*(exp(-DXX) + diag(par[2], nrow(DXX))\n - KX %*% Ki %*% t(KX))\n a_k <- rmvnorm(size, a_hat, Sigma.int)\n\n # routine to calculate the MSE part 1\n yhat <- covariate_pred(em_output, test_set)\n rep_yhat_mat <- matrix(rep(yhat, size), nrow = size, byrow = TRUE)\n combined_mat <- a_k + rep_yhat_mat\n\n v_2 <- var((apply(1 / (1 + exp(-combined_mat)), 1, mean)))\n v_1 <- var(apply(1 / (1 + exp(-combined_mat)), 2, mean)) / ncol(combined_mat)\n\n total_v <- v_1 + v_2\n\n return(total_v)\n}\n\n\n", "meta": {"hexsha": "709cec805794ca6667cd52e2ee166239271abc7d", "size": 13364, "ext": "r", "lang": "R", "max_stars_repo_path": "R/unsae.r", "max_stars_repo_name": "ydhwang/unsae", "max_stars_repo_head_hexsha": "6da1f4c6348e23e76fa5d3cd9ab8a42ddcf0514d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/unsae.r", "max_issues_repo_name": "ydhwang/unsae", "max_issues_repo_head_hexsha": "6da1f4c6348e23e76fa5d3cd9ab8a42ddcf0514d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/unsae.r", "max_forks_repo_name": "ydhwang/unsae", "max_forks_repo_head_hexsha": "6da1f4c6348e23e76fa5d3cd9ab8a42ddcf0514d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.216802168, "max_line_length": 206, "alphanum_fraction": 0.5947321161, "num_tokens": 3902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.487284046834454}} {"text": "#' @title calcCp\n#'\n#'@description Calculates the prismatic coefficient (\\code{Cp}) (dimensionless).\n#'\n#'@param Cm Midship section coefficient (vector of numericals, dimensionless) \n#'(see \\code{\\link{calcCm}})\n#'@param Cbw Waterline block coefficient (vector of numericals, dimensionless) \n#'(see \\code{\\link{calcCbw}})\n#'@param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}}). \n#' Must align with \\code{roroPaxContainerShipTypes},\n#'\\code{gCargoShipTypes}, and \\code{tankerBulkCarrierShipTypes} groupings\n#'@param bounds Indicates which upper and lower bounds on \\code{Cp} should be\n#'applied:\\itemize{\n#'\\item Pass \"holtrop mennen\" to use the bounds specified by Holtrop & Mennen\n#'\\item Pass \"none\" (default) to calculate \\code{Cp} without upper or lower\n#' bounds}\n#' This argument is not vectorized. Either supply a single string or rely on the\n#' default\n#'@param roroPaxContainerShipTypes Ship types specified in input \\code{shipTypes}\n#'to be modeled as RORO, passenger and container ships (vector of strings)\n#'@param gCargoShipTypes Ship types specified in input \\code{shipTypes} to be\n#'modeled as general cargo (vector of strings)\n#'@param tankerBulkCarrierShipTypes Ship types specified in input\n#'\\code{shipTypes} to be modeled as tankers and bulk carriers (vector of strings)\n#'\n#' @details\n#' \\deqn{Cp = \\frac{Cbw}{Cm}}{Cp=Cbw/Cm}\n#'\n#' This function can calculate \\code{Cp} with or without upper and lower bounds.\n#' If the Holtrop & Mennen bounds are applied, this requires ship types to be\n#' grouped. Use the \\code{roroPaxContainerShipTypes}, \\code{gCargoShipTypes},\n#' and \\code{tankerBulkCarrierShipTypes} parameters to provide these ship\n#' type groupings. Any ship types not included in these groupings will be\n#' considered as miscellaneous vessels.\n#'\n#' @return \\code{Cp} (vector of numericals, dimensionless)\n#'\n#'@references\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#' @seealso\n#' \\itemize{\n#' \\item \\code{\\link{calcCm}}\n#' \\item \\code{\\link{calcCbw}}\n#' \\item \\code{\\link{calcShipType}}\n#' }\n#'\n#' @examples\n#' calcCp(c(0.99,0.98), c(.8,.75),c(\"bulk.carrier\",\"container.ship\"),\"none\")\n#'\n#' @export\n\ncalcCp <-function(Cm, Cbw, shipType, bounds=\"none\",\n roroPaxContainerShipTypes=c(\"ro.ro\",\"passenger\",\"ferry.pax\",\"ferry.ro.pax\",\"cruise\",\"cruise.ed\",\"yacht\",\"container.ship\"),\n gCargoShipTypes=c(\"general.cargo\"),\n tankerBulkCarrierShipTypes=c(\"tanker\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\")\n){\n\n\n Cp <-if(bounds==\"holtrop mennen\"){\n ifelse(\n shipType%in%roroPaxContainerShipTypes,\n pmax(0.55,pmin(0.67,(Cbw/Cm))),\n ifelse(shipType%in%gCargoShipTypes,\n pmax(0.56,pmin(0.75,(Cbw/Cm))),\n ifelse(shipType%in%tankerBulkCarrierShipTypes,\n pmax(0.85,pmin(0.73,(Cbw/Cm))),#case 3: bulk carrier & tanker,\n Cbw/Cm\n )\n )\n )\n }else{(Cbw/Cm)}\n\n return(Cp)\n}\n", "meta": {"hexsha": "09a919696b147a3e73be37fccc762fcbe2457fe6", "size": 3111, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcCp.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcCp.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcCp.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 40.4025974026, "max_line_length": 140, "alphanum_fraction": 0.6885245902, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4865469252001074}} {"text": "#' pegasos\n#' \n#' Pegasos SVM solver.\n#' \n#' @description\n#' If \\code{intercept=TRUE}, the data is not literally modified to include a\n#' column of ones. However, this is conceptually what we do.\n#' \n#' @param x\n#' The features matrix.\n#' @param y\n#' The 2-class response vector. Note that the groups must be +/- 1.\n#' See \\code{recode()} \n#' @param intercept\n#' Should the model include an intercept term?\n#' @param k\n#' TODO, currently ignored\n#' @param lambda\n#' Regularization parameter.\n#' @param niter\n#' The number of iterations.\n#' \n#' @return\n#' An object of class pegasosSVM.\n#' \n#' @references\n#' Shalev-Shwartz, Shai, et al. \"Pegasos: Primal estimated sub-gradient solver\n#' for svm.\" Mathematical programming 127.1 (2011): 3-30.\n#' \n#' @examples\n#' \\dontrun{\n#' library(ssvm)\n#' \n#' y <- recode(iris$Species == \"setosa\")\n#' x <- as.matrix(iris[, -5])\n#' \n#' pegasos(x, y)\n#' }\n#' \n#' @author\n#' Drew Schmidt\n#' \n#' @export\npegasos <- function(x, y, intercept=TRUE, k=5, lambda=.1, niter=1e5)\n{\n check.is.flag(intercept)\n check.is.posint(k)\n check.is.scalar(lambda)\n check.is.posint(niter)\n \n if (!is.double(x))\n storage.mode(x) <- \"double\"\n if (!is.integer(y))\n storage.mode(y) <- \"integer\"\n \n w <- .Call(R_svm_pegasos_fit, intercept, as.integer(k), as.double(lambda), as.integer(niter), x, y)\n nm <- colnames(x)\n if (!is.null(nm))\n {\n if (intercept)\n nm <- c(\"Intercept\", nm)\n \n names(w) <- nm\n }\n \n svm <- list(w=w, niter=niter, intercept=intercept)\n class(svm) <- \"pegasosSVM\"\n \n svm\n}\n\n\n\n#' @export\nprint.pegasosSVM <- function(x, ...)\n{\n cat(paste0(\"SVM model (Method=Pegasos, Iterations=\", x$niter, \")\\n\"))\n print(x$w)\n}\n\n\n\n#' @export\npredict.pegasosSVM <- function(object, newdata, ...)\n{\n .Call(R_svm_pegasos_pred, newdata, object$w, object$intercept)\n}\n", "meta": {"hexsha": "ac816b110c6738b9f8a489a93db9b5d3c3697dbb", "size": 1817, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pegasos.r", "max_stars_repo_name": "hiendn/PEGASOS", "max_stars_repo_head_hexsha": "54849403fcb1663c9864d5a38444781ad5e54ea1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-10-08T18:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-21T20:22:59.000Z", "max_issues_repo_path": "R/pegasos.r", "max_issues_repo_name": "hiendn/PEGASOS", "max_issues_repo_head_hexsha": "54849403fcb1663c9864d5a38444781ad5e54ea1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/pegasos.r", "max_forks_repo_name": "hiendn/PEGASOS", "max_forks_repo_head_hexsha": "54849403fcb1663c9864d5a38444781ad5e54ea1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6477272727, "max_line_length": 101, "alphanum_fraction": 0.629609246, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4864510133592458}} {"text": "#!/usr/bin/env Rscript\n\ndata <- read.table(\"gasdisk.txt\", head=TRUE)\ntrmodel <- read.table(\"trcurve.txt\", head=TRUE)\n\nrc <- splinefun(trmodel$r, trmodel$v)\ntheta <- seq(0,2*pi, length.out=10000)\n\ncross <- function(a, b) {\n\treturn (c( a[2]*b[3]-a[3]*b[2] , a[3]*b[1]-a[1]*b[3] , a[1]*b[2]-a[2]*b[1] ))\n}\n\ndotprod <- function(a,b) {\n return ( a[1]*b[1] + a[2]*b[2] + a[3]*b[3] )\n}\n\nlhat <- c(-0.137364,0.332812,0.932935)\nslit0 <- c(-0.000159857,0.00147301,0.000698394)\nslit90 <- c(0.00197305,-0.000506444,-0.00141966)\ni <- cross(lhat, c(1,0,0))\nj <- cross(lhat, i)\nslitpos0 <- c(dotprod(slit0, i), dotprod(slit0, j))\nslitpos90 <- c(dotprod(slit90, i), dotprod(slit90, j))\n\nslitpos0 <- 10 * slitpos0/sqrt(sum(slitpos0^2))\nslitpos90 <- 10 * slitpos90/sqrt(sum(slitpos90^2))\n\npdf(\"velmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nvtot <- sqrt(data$vx^2 + data$vy^2)\nvscale <- 1e-3 * max(vtot)/50\nradius <- sqrt(data$x^2 + data$y^2)*1e-3\nn <- which(vtot>rc(radius))\nm <- which(vtot ratio), which(vr/vtot < ratio+0.1))\n\tsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(ratio,0,1-ratio^0.5))\n}\nn <- which(vr/vtot > 1)\nsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=\"red\")\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\npdf(\"lzmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nLz <- data$x*data$vy - data$y*data$vx\nfor (i in seq(10,1000, by=10)) {\n\tn <- intersect(which(Lzi-100))\n\tsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(i/1e3,0,1-i/1e3))\n}\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\npdf(\"philz.pdf\")\nphi <- atan2(data$x, data$y)\nm <- intersect(which(radius<2.6e-3),which(radius>2.5e-3))\nm <- m[order(phi[m])]\nplot(phi[m], Lz[m], cex=0.1, ylim=c(0,4e-3), type=\"l\")\ndL <- 500\nfor (L in seq(dL,2000,by=dL)) {\n\tm <- intersect(which(LzL))\n\tm <- m[order(phi[m])]\n\tif (length(m)>0) { lines(phi[m], radius[m]) }\n}\n\nn <- which(radius<4e-3)\ncoldmass <- sum(data$m[n])\ndata <- read.table(\"hotdisk.txt\", head=TRUE)\nradius <- sqrt(data$x^2 + data$y^2)*1e-3\nn <- which(radius<4e-3)\nhotmass <- sum(data$m[n])\ndev.off()\n\npdf(\"fullvelmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nvtot <- sqrt(data$vx^2 + data$vy^2)\nn <- which(vtot>rc(radius))\nm <- which(vtot ratio), which(vr/vtot < ratio+0.1))\n\tsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(ratio,0,1-ratio^0.5))\n}\nn <- which(vr/vtot > 1)\nsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=\"red\")\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\npdf(\"fulllzmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nLz <- data$x*data$vy - data$y*data$vx\nfor (i in seq(10,1000, by=10)) {\n\tn <- intersect(which(Lzi-100))\n\tsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(i/1e3,0,1-i/1e3))\n}\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\ndata <- read.table(\"stellardisk.txt\", head=TRUE)\nradius <- sqrt(data$x^2 + data$y^2)*1e-3\nn <- which(radius<4e-3)\nstarmass <- sum(data$m[n])\nn <- sample(seq(length(data$x)), min(c(50000,length(data$m))))\ndata <- data[n,]\n\npdf(\"starvelmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nvtot <- sqrt(data$vx^2 + data$vy^2)\nradius <- sqrt(data$x^2 + data$y^2)*1e-3\nn <- which(vtot>rc(radius))\nm <- which(vtot ratio), which(vr/vtot < ratio+0.1))\n\tsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(ratio,0,1-ratio^0.5))\n}\nn <- which(vr/vtot > 1)\nsegments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=\"red\")\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\npdf(\"starlzmap.pdf\")\nplot(data$x, data$y, cex=0.1, xlim=c(-5,5), ylim=c(-5,5), xlab=\"x[kpc]\", ylab=\"y[kpc]\")\nLz <- data$x*data$vy - data$y*data$vx\nfor (i in seq(10,1000, by=10)) {\n\tn <- intersect(which(Lzi-100))\n\t#segments(data$x[n], data$y[n], data$x[n]+data$vx[n]*vscale, data$y[n]+data$vy[n]*vscale, col=rgb(i/1e3,0,1-i/1e3))\n\tpoints(data$x[n], data$y[n], col=rgb(i/1e3,0,1-i/1e3), cex=0.2, pch=19)\n}\nlines(3*cos(theta), 3*sin(theta), lty=3, col=\"green\", lwd=3)\npoints(0,0, pch=16)\ndev.off()\n\n\nhotmass <- hotmass-coldmass\ntotmass <- coldmass+hotmass+starmass\nprint(coldmass/totmass)\nprint(hotmass/totmass)\nprint(starmass/totmass)\n", "meta": {"hexsha": "478c1791adafc59cec2c6b42edab3e4004b75131", "size": 6649, "ext": "r", "lang": "R", "max_stars_repo_path": "velmap.r", "max_stars_repo_name": "petehague/galaxyview", "max_stars_repo_head_hexsha": "9202a09c97d66b23213356815f3c6eaeb8958d7f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "velmap.r", "max_issues_repo_name": "petehague/galaxyview", "max_issues_repo_head_hexsha": "9202a09c97d66b23213356815f3c6eaeb8958d7f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "velmap.r", "max_forks_repo_name": "petehague/galaxyview", "max_forks_repo_head_hexsha": "9202a09c97d66b23213356815f3c6eaeb8958d7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6569767442, "max_line_length": 119, "alphanum_fraction": 0.6249060009, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4864086530864653}} {"text": "# Author: Lerato E. Magosi\n# R version: 4.0.3 (2020-10-10)\n# Platform: x86_64-apple-darwin19.6.0 (64-bit)\n# Date: 16Mar2021\n\n\n# Goal: Estimate transmission flows within and between population groups accounting for\n# sampling heterogeneity\n\n\n# Required libraries ---------------------------\n\n# library(dplyr) # needed for sorting and merging data.frames\n# library(Hmisc) # needed for capitalizing elements of a character vector\n# library(magrittr) # needed for the pipe function\n# library(gtools) # needed for computing permutations and combinations\n# library(stats) # needed for the following functions: qchisq\n# library(utils) # needed for the following functions: str, head, tail\n\n\n# Optional libraries ---------------------------\n\n# library(DescTools) # needed for computing simultaneous confidence intervals for a multinomial proportions (Goodman, Sison-Glaz)\n# library(ACSWR) # needed for computing Queensbury Hurst simultaneous confidence intervals\n# library(CoinMinD) # needed for computing Queensbury Hurst simultaneous confidence intervals (narrow CIs)\n\n\n# Calling globalVariables on the following variables to address \n# the note: \"no visible binding for global variable\" generated by \"R CMD check\"\nutils::globalVariables(c(\"est\", \"lwr.ci\", \"num_linked_pairs_observed\", \"upr.ci\"))\n\n\n\n# Strategy ---------------------------\n\n# Estimates of transmisison flows are computed using methods from Carnegie and colleagues. \n# Carnegie NB, Wang R, Novitsky V, De Gruttola V (2014) Linkage of Viral Sequences among \n# HIV-Infected Village Residents in Botswana: Estimation of Linkage Rates in the Presence \n# of Missing Data. PLoS Computational Biology 10(1): e1003430. (PMID: 24415932)\n\n# Note: Methods from Carnegie and colleagues are extended to account for direction of transmission\n# between linked pairs\n\n\n# Function: estimate_transmission_flows ---------------------------\n#\n# Goal: use counts of observed directed transmission pairs (obtained via phyloscanner) \n# to estimate transmission flows within and between population groups accounting \n# for sampling heterogeneity\n#\n# For details on phyloscanner see PMID: 30926780 and PMID: 29186559\n#\n# parameters:\n#\n#\n# group_in (character) A vector indicating population groups/strata (e.g. communities, age-groups, genders or trial arms) between which transmission flows will be evaluated, \n# individuals_sampled_in (numeric) A vector indicating the number of individuals sampled per population group, \n# individuals_population_in (numeric) A vector of the estimated number of individuals per population group, \n# linkage_counts_in A data.frame of counts of linked pairs identified between samples of each population pairing of interest.\n# The data.frame should contain the following three fields: H1_group (character), H2_group (character), number_linked_pairs_observed (numeric).\n# For a population group pairing, H1_group and H2_group denote population groups 1 and 2 respectively; and number_linked_pairs_observed denotes \n# the number of observed directed transmission pairs between samples from population groups 1 and 2.\n# verbose_output (boolean) A value to display intermediate output \n# detailed_report (boolean) A value to produce detailed output of the analysis \n# \n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2 \n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n# est_linkedpairs_in_population (numeric) Estimated transmission pairs between population groups 1 and 2\n# theta_hat (numeric) Estimated transmission flows or relative probability of transmission within and between population groups 1 and 2 adjusted\n# for sampling heterogeneity. More precisely, the conditional probability that a pair of pathogen sequences is from a specific population \n# group pairing given that the pair is linked.\n# obs_trm_pairs_est_goodman (numeric) Point estimate, Goodman method Confidence intervals for observed transmission pairs\n# obs_trm_pairs_lwr_ci_goodman (numeric) Lower bound of Goodman confidence interval \n# obs_trm_pairs_upr_ci_goodman (numeric) Upper bound of Goodman confidence interval \n# est_goodman (numeric) Point estimate, Goodman method Confidence intervals for estimated transmission flows\n# lwr_ci_goodman (numeric) Lower bound of Goodman confidence interval \n# upr_ci_goodman (numeric) Upper bound of Goodman confidence interval \n#\n#\n# The following additional fields are returned if the detailed_report \n# flag is set\n#\n# prob_group_pairing_and_linked (numeric) Probability that a pair of pathogen sequences is from a specific population group pairing and is linked\n# c_hat (numeric) Probability that a randomly selected pathogen sequence in one population group links to at least \n# one pathogen sequence in another population group i.e. probability of clustering\n# est_goodman_cc (numeric) Point estimate, Goodman method Confidence intervals with continuity correction\n# lwr_ci_goodman_cc (numeric) Lower bound of Goodman confidence interval \n# upr_ci_goodman_cc (numeric) Upper bound of Goodman confidence interval \n# est_sisonglaz (numeric) Point estimate, Sison-Glaz method Confidence intervals\n# lwr_ci_sisonglaz (numeric) Lower bound of Sison-Glaz confidence interval \n# upr_ci_sisonglaz (numeric) Upper bound of Sison-Glaz confidence interval \n# est_qhurst_acswr (numeric) Point estimate, Queensbury-Hurst method Confidence intervals via ACSWR r package \n# lwr_ci_qhurst_acswr (numeric) Lower bound of Queensbury-Hurst confidence interval \n# upr_ci_qhurst_acswr (numeric) Upper bound of Queensbury-Hurst confidence interval \n# est_qhurst_coinmind (numeric) Point estimate, Queensbury-Hurst method Confidence intervals via CoinMinD r package \n# lwr_ci_qhurst_coinmind (numeric) Lower bound of Queensbury-Hurst confidence interval\n# upr_ci_qhurst_coinmind (numeric) Upper bound of Queensbury-Hurst confidence interval\n# lwr_ci_qhurst_adj_coinmind (numeric) Lower bound of Queensbury-Hurst confidence interval adjusted \n# upr_ci_qhurst_adj_coinmind (numeric) Upper bound of Queensbury-Hurst confidence interval adjusted\n#\n# ------------------------------------------------------------------------------------\n\n\nestimate_transmission_flows <- function(group_in, \n individuals_sampled_in, \n individuals_population_in, \n linkage_counts_in,\n detailed_report = FALSE,\n verbose_output = FALSE) {\n\n\t# Assemble dataset and prepare input to calculate p_hat\n\t# Reminder! p_hat denotes the probability that pathogen sequences from two individuals randomly sampled from their\n\t# respective population groups are linked.\n\n\tresults_prepare_input_for_get_p_hat <- tryCatch({\n\t \n\t # Condition: Try and execute function prepare_input_for_get_p_hat() a.k.a prep_p_hat()\n\t \n\t if (verbose_output) message(\"Executing function: prep_p_hat(). \\n\")\n\t \n\t\tprepare_input_for_get_p_hat(group_in, \n\t\t\t\t\t\t\t\t individuals_sampled_in, \n\t\t\t\t\t\t\t\t individuals_population_in, \n\t\t\t\t\t\t\t\t linkage_counts_in, \n\t\t\t\t\t\t\t\t verbose_output)\n\t \n\t\n\t },\n\t\n\t # Condition handler: If an error condition occurs:\n\t \n\t error = function(condition) {\n\t \n\t message(\"Execution of function: prep_p_hat() failed. \\n\")\n\t \n\t conditionMessage(condition)\n\t \n\t message(\"See ?prep_p_hat() to execute step separately for debugging. \\n\")\n\t \n\t # Exit function rather than chug-along\n\t # return(NULL)\n\t stop(condition)\t \n\t \n\t },\n\n # Statements to execute at the end regardless of success or error.\n\t \n\t finally = NULL\n\t\n\t)\n\n\n\t# Calculate p_hat\n\n\tresults_get_p_hat <- tryCatch({\n\t \n\t # Condition: Try and execute function get_p_hat() a.k.a estimate_p_hat()\n\t \n\t if (verbose_output) message(\"Executing function: estimate_p_hat(). \\n\")\n\t \n get_p_hat(results_prepare_input_for_get_p_hat)\t \n\t\n\t },\n\t\n\t # Condition handler: If an error condition occurs:\n\t \n\t error = function(condition) {\n\t \n\t message(\"Execution of function: estimate_p_hat() failed. \\n\")\n\t \n\t conditionMessage(condition)\n\t \n\t message(\"See ?estimate_p_hat() to execute step separately for debugging. \\n\")\n\t \n\t # Exit function rather than chug-along\n\t # return(NULL)\n\t stop(condition)\t \n\t \n\t },\n\n # Statements to execute at the end regardless of success or error.\n\t \n\t finally = NULL\n\t\n\t)\n\n\n\n\tif (detailed_report) {\n\n\n\t\t# Calculate the probability that a pair of pathogen sequences is from a specific \n\t\t# population group pairing and is linked\n\n\t\tresults_get_prob_group_pairing_and_linked <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_prob_group_pairing_and_linked() a.k.a estimate_prob_group_pairing_and_linked()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_prob_group_pairing_and_linked(). \\n\")\n\t\t\n\t\t\tget_prob_group_pairing_and_linked(results_get_p_hat, individuals_population_in, verbose_output)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_prob_group_pairing_and_linked() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_prob_group_pairing_and_linked() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t\t# Calculate theta_hat, the probability that a pair of pathogen sequences is from \n\t\t# a specific population group pairing given that the pair is linked\n\n\t\tresults_get_theta_hat <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_theta_hat() a.k.a estimate_theta_hat()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_theta_hat(). \\n\")\n\t\t\n\t\t\tget_theta_hat(results_get_prob_group_pairing_and_linked)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_theta_hat() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_theta_hat() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t\t# Calculate c_hat, the probability that a randomly selected pathogen sequence \n\t\t# in one population group links to at least one pathogen sequence in another\n\t\t# population group i.e. probability of clustering. This excludes linkage to \n\t\t# itself when clustering is estimated within populaton groups. \n\n\t\tresults_get_c_hat <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_c_hat() a.k.a estimate_c_hat()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_c_hat(). \\n\")\n\t\t\n\t\t\tget_c_hat(results_get_theta_hat)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_c_hat() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_c_hat() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t\t# Calculate simultaneous confidence intervals at the 5% significance level\n\n\t\toutput <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_multinomial_proportion_conf_ints_extended() a.k.a estimate_multinom_ci()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_multinom_ci(). \\n\")\n\t\t\n\t\t\tget_multinomial_proportion_conf_ints_extended(results_get_c_hat, detailed_report = TRUE)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_multinom_ci() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_multinom_ci() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t} else {\n\n\t\t# Calculate theta_hat, the probability that a pair of pathogen sequences is from \n\t\t# a specific population group pairing given that the pair is linked\n\n\t\tresults_get_theta_hat <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_theta_hat() a.k.a estimate_theta_hat()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_theta_hat(). \\n\")\n\t\t\n\t\t\tresults_get_theta_hat <- get_theta_hat(results_get_p_hat)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_theta_hat() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_theta_hat() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t\t# Calculate simultaneous confidence intervals at the 5% significance level with the Goodman method\n\n\t\toutput <- tryCatch({\n\t\t\n\t\t\t# Condition: Try and execute function get_multinomial_proportion_conf_ints_extended() a.k.a estimate_multinom_ci()\n\t \n\t\t\tif (verbose_output) message(\"Executing function: estimate_multinom_ci(). \\n\")\n\t\t\n\t\t\tget_multinomial_proportion_conf_ints_extended(results_get_theta_hat, detailed_report = FALSE)\t \n\t\n\t\t\t},\n\t\n\t\t\t# Condition handler: If an error condition occurs:\n\t\t\n\t\t\terror = function(condition) {\n\t\t\n\t\t\t\tmessage(\"Execution of function: estimate_multinom_ci() failed. \\n\")\n\t\t\t\n\t\t\t\tconditionMessage(condition)\n\t\t\t\n\t\t\t\tmessage(\"See ?estimate_multinom_ci() to execute step separately for debugging. \\n\")\n\t\t\t\n\t\t\t\t# Exit function rather than chug-along\n\t\t\t\t# return(NULL)\n\t\t\t\tstop(condition)\t \n\t\t\t\n\t\t\t},\n\n\t\t\t# Statements to execute at the end regardless of success or error.\n\t\t\n\t\t\tfinally = NULL\n\t\n\t\t)\n\n\t}\n\n\n\t# List of items to return\n\tbase::list(flows_dataset = output)\n\t\t\n\n}\n\n\n\n\n# Function: prepare_input_for_get_p_hat ---------------------------\n#\n# goal: Generate variables required for calculating p_hat\n#\n# parameters: \n#\n#\n# group_in (character) A vector indicating population groups/strata (e.g. communities, age-groups, genders or trial arms) between which transmission flows will be evaluated, \n# individuals_sampled_in (numeric) A vector indicating the number of individuals sampled per population group, \n# individuals_population_in (numeric) A vector of the estimated number of individuals per population group, \n# linkage_counts_in A data.frame of counts of linked pairs identified between samples of each population pairing of interest.\n# The data.frame should contain the following three fields: H1_group (character), H2_group (character), number_linked_pairs_observed (numeric).\n# For a population group pairing, H1_group and H2_group denote population groups 1 and 2 respectively; \n# and number_linked_pairs_observed denotes the number of observed directed transmission pairs between samples from population groups 1 and 2.\n# verbose_output (boolean) A value to display intermediate output \n#\n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2\n#\n# ------------------------------------------------------------------------------------\n\n\nprepare_input_for_get_p_hat <- function(group_in, \n individuals_sampled_in, \n individuals_population_in, \n linkage_counts_in, \n verbose_output = FALSE) {\n\n\t# Assemble dataset\n\tgroup <- base::factor(group_in)\n\n\tindividuals_sampled <- base::as.numeric(individuals_sampled_in)\n\n\tindividuals_population <- base::as.numeric(individuals_population_in)\n\n\tm <- base::data.frame(group, individuals_sampled, individuals_population)\n\n # View dataset structure\n\tif (verbose_output) utils::str(m)\n\n\n\t# Calculate number of groups\n\tn_groups <- base::nlevels(m$group)\n\n\t# Get all possible group pairings\n\tgroup_permutations <- base::data.frame(gtools::permutations(n_groups, 2, base::as.character(m$group), repeats.allowed = TRUE))\n\n\tbase::names(group_permutations) <- base::c(\"H1_group\", \"H2_group\")\n\n # View dataset structure\n\tif (verbose_output) utils::str(group_permutations)\t\n\n\n\n\tget_max_possible_pairs <- function(df_group_permutations, df_number_hosts_per_group) {\n\n\n if (verbose_output) {\n \n\t\t\tbase::writeLines(\"\\nstr(df_group_permutations): \\n\")\n\t\t\tutils::str(df_group_permutations)\n\t\t\n\t\t\tbase::writeLines(\"str(df_number_hosts_per_group): \\n\")\n\t\t\tutils::str(df_number_hosts_per_group)\n \n }\n\n\n\t\t# Calculate max distinct possible pairs in sample for each group pairing\n\n\t\tgroup_1 <- df_group_permutations[[\"H1_group\"]]\n\t\tnum_hosts_group_1 <- df_number_hosts_per_group$individuals_sampled[df_number_hosts_per_group$group == group_1]\n\n if (verbose_output) {\n \n\t\t\tbase::writeLines(paste0(\"\\nNumber of hosts in group 1: \", group_1, \"\\n\"))\n\t\t\tbase::print(num_hosts_group_1)\n \n }\n \n\t\tgroup_2 <- df_group_permutations[[\"H2_group\"]]\n\t\tnum_hosts_group_2 <- df_number_hosts_per_group$individuals_sampled[df_number_hosts_per_group$group == group_2]\n\n if (verbose_output) {\n \n\t\t\tbase::writeLines(paste0(\"\\nNumber of hosts in group 2: \", group_2, \"\\n\"))\n\t\t\tbase::print(num_hosts_group_2)\n \n }\n \n\t\tif (verbose_output) base::writeLines(\"Max distinct possible linked pairs in sample for current group pairing i.e. individuals_sampled_group_1 * individuals_sampled_group_2: \\n\")\n\t\tif (group_1 == group_2 & !(num_hosts_group_1 == 1)) {\n\t\t\n\t\t max_possible_pairs_in_sample <- (num_hosts_group_1 * (num_hosts_group_1 - 1)) / 2\n\t\t\n\t\t} else {\n\t\t\n\t\t max_possible_pairs_in_sample <- num_hosts_group_1 * num_hosts_group_2\n\t\t\n\t\t}\n\t\t\n\t\tif (verbose_output) base::print(max_possible_pairs_in_sample)\n\n\n\t\t# Calculate max distinct possible pairs in population for each group pairing\n\n individuals_population_group_1 <- df_number_hosts_per_group$individuals_population[df_number_hosts_per_group$group == group_1]\n \n\t\tif (verbose_output) {\n\t\t\n\t\t base::writeLines(\"\\nEstimated number of individuals in population group 1: \\n\")\n\t\t base::print(individuals_population_group_1)\n\t\t}\n\t\t\n\n individuals_population_group_2 <- df_number_hosts_per_group$individuals_population[df_number_hosts_per_group$group == group_2]\n \n\t\tif (verbose_output) {\n\t\t\n\t\t base::writeLines(\"\\nEstimated number of individuals in population group 2: \\n\")\n\t\t base::print(individuals_population_group_2)\n\t\t}\n \n\n\t\tif (verbose_output) base::writeLines(\"Max distinct possible linked pairs in population for current group pairing i.e. individuals_population_group_1 * individuals_population_group_2: \\n\")\n\t\tif (group_1 == group_2) {\n\n\t\t max_possible_pairs_in_population <- (individuals_population_group_1 * (individuals_population_group_1 - 1)) / 2\n\t\t\n\t\t} else {\n\n\t\t max_possible_pairs_in_population <- individuals_population_group_1 * individuals_population_group_2\n\t\t\n\t\t}\n\n\t\tif (verbose_output) base::print(max_possible_pairs_in_population)\n\n\n\t\toutput <- data.frame(\"H1_group\" = group_1, \"H2_group\" = group_2, \"number_hosts_sampled_group_1\" = num_hosts_group_1, \"number_hosts_sampled_group_2\" = num_hosts_group_2, \"number_hosts_population_group_1\" = individuals_population_group_1, \"number_hosts_population_group_2\" = individuals_population_group_2, max_possible_pairs_in_sample, max_possible_pairs_in_population)\n\n\t\toutput\n\n\t}\n\n\n\tresult_get_max_possible_pairs <- base::apply(group_permutations, 1, get_max_possible_pairs, m)\n\n\n # Assemble entries in list: result_get_max_possible_pairs into a data.frame using row bind\n\tnumber_hosts_per_group_pairing <- base::data.frame()\n\n\tfor (item in base::seq_along(result_get_max_possible_pairs)) { number_hosts_per_group_pairing <- base::rbind(number_hosts_per_group_pairing, result_get_max_possible_pairs[[item]]) }\n\n\n # Attach counts for the number of highly supported linked pairs observed between each group pairing\n\n\t# Important! Number of observed links was set to zero where no linked pairs were detected by phyloscanner\n\t# between group pairings \n\n number_hosts_per_group_pairing <- dplyr::left_join(number_hosts_per_group_pairing, linkage_counts_in, by = c(\"H1_group\", \"H2_group\"))\n number_hosts_per_group_pairing$num_linked_pairs_observed[is.na(number_hosts_per_group_pairing$num_linked_pairs_observed)] <- 0\n\t\n\tnumber_hosts_per_group_pairing\n\n}\n\n\n\n# Function: get_p_hat ---------------------------\n#\n# Goal: Compute probability that pathogen sequences from two individuals randomly sampled from their respective \n# population groups (e.g. communities, age-groups, genders or trial arms) are linked.\n# \n# Example: For a group pairing (u,v) this would be the fraction of distinct possible\n# pairs between samples from groups u and v that are linked. Note: The number\n# of distinct possible (u,v) pairs in the sample is the product of sampled \n# individuals in groups u and v. If u = v, distinct possible pairs is the \n# number of individuals sampled in population group u choose 2.\n#\n# parameters:\n#\n# df_counts A data.frame returned by the function: \n# prepare_input_for_get_p_hat()\n# \n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2\n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n#\n# ------------------------------------------------------------------------------------\n\n \nget_p_hat <- function(df_counts) {\n\n df_counts$p_hat <- df_counts$num_linked_pairs_observed / df_counts$max_possible_pairs_in_sample\n\n df_counts\n\n}\n\n\n\n# Function: get_prob_group_pairing_and_linked ---------------------------\n#\n# Goal: Compute probability that a pair is from a specific population group pairing and is linked.\n# Example: For a group pairing (u,v), prob. that a pair is from (u,v) and linked is:\n# (N_uv / N_choose_2) * p_hat_uv\n# where:\n# N_uv = N_u * N_v i.e. maximum distinct possible (u,v) pairs in population.\n# p_hat_uv = fraction of observed (u,v) pairs between samples from population groups \n# u and v that are linked.\n# N choose 2 or (N * (N - 1))/2 i.e. all distinct possible pairs in population.\n#\n# parameters:\n#\n# df_counts_and_p_hat A data.frame returned by function: \n# get_p_hat()\n# individuals_population_in (numeric) A vector of the estimated number of individuals \n# per population group \n# verbose_output (boolean) A value to display intermediate output \n#\n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2\n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n# prob_group_pairing_and_linked (numeric) Probability that a pair of pathogen sequences is from a specific population group pairing and is linked\n#\n# ------------------------------------------------------------------------------------\n\n\nget_prob_group_pairing_and_linked <- function(df_counts_and_p_hat, individuals_population_in,\n verbose_output = FALSE) {\n\n # View dataset structure\n\tif (verbose_output) utils::str(df_counts_and_p_hat)\n\n # Sum up estimated number of individuals in each population group to get total population\n\tindividuals_population <- base::as.numeric(individuals_population_in)\n individuals_population_total <- base::sum(individuals_population)\n if (verbose_output) base::print(individuals_population_total)\n \n # Get all distinct possible pairs in population\n max_possible_pairs_in_total_population <- (individuals_population_total * (individuals_population_total - 1)) / 2\n \n df_counts_and_p_hat$prob_group_pairing_and_linked <- (df_counts_and_p_hat$max_possible_pairs_in_population / max_possible_pairs_in_total_population) * df_counts_and_p_hat$p_hat\n \n df_counts_and_p_hat\n\n}\n\n\n\n# Function: get_theta_hat ---------------------------\n#\n# Goal: Compute the conditional probability that a pair is from a specific population group\n# pairing given the pair is linked.\n# Example: For a group pairing (u,v), theta_hat denotes estimated transmission\n# flows within and between population groups u and v adjusted for sampling\n# heterogeneity.\n#\n# parameters:\n#\n# df_counts_and_p_hat A data.frame returned by the function: \n# get_p_hat()\n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2 \n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n# est_linkedpairs_in_population (numeric) Estimated transmission pairs between population groups 1 and 2\n# theta_hat (numeric) Estimated transmission flows or relative probability of transmission within and between population groups 1 and 2 adjusted\n# for sampling heterogeneity. More precisely, the conditional probability that a pair of pathogen sequences is from a specific population \n# group pairing given that the pair is linked.\n#\n# ------------------------------------------------------------------------------------\n\n\nget_theta_hat <- function(df_counts_and_p_hat) {\n\n\tdf_counts_and_p_hat$est_linkedpairs_in_population <- df_counts_and_p_hat$max_possible_pairs_in_population * df_counts_and_p_hat$p_hat\n\n\tdf_counts_and_p_hat$theta_hat <- df_counts_and_p_hat$est_linkedpairs_in_population / base::sum(df_counts_and_p_hat$est_linkedpairs_in_population)\n\n\tdf_counts_and_p_hat\n\n}\n\n\n\n# Function: get_c_hat ---------------------------\n#\n# Goal: Compute c_hat, for a group pairing (u,v) c_hat is the probability that a pathogen sequence from\n# an individual in population group u links with pathogen sequences from one or more other individuals\n# in population group v (excluding itself if u = v) i.e. probability of clustering.\n#\n# parameters:\n#\n# df_counts_and_p_hat A data.frame returned by the function: \n# get_p_hat()\n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2 \n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n# c_hat (numeric) Probability that a randomly selected pathogen sequence in one population group links to at least \n# one pathogen sequence in another population group i.e. probability of clustering\n#\n# ------------------------------------------------------------------------------------\n\n\nget_c_hat <- function(df_counts_and_p_hat) {\n\n\tdf_counts_and_p_hat$c_hat <- 1 - ((1 - df_counts_and_p_hat$p_hat) ^ df_counts_and_p_hat$number_hosts_population_group_2)\n\n\tdf_counts_and_p_hat\n\n}\n\n\n\n# Calculate simultaneous confidence intervals for a multinomial proportion\n#---------------------------\n\n\n# Function: get_multinomial_proportion_conf_ints ---------------------------\n#\n# Goal: Compute simultaneous confidence intervals at the 5% significance level\n#\n# Reminder: Goodman CIs work for fewer cells with larger counts and Sison-Glaz many cells with smaller counts\n#\n# parameters:\n#\n# df_theta_hat A data.frame returned by the function: \n# get_theta_hat()\n# detailed_report (boolean) A value to produce detailed output of the analysis \n#\n# returns: a data.frame containing:\n#\n#\n# H1_group (Factor) Name of population group 1 \n# H2_group (Factor) Name of population group 2 \n# number_hosts_sampled_group_1 (numeric) Number of individuals sampled from population group 1\n# number_hosts_sampled_group_2 (numeric) Number of individuals sampled from population group 2\n# number_hosts_population_group_1 (numeric) Estimated number of individuals in population group 1\n# number_hosts_population_group_2 (numeric) Estimated number of individuals in population group 2\n# max_possible_pairs_in_sample (numeric) Number of distinct possible transmission pairs between individuals sampled from population groups 1 and 2\n# max_possible_pairs_in_population (numeric) Number of distinct possible transmission pairs between individuals in population groups 1 and 2\n# num_linked_pairs_observed (numeric) Number of observed directed transmission pairs between samples from population groups 1 and 2 \n# p_hat (numeric) Probability that pathogen sequences from two individuals randomly sampled from their respective population groups are linked \n# est_linkedpairs_in_population (numeric) Estimated transmission pairs between population groups 1 and 2\n# theta_hat (numeric) Estimated transmission flows or relative probability of transmission within and between population groups 1 and 2 adjusted\n# for sampling heterogeneity. More precisely, the conditional probability that a pair of pathogen sequences is from a specific population \n# group pairing given that the pair is linked.\n# obs_trm_pairs_est_goodman (numeric) Point estimate, Goodman method Confidence intervals for observed transmission pairs\n# obs_trm_pairs_lwr_ci_goodman (numeric) Lower bound of Goodman confidence interval \n# obs_trm_pairs_upr_ci_goodman (numeric) Upper bound of Goodman confidence interval \n# est_goodman (numeric) Point estimate, Goodman method Confidence intervals for estimated transmission flows\n# lwr_ci_goodman (numeric) Lower bound of Goodman confidence interval \n# upr_ci_goodman (numeric) Upper bound of Goodman confidence interval \n#\n#\n# The following additional fields are returned if the detailed_report \n# flag is set\n#\n# est_goodman_cc (numeric) Point estimate, Goodman method Confidence intervals with continuity correction\n# lwr_ci_goodman_cc (numeric) Lower bound of Goodman confidence interval \n# upr_ci_goodman_cc (numeric) Upper bound of Goodman confidence interval \n# est_sisonglaz (numeric) Point estimate, Sison-Glaz method Confidence intervals\n# lwr_ci_sisonglaz (numeric) Lower bound of Sison-Glaz confidence interval \n# upr_ci_sisonglaz (numeric) Upper bound of Sison-Glaz confidence interval \n# est_qhurst_acswr (numeric) Point estimate, Queensbury-Hurst method Confidence intervals via ACSWR r package \n# lwr_ci_qhurst_acswr (numeric) Lower bound of Queensbury-Hurst confidence interval \n# upr_ci_qhurst_acswr (numeric) Upper bound of Queensbury-Hurst confidence interval \n# est_qhurst_coinmind (numeric) Point estimate, Queensbury-Hurst method Confidence intervals via CoinMinD r package \n# lwr_ci_qhurst_coinmind (numeric) Lower bound of Queensbury-Hurst confidence interval\n# upr_ci_qhurst_coinmind (numeric) Upper bound of Queensbury-Hurst confidence interval\n# lwr_ci_qhurst_adj_coinmind (numeric) Lower bound of Queensbury-Hurst confidence interval adjusted \n# upr_ci_qhurst_adj_coinmind (numeric) Upper bound of Queensbury-Hurst confidence interval adjusted\n#\n# ------------------------------------------------------------------------------------\n\n \nget_multinomial_proportion_conf_ints_extended <- function(df_theta_hat, detailed_report = FALSE) {\n\n # Extend MultinomCI function in DescTools to compute Goodman confidence intervals\n # with a continuity correction i.e. goodmancc. \n # Acknowledgements: \n # (Steve Cherry, 1996) A Comparison of Confidence Interval Methods for Habitat Use-Availability Studies.\n # The Journal of Wildlife Management, Jul., 1996, Vol. 60, No. 3 (Jul., 1996), pp. 653-658\n # Goodman continuity correction described on pg. 655 \n\t\n\t# Define function:\n\tMultinomCI_mod <- function (x, conf.level = 0.95, sides = c(\"two.sided\", \"left\", \n\t\t\"right\"), method = c(\"sisonglaz\", \"cplus1\", \"goodman\", \"goodmancc\",\n\t\t\"wald\", \"waldcc\", \"wilson\")) {\n\n\t\t.moments <- function(c, lambda) {\n\t\t\ta <- lambda + c\n\t\t\tb <- lambda - c\n\t\t\tif (b < 0) \n\t\t\t\tb <- 0\n\t\t\tif (b > 0) \n\t\t\t\tden <- stats::ppois(a, lambda) - stats::ppois(b - 1, lambda)\n\t\t\tif (b == 0) \n\t\t\t\tden <- stats::ppois(a, lambda)\n\t\t\tmu <- mat.or.vec(4, 1)\n\t\t\tmom <- mat.or.vec(5, 1)\n\t\t\tfor (r in 1:4) {\n\t\t\t\tpoisA <- 0\n\t\t\t\tpoisB <- 0\n\t\t\t\tif ((a - r) >= 0) {\n\t\t\t\t\tpoisA <- stats::ppois(a, lambda) - stats::ppois(a - r, lambda)\n\t\t\t\t}\n\t\t\t\tif ((a - r) < 0) {\n\t\t\t\t\tpoisA <- stats::ppois(a, lambda)\n\t\t\t\t}\n\t\t\t\tif ((b - r - 1) >= 0) {\n\t\t\t\t\tpoisB <- stats::ppois(b - 1, lambda) - stats::ppois(b - r - \n\t\t\t\t\t 1, lambda)\n\t\t\t\t}\n\t\t\t\tif ((b - r - 1) < 0 && (b - 1) >= 0) {\n\t\t\t\t\tpoisB <- stats::ppois(b - 1, lambda)\n\t\t\t\t}\n\t\t\t\tif ((b - r - 1) < 0 && (b - 1) < 0) {\n\t\t\t\t\tpoisB <- 0\n\t\t\t\t}\n\t\t\t\tmu[r] <- (lambda^r) * (1 - (poisA - poisB)/den)\n\t\t\t}\n\t\t\tmom[1] <- mu[1]\n\t\t\tmom[2] <- mu[2] + mu[1] - mu[1]^2\n\t\t\tmom[3] <- mu[3] + mu[2] * (3 - 3 * mu[1]) + (mu[1] - \n\t\t\t\t3 * mu[1]^2 + 2 * mu[1]^3)\n\t\t\tmom[4] <- mu[4] + mu[3] * (6 - 4 * mu[1]) + mu[2] * (7 - \n\t\t\t\t12 * mu[1] + 6 * mu[1]^2) + mu[1] - 4 * mu[1]^2 + \n\t\t\t\t6 * mu[1]^3 - 3 * mu[1]^4\n\t\t\tmom[5] <- den\n\t\t\treturn(mom)\n\t\t}\n\t\t.truncpoi <- function(c, x, n, k) {\n\t\t\tm <- matrix(0, k, 5)\n\t\t\tfor (i in 1L:k) {\n\t\t\t\tlambda <- x[i]\n\t\t\t\tmom <- .moments(c, lambda)\n\t\t\t\tfor (j in 1L:5L) {\n\t\t\t\t\tm[i, j] <- mom[j]\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i in 1L:k) {\n\t\t\t\tm[i, 4] <- m[i, 4] - 3 * m[i, 2]^2\n\t\t\t}\n\t\t\ts <- colSums(m)\n\t\t\ts1 <- s[1]\n\t\t\ts2 <- s[2]\n\t\t\ts3 <- s[3]\n\t\t\ts4 <- s[4]\n\t\t\tprobn <- 1/(stats::ppois(n, n) - stats::ppois(n - 1, n))\n\t\t\tz <- (n - s1)/sqrt(s2)\n\t\t\tg1 <- s3/(s2^(3/2))\n\t\t\tg2 <- s4/(s2^2)\n\t\t\tpoly <- 1 + g1 * (z^3 - 3 * z)/6 + g2 * (z^4 - 6 * z^2 + \n\t\t\t\t3)/24\n\t\t\t+g1^2 * (z^6 - 15 * z^4 + 45 * z^2 - 15)/72\n\t\t\tf <- poly * exp(-z^2/2)/(sqrt(2) * gamma(0.5))\n\t\t\tprobx <- 1\n\t\t\tfor (i in 1L:k) {\n\t\t\t\tprobx <- probx * m[i, 5]\n\t\t\t}\n\t\t\treturn(probn * probx * f/sqrt(s2))\n\t\t}\n\t\tn <- sum(x, na.rm = TRUE)\n\t\tk <- length(x)\n\t\tp <- x/n\n\t\tif (missing(method)) \n\t\t\tmethod <- \"sisonglaz\"\n\t\tif (missing(sides)) \n\t\t\tsides <- \"two.sided\"\n\t\tsides <- match.arg(sides, choices = c(\"two.sided\", \"left\", \n\t\t\t\"right\"), several.ok = FALSE)\n\t\tif (sides != \"two.sided\") \n\t\t\tconf.level <- 1 - 2 * (1 - conf.level)\n\t\tmethod <- match.arg(arg = method, choices = c(\"sisonglaz\", \n\t\t\t\"cplus1\", \"goodman\", \"goodmancc\", \"wald\", \"waldcc\", \"wilson\"))\n\t\tif (method == \"goodman\") {\n\t\t\tq.chi <- stats::qchisq(conf.level, k - 1)\n\t\t\tlci <- (q.chi + 2 * x - sqrt(q.chi * (q.chi + 4 * x * \n\t\t\t\t(n - x)/n)))/(2 * (n + q.chi))\n\t\t\tuci <- (q.chi + 2 * x + sqrt(q.chi * (q.chi + 4 * x * \n\t\t\t\t(n - x)/n)))/(2 * (n + q.chi))\n\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, lci), upr.ci = pmin(1, \n\t\t\t\tuci))\n\t\t}\n\t\telse if (method == \"goodmancc\") {\n\t\t\tq.chi <- stats::qchisq(conf.level, k - 1)\n\t\t\tlci <- (q.chi + 2 * (x - 0.5) - sqrt(q.chi * (q.chi + 4 * (x - 0.5) * \n\t\t\t\t(n - x + 0.5)/n)))/(2 * (n + q.chi))\n\t\t\tuci <- (q.chi + 2 * (x + 0.5) + sqrt(q.chi * (q.chi + 4 * (x + 0.5) * \n\t\t\t\t(n - x - 0.5)/n)))/(2 * (n + q.chi))\n\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, lci), upr.ci = pmin(1, \n\t\t\t\tuci))\n\t\t}\n\t\telse if (method == \"wald\") {\n\t\t\tq.chi <- stats::qchisq(conf.level, 1)\n\t\t\tlci <- p - sqrt(q.chi * p * (1 - p)/n)\n\t\t\tuci <- p + sqrt(q.chi * p * (1 - p)/n)\n\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, lci), upr.ci = pmin(1, \n\t\t\t\tuci))\n\t\t}\n\t\telse if (method == \"waldcc\") {\n\t\t\tq.chi <- stats::qchisq(conf.level, 1)\n\t\t\tlci <- p - sqrt(q.chi * p * (1 - p)/n) - 1/(2 * n)\n\t\t\tuci <- p + sqrt(q.chi * p * (1 - p)/n) + 1/(2 * n)\n\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, lci), upr.ci = pmin(1, \n\t\t\t\tuci))\n\t\t}\n\t\telse if (method == \"wilson\") {\n\t\t\tq.chi <- stats::qchisq(conf.level, 1)\n\t\t\tlci <- (q.chi + 2 * x - sqrt(q.chi^2 + 4 * x * q.chi * \n\t\t\t\t(1 - p)))/(2 * (q.chi + n))\n\t\t\tuci <- (q.chi + 2 * x + sqrt(q.chi^2 + 4 * x * q.chi * \n\t\t\t\t(1 - p)))/(2 * (q.chi + n))\n\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, lci), upr.ci = pmin(1, \n\t\t\t\tuci))\n\t\t}\n\t\telse {\n\t\t\tconst <- 0\n\t\t\tpold <- 0\n\t\t\tfor (cc in 1:n) {\n\t\t\t\tpoi <- .truncpoi(cc, x, n, k)\n\t\t\t\tif (poi > conf.level && pold < conf.level) {\n\t\t\t\t\tconst <- cc\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tpold <- poi\n\t\t\t}\n\t\t\tdelta <- (conf.level - pold)/(poi - pold)\n\t\t\tconst <- const - 1\n\t\t\tif (method == \"sisonglaz\") {\n\t\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, p - const/n), \n\t\t\t\t\tupr.ci = pmin(1, p + const/n + 2 * delta/n))\n\t\t\t}\n\t\t\telse if (method == \"cplus1\") {\n\t\t\t\tres <- cbind(est = p, lwr.ci = pmax(0, p - const/n - \n\t\t\t\t\t1/n), upr.ci = pmin(1, p + const/n + 1/n))\n\t\t\t}\n\t\t}\n\t\tif (sides == \"left\") \n\t\t\tres[3] <- 1\n\t\telse if (sides == \"right\") \n\t\t\tres[2] <- 0\n\t\treturn(res)\n\t}\n\n\t# Acknowledgments\n\t# QH (Queensbury-Hurst) confidence intervals function sourced from CoinMinD package and tweaked \n\t# to report and store the estimate and confidence intervals. \n\t# Default behaviour: Print confidence intervals to screen without reporting the estimate. \n\n\t# Define function:\n\tQH_coinmind_mod <- function(inpmat, alpha) {\n\n\t\tk = base::length(inpmat)\n\t\ts = base::sum(inpmat)\n\t\tchi = stats::qchisq(1 - alpha, df = k - 1)\n\t\tpi = inpmat / s\n\t\tQH.UL = (chi + 2 * inpmat + sqrt(chi * chi + 4 * inpmat * \n\t\t\tchi * (1 - pi)))/(2 * (chi + s))\n\t\tQH.LL = (chi + 2 * inpmat - sqrt(chi * chi + 4 * inpmat * \n\t\t\tchi * (1 - pi)))/(2 * (chi + s))\n\t\tLLA = 0\n\t\tULA = 0\n\t\tfor (r in 1:base::length(inpmat)) {\n\t\t\tif (QH.LL[r] < 0) \n\t\t\t\tLLA[r] = 0\n\t\t\telse LLA[r] = QH.LL[r]\n\t\t\tif (QH.UL[r] > 1) \n\t\t\t\tULA[r] = 1\n\t\t\telse ULA[r] = QH.UL[r]\n\t\t}\n\t\tdiA = ULA - LLA\n\t\tVOL = base::round(prod(diA), 8)\n\n\t\toutput <- base::cbind(\"est_qhurst_coinmind\" = pi, \"lwr_ci_qhurst_coinmind\" = QH.LL, \"upr_ci_qhurst_coinmind\" = QH.UL, \"lwr_ci_qhurst_adj_coinmind\" = LLA, \"upr_ci_qhurst_adj_coinmind\" = ULA)\n\n\t\toutput\n\n\t}\n\n\n\t# Acknowledgments\n\t# QH (Queensbury-Hurst) confidence intervals function sourced from ACSWR package and tweaked \n\t# to report the estimate as well as confidence intervals. \n\t# Default behaviour: Report confidence intervals without the estimate. \n\n\t# Define function:\n\tQH_CI_acswr_mod <- function(x, alpha) {\n\n\t k <- base::length(x); n <- base::sum(x)\n \n\t QH_est <- x / n\n \n\t QH_lcl <- (1 / (2 * (base::sum(x) + stats::qchisq(1 - alpha / k, k - 1)))) * \n\t\t {\n\t\t\t stats::qchisq(1 - alpha / k, k - 1) + 2 * x - base::sqrt( stats::qchisq(1 - alpha / k, k - 1) * \n\t\t\t (stats::qchisq(1 - alpha / k, k - 1) + 4 * x *(base::sum(x) - x) / base::sum(x))) \n\t \n\t\t }\n \n\t QH_ucl <- (1 / (2 * (base::sum(x) + stats::qchisq(1 - alpha / k, k - 1)))) *\n\t\t {\n\t\t\t stats::qchisq(1 - alpha / k, k - 1) + 2 * x + base::sqrt( stats::qchisq(1 - alpha / k, k - 1) *\n\t\t\t (stats::qchisq(1 - alpha / k, k - 1) + 4 * x * (base::sum(x) - x) / base::sum(x))) \n\t\t } \n \n\t return(base::cbind(\"est_qhurst_acswr\" = QH_est, \"lwr_ci_qhurst_acswr\" = QH_lcl, \"upr_ci_qhurst_acswr\" = QH_ucl))\n\n\t}\n\n\n # compute multi-nomial confidence intervals\n \n # Note: We scale the estimated transmission pairs in the population such that the sum of the weights\n # is equal to the observed number of transmission pairs. This is a common approach in survey sampling.\n # Basically, we express the estimated transmission pairs in the population as proportions then multiply \n # by the sum of the observed counts\n weighted_est_linkedpairs_in_population <- (df_theta_hat$est_linkedpairs_in_population / base::sum(df_theta_hat$est_linkedpairs_in_population)) * base::sum(df_theta_hat$num_linked_pairs_observed)\n\n # compute Goodman confidence intervals for observed transmission events\n obs_trm_pairs_ci_goodman <- base::cbind(df_theta_hat, MultinomCI_mod(df_theta_hat$num_linked_pairs_observed, method=\"goodman\"))\n obs_trm_pairs_ci_goodman <- obs_trm_pairs_ci_goodman %>% dplyr::rename(obs_trm_pairs_est_goodman = est, obs_trm_pairs_lwr_ci_goodman = lwr.ci, obs_trm_pairs_upr_ci_goodman = upr.ci)\n \n \t# compute Goodman intervals\n df_theta_hat_goodman <- base::cbind(obs_trm_pairs_ci_goodman, MultinomCI_mod(weighted_est_linkedpairs_in_population, method=\"goodman\"))\n df_theta_hat_goodman <- df_theta_hat_goodman %>% dplyr::rename(est_goodman = est, lwr_ci_goodman = lwr.ci, upr_ci_goodman = upr.ci)\n\n\n if (detailed_report) {\n \n\t\t# compute Goodman intervals with a continuity correction\n\t\tdf_theta_hat_goodman_cc <- base::cbind(df_theta_hat_goodman, MultinomCI_mod(weighted_est_linkedpairs_in_population, method=\"goodmancc\"))\n\t\tdf_theta_hat_goodman_cc <- df_theta_hat_goodman_cc %>% dplyr::rename(est_goodman_cc = est, lwr_ci_goodman_cc = lwr.ci, upr_ci_goodman_cc = upr.ci)\n\n\t\t\n\t\t# compute Sison-Glaz intervals\n\t\tdf_theta_hat_goodman_sisonglaz <- base::cbind(df_theta_hat_goodman_cc, MultinomCI_mod(weighted_est_linkedpairs_in_population, method=\"sisonglaz\"))\n\t\tdf_theta_hat_goodman_sisonglaz <- df_theta_hat_goodman_sisonglaz %>% dplyr::rename(est_sisonglaz = est, lwr_ci_sisonglaz = lwr.ci, upr_ci_sisonglaz = upr.ci)\n\t\n\t\t# compute Queensbury-Hurst intervals\n\t\tdf_theta_hat_goodman_sisonglaz_qhurst_acswr <- base::cbind(df_theta_hat_goodman_sisonglaz, QH_CI_acswr_mod(weighted_est_linkedpairs_in_population, 0.05))\n\n\t\tdf_theta_hat_goodman_sisonglaz_qhurst_acswr_coinmind <- base::cbind(df_theta_hat_goodman_sisonglaz_qhurst_acswr, QH_coinmind_mod(weighted_est_linkedpairs_in_population, 0.05))\n\t\n\t\tdf_theta_hat_goodman_sisonglaz_qhurst_acswr_coinmind <- df_theta_hat_goodman_sisonglaz_qhurst_acswr_coinmind %>% dplyr::arrange(-num_linked_pairs_observed)\n \t\t\n\t output <- df_theta_hat_goodman_sisonglaz_qhurst_acswr_coinmind\n\t \n\t} else {\n\t\n output <- df_theta_hat_goodman %>% dplyr::arrange(-num_linked_pairs_observed)\n\t\n\t}\n\n output\n\n}\n\n\n", "meta": {"hexsha": "53c3b48b4f84ec173b35cff8c74e7be38aa43a4a", "size": 50526, "ext": "r", "lang": "R", "max_stars_repo_path": "R/estimate_transmission_flows.r", "max_stars_repo_name": "magosil86/bumblebee", "max_stars_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/estimate_transmission_flows.r", "max_issues_repo_name": "magosil86/bumblebee", "max_issues_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-29T03:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T12:38:24.000Z", "max_forks_repo_path": "R/estimate_transmission_flows.r", "max_forks_repo_name": "magosil86/bumblebee", "max_forks_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2434325744, "max_line_length": 370, "alphanum_fraction": 0.6607093378, "num_tokens": 12295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.486245598430963}} {"text": "#' Drawing a sample from a fitted joint distribution\r\n#'\r\n#' @description \r\n#' This function draws a random sample from an existing fitted Weibull-log-normal\r\n#' (\\code{wln}) or Heffernan-Tawn (\\code{ht}) model for a given duration.\r\n#' \r\n#' @param jdistr a \\code{wln} or \\code{ht} joint distribution object, as the output from function \\code{\\link{fit_wln}}\r\n#' and \\code{\\link{fit_ht}} respectively.\r\n#' \r\n#' @param sim_year the period of the simulate data in equivalent number of years.\r\n#' \r\n#' @param perturbed_ht_residuals whether or not to the simulation from the Heffernan-Tawn (\\code{ht}) model should\r\n#' add a perturbation when sampling from the empirical residual distribution (default value is \\code{TRUE}). This\r\n#' argument is ignored when the input object is a Weibull-log-normal (\\code{wln}) distribution.\r\n#'\r\n#' @return The function returns \\code{data.table} object with two columns - wave\r\n#' height \\code{hs} and wave period and \\code{tp}.\r\n#'\r\n#' @examples\r\n#' \r\n#' # Load data\r\n#' data(ww3_pk)\r\n#' \r\n#' # Fit Heffernan-Tawn model with 0.95 marginal and dependence thresholds\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 100, dep_thresh_count = 100)\r\n#' \r\n#' # Draw the equivalent of 100-year of data from the fitted Heffernan-Tawn model with or without perturbed residuals\r\n#' sim_ht1 = sample_jdistr(jdistr = ht, sim_year = 100, perturbed_ht_residuals = FALSE)\r\n#' sim_ht2 = sample_jdistr(jdistr = ht, sim_year = 100)\r\n#' par(mfrow=c(1,2))\r\n#' plot(sim_ht1, pch=20, cex=.5, main=\"HT without perturbation\")\r\n#' plot(sim_ht2, pch=20, cex=.5, main=\"HT with perturbation\")\r\n#' \r\n#' # Fit Weibull-log-normal model\r\n#' wln = fit_wln(data = ww3_pk, npy = nrow(ww3_pk)/10)\r\n#'\r\n#' # Draw the equivalent of 100-year of data from the fitted Weibull-log-normal model\r\n#' sim_wln = sample_jdistr(jdistr = wln, sim_year = 100)\r\n#' plot(sim_wln, pch=20, cex=.5, main=\"WLN\")\r\n#' \r\n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}\r\n#' \r\n#' @export\r\nsample_jdistr = function(jdistr, sim_year, perturbed_ht_residuals = TRUE){\r\n \r\n if(class(jdistr)==\"ht\"){\r\n res = .sample_ht(jdistr, sim_year, perturbed_ht_residuals)\r\n }else if(class(jdistr)==\"wln\"){\r\n res = .sample_wln(jdistr, sim_year)\r\n }else{\r\n stop(\"Input class of distribution not supported.\")\r\n }\r\n return(res)\r\n}\r\n\r\n\r\n# Heffernan-Tawn ----------------------------------------------------------\r\n.sample_ht = function(ht, sim_year, perturbed_ht_residuals){\r\n \r\n set.seed(.seed_sampling)\r\n n_sim = sim_year*ht$npy\r\n\r\n # Sample overall freq\r\n res = ht$dep$dep_data[sample.int(.N, size = n_sim, replace = T), .(u_hs, u_tp)]\r\n rot_wb = res[, .N^(-1/6)]\r\n res[, u_hs:=pnorm(qnorm(u_hs)+rnorm(.N, 0, rot_wb))]\r\n res[, u_tp:=pnorm(qnorm(u_tp)+rnorm(.N, 0, rot_wb))]\r\n n_hs = res[u_hs>ht$dep$p_dep_thresh & u_hs>u_tp, .N]\r\n n_tp = res[u_tp>ht$dep$p_dep_thresh & u_tp>=u_hs, .N]\r\n \r\n # Sample hs & tp extreme in unif\r\n dep_data_hs = .sample_ht1(n_hs, ht$dep$hs$par, ht$dep$hs$resid, ht$dep$p_dep_thresh, perturbed_ht_residuals)\r\n res[u_hs>ht$dep$p_dep_thresh & u_hs>u_tp, c(\"u_hs\", \"u_tp\"):=dep_data_hs[, .(u_cond, u_dep)]]\r\n dep_data_tp = .sample_ht1(n_tp, ht$dep$tp$par, ht$dep$tp$resid, ht$dep$p_dep_thresh, perturbed_ht_residuals)\r\n res[u_tp>ht$dep$p_dep_thresh & u_tp>=u_hs, c(\"u_hs\", \"u_tp\"):=dep_data_tp[, .(u_dep, u_cond)]]\r\n\r\n # Convert to original scale\r\n n = length(ht$margin$hs$emp)\r\n res[, hs:=.convert_unif_to_origin(\r\n unif = u_hs, p_thresh = ht$margin$p_margin_thresh, gpd_par = ht$margin$hs$par, emp = ht$margin$hs$emp)]\r\n res[, tp:=.convert_unif_to_origin(\r\n unif = u_tp, p_thresh = ht$margin$p_margin_thresh, gpd_par = ht$margin$tp$par, emp = ht$margin$tp$emp)]\r\n \r\n return(res[, .(hs, tp)])\r\n}\r\n\r\n.sample_ht1 = function(n_sim, par, resid, p_dep_thresh, perturbed_ht_residuals){\r\n set.seed(.seed_sampling)\r\n a = par[1]\r\n b = par[2]\r\n sim_data = data.table(u_cond=runif(n_sim, p_dep_thresh, 1))\r\n sim_data[, l_cond:=.convert_unif_to_lap(u_cond)]\r\n resid_max = sim_data[, (1-a)*l_cond^(1-b)]\r\n if(perturbed_ht_residuals){\r\n resid_bw = bw.SJ(resid)\r\n extended_resid = resid+rnorm(length(resid)*100, 0, resid_bw)\r\n }else{\r\n extended_resid = resid\r\n }\r\n resid_sample = sapply(resid_max, function(x)sample(extended_resid[extended_resid=ht$dep$p_dep_thresh,lap_tp:=\r\n lap_hs*ht$dep$hs$par[[\"a\"]]+lap_hs^ht$dep$hs$par[[\"b\"]]*quantile(ht$dep$hs$resid, u_tp_hs)]\r\n calc_hs[u_hs>=ht$dep$p_dep_thresh, u_tp:=.convert_lap_to_unif(lap_tp)]\r\n calc_hs = calc_hs[u_hs>ht$dep$p_dep_thresh][u_hs>u_tp]\r\n calc_hs[, dir:=atan2(qnorm(u_hs), qnorm(u_tp))]\r\n \r\n # Generate by Tp|Hs model\r\n calc_tp = calc[, .(u_hs_tp=pnorm(cos(dir)*r), u_tp=pnorm(sin(dir)*r))]\r\n calc_tp[, lap_tp:=.convert_unif_to_lap(u_tp)]\r\n calc_tp[u_tp>=ht$dep$p_dep_thresh,lap_hs:=\r\n lap_tp*ht$dep$tp$par[[\"a\"]]+lap_tp^ht$dep$tp$par[[\"b\"]]*quantile(ht$dep$tp$resid, u_hs_tp)]\r\n calc_tp[u_tp>=ht$dep$p_dep_thresh, u_hs:=.convert_lap_to_unif(lap_hs)]\r\n calc_tp = calc_tp[u_tp>ht$dep$p_dep_thresh][u_tp>u_hs]\r\n calc_tp[, dir:=atan2(qnorm(u_hs), qnorm(u_tp))]\r\n \r\n # Generate low/low corner\r\n n_ll = calc[, .N]-calc_hs[, .N]-calc_tp[, .N]\r\n set.seed(.seed_sampling)\r\n res = ht$dep$dep_data[sample.int(.N, size = calc[, .N]/.target_rp_lb, replace = T), .(u_hs, u_tp)]\r\n # print(res[, .N])\r\n rot_wb = res[, .N^(-1/6)]\r\n res[, u_hs:=pnorm(qnorm(u_hs)+rnorm(.N, 0, rot_wb))]\r\n res[, u_tp:=pnorm(qnorm(u_tp)+rnorm(.N, 0, rot_wb))]\r\n res[, r:=sqrt(qnorm(u_hs)^2+qnorm(u_tp)^2)]\r\n res[, dir:=atan2(qnorm(u_hs), qnorm(u_tp))]\r\n res_ll = res[dir>max(calc_hs$dir) | dirquantile(r, 1-n_ll/res_ll[,.N])], .(dir_grp)]\r\n \r\n # Merge\r\n out = rbind(calc_hs[, .(u_hs, u_tp)], calc_tp[, .(u_hs, u_tp)], calc_ll[, .(u_hs, u_tp)])\r\n out[, hs:=.convert_unif_to_origin(\r\n unif = u_hs, p_thresh = ht$margin$p_margin_thresh,\r\n gpd_par = ht$margin$hs$par, emp = ht$margin$hs$emp)]\r\n out[, tp:=.convert_unif_to_origin(\r\n unif = u_tp, p_thresh = ht$margin$p_margin_thresh,\r\n gpd_par = ht$margin$tp$par, emp = ht$margin$tp$emp)]\r\n \r\n return(out[, .(hs, tp)])\r\n}\r\n\r\n\r\n# Weibull log-normal ------------------------------------------------------\r\n.sample_wln = function(wln, sim_year){\r\n set.seed(.seed_sampling)\r\n n_sim = round(wln$npy*sim_year)\r\n \r\n # Sample hs\r\n hs = rweibull(n_sim, shape = wln$hs$par[\"shape\"], scale = wln$hs$par[\"scale\"]) + wln$hs$par[\"loc\"]\r\n \r\n # sample tp cond on hs\r\n tp_norm_mean = wln$tp$par[1] + wln$tp$par[2] * (hs ^ wln$tp$par[3])\r\n # tp_norm_sd = wln$tp$par[4] + wln$tp$par[5] * exp(wln$tp$par[6] * hs)\r\n tp_norm_sd = pmax(.limit_zero, wln$tp$par[4] + wln$tp$par[5] * exp(wln$tp$par[6] * hs))\r\n tp = exp(rnorm(n_sim, tp_norm_mean, tp_norm_sd))\r\n \r\n res = data.table(hs, tp)\r\n return(res)\r\n}\r\n\r\n.sample_wln_is = function(wln, target_rp){\r\n \r\n n_sim = round(wln$npy*target_rp*.target_rp_ub)\r\n tail_prob = 1/(target_rp*.target_rp_lb*wln$npy)\r\n min_r = qnorm(1-tail_prob)\r\n n_tail = n_sim*exp(-min_r^2/2)\r\n \r\n # Generate importance samples outside the Rosenblatt transformed contour of tail_rtrp\r\n set.seed(.seed_sampling)\r\n calc = data.table(ur2 = runif(n_tail, min=pchisq(q = min_r^2,df = 2)))\r\n calc[, r:=sqrt(qchisq(p=ur2, df = 2))]\r\n calc[, dir:=runif(.N, min=0, max=2*pi)]\r\n calc[, u_hs:=pnorm(cos(dir)*r)]\r\n calc[, u_tp:=pnorm(sin(dir)*r)]\r\n \r\n # Sample hs\r\n calc[, hs:= qweibull(u_hs, shape = wln$hs$par[\"shape\"], scale = wln$hs$par[\"scale\"]) + wln$hs$par[\"loc\"]]\r\n \r\n # sample tp cond on hs\r\n calc[, tp_norm_mean:= wln$tp$par[1] + wln$tp$par[2] * (hs ^ wln$tp$par[3])]\r\n # calc[, tp_norm_sd:= wln$tp$par[4] + wln$tp$par[5] * exp(wln$tp$par[6] * hs)]\r\n calc[, tp_norm_sd:= pmax(.limit_zero, wln$tp$par[4] + wln$tp$par[5] * exp(wln$tp$par[6] * hs))]\r\n calc[, tp:= exp(qnorm(u_tp, tp_norm_mean, tp_norm_sd))]\r\n \r\n # Return\r\n return(calc[, .(hs, tp)])\r\n}\r\n", "meta": {"hexsha": "50b7e0dc0e6351c77b9279792ab25a5c177a73eb", "size": 8790, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/sample_jdistr.r", "max_stars_repo_name": "ECSADES/ecsades-r", "max_stars_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-17T00:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:13:22.000Z", "max_issues_repo_path": "ecsades/R/sample_jdistr.r", "max_issues_repo_name": "ECSADES/ecsades-r", "max_issues_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-22T13:00:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-04T16:45:59.000Z", "max_forks_repo_path": "ecsades/R/sample_jdistr.r", "max_forks_repo_name": "ECSADES/ecsades-r", "max_forks_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8571428571, "max_line_length": 120, "alphanum_fraction": 0.6489192264, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593359052279467}} {"text": "#' @title\n#' Calculate the ordering of events\n#'\n#' @description\n#' For each event, we generate distributions of time of event occurance using profiles within clusters. These distributions are then pair wise compared and the results of all comparisons are represented in the graph space, where events are the graph nodes, and the directional edges represent that the source node event occurs significantly early than the target node. This graph is then utilized to generate the ordering.\n#'\n#' @param Tc A matrix containing time course data.\n#' @param clusters A vector with same length as number of profiles. The cluster labels are assumed to be numbers, starting from 1.\n#' @param mat_events A matrix containing the time regions (and events for the centroid) generated by running the \\code{calcEvents} function.\n#' @param test The test used to compare the event time distributions. The choice is between a parametric or a non-parametric test:\n#' \\describe{\n#' \t\t\\item{\\code{wilcox}}{Choosing this will result in event times being compared using the Mann Whitney U test}\n#' \t\t\\item{\\code{t-test}}{Choosing this will result in event times being compared using the Students t-test}\n#' }\n#' @param fdrSignif The significance cutoff for FDR correction, performed after pairwise comparisons of the event times.\n#' @param phosEventTh Value between 0 and 1, to define the threshold at which a phosphorylation (or increasing) event occurs. Here, a threshold of 0 corresponds to the minimum value within an interval. (Such an event is designated as 1).\n#' @param dephosEventTh Value between 0 and 1, to define the threshold at which a dephosphorylation (or decreasing) event occurs. A threshold of 0 corresponds to the maximum value within an interval. (Such an event is designated as -1).\n#'\n#'\n#' @return A list with four named objects is returned, which encodes the order of the events and the clusters.\n#'\n#'\n#' @importFrom methods is\n#' @importFrom stats p.adjust wilcox.test t.test\n#' @importFrom nem transitive.reduction\n#' @importFrom igraph graph_from_adjacency_matrix adjacent_vertices V are.connected vertex_connectivity\n#'\n#' @seealso \\code{\\link[e1071]{cmeans}} for clustering time profiles, \\code{\\link{calcEvents}} for identifying events.\n#'\n#' @export\ncalculateOrder <- function(Tc, clusters, mat_events, test=\"wilcox\", fdrSignif=0.05, phosEventTh=0.5, dephosEventTh=0.5){\n\n\n\tstopifnot(is(Tc, \"matrix\"), (length(clusters) == nrow(Tc)), is(mat_events, \"matrix\"), (fdrSignif >0 && fdrSignif <= 1 ), (phosEventTh >= 0 && phosEventTh <= 1), (dephosEventTh >= 0 && dephosEventTh <= 1))\n\n\tif (!(test == eventOrderTest$param) && !(test == eventOrderTest$nonParam)){\n\t\tstop(paste(\"Test \", test, \" not recognized.\", sep=\"\"))\n\t}\n\n\n\n\tlist_matrices <- splitIntoSubMatrices(Tc, clusters)\n\n\tlist_distributions <- getDistOfAllEvents_v2(mat_events, list_matrices, phosEventTh, dephosEventTh)\n\n\t# mat_missingStats <- missingStats(list_distributions) # exclude events based on percentage missing. mat_fiftyPoints, list_distributions\n\t# return(mat_missingStats)\n\n\t# return (list_distributions)\n\n\n\tlist_pVal_stat <- list()\n\n\tif (test==eventOrderTest$nonParam){\n\t\tprint (\"Running wilcoxon test.\")\n\t\tlist_pVal_stat <- performWilcoxonSignedRankTabular(list_distributions)\n\n\n\t\ttitle_testType = \"(Non-parametric)\"\n\t}\n\telse {\n\t\tprint(\"Running t-test.\")\n\t\tlist_pVal_stat <- performTtestsTabular(list_distributions)\n\n\t\ttitle_testType = \"(Parametric)\"\n\t}\n\n\t# FDR adjustment for multiple testing.\n\tmat_pValsFDR <- matrix(stats::p.adjust(as.vector(list_pVal_stat[[1]]), method='fdr'), ncol=nrow(mat_events))\n\n\t# Convert to adjacency matrix.\n\tsignifs <- mat_pValsFDR < fdrSignif\n\tstatistic_t <- list_pVal_stat[[2]]\n\tstatistic_t[!signifs] <- NA\n\n\n\tstatistic_t[statistic_t > 0] <- NA\n\tstatistic_t[is.na(statistic_t)] <- 0\n\tstatistic_t[statistic_t < 0] <- 1\n\n\t# library(nem) # for trasitive reduction\n\t# library(igraph) # for adjacency matrix\n\treducted <- nem::transitive.reduction(statistic_t)\n\tnet = igraph::graph_from_adjacency_matrix(reducted, mode=\"directed\")\n\n\tlist_eventsOrder <- getEventsOrderInGraph(reducted, net) # computing the order of the events in the mat_events based on a bfs search.\n\tlist_eventsOrder <- adjustEvents(list_eventsOrder, signifs)\n\n\n\tmat_events_withOrder <- appendOrder(mat_events, list_eventsOrder)\n\n\tres <- list(mat_events_withOrder, list_eventsOrder, signifs, test)\n\tnames(res) <- c(\"mat_events_withOrder\", \"individEventOrder\", \"signifs\", \"test\")\n\treturn (res)\n\n\n}\n\n#' @title\n#' Visualize the order of events.\n#'\n#' @description\n#' A plot depicting the temporal order of events is generated. The order is shown using two visualizations, event maps (top) and event sparklines (bottom). The event sparkline is a summary of the event map.\n#'\n#' @param theOrder A list containing information regarding the order of events and clusters generated via the \\code{calculateOrder} function.\n#'\n#'\n#' @return A plot containing the ordered clusters by occurance of first event is generated (see description).\n#'\n#'\n#' @importFrom methods is\n#' @importFrom graphics plot segments axis rect text lines\n#' @importFrom shape Arrows\n#'\n#' @seealso \\code{\\link{calculateOrder}}\n#'\n#' @export\nvisualizeOrder <- function(theOrder){\n# Visualise the ordering of events\n\n\tstopifnot(is(theOrder, \"list\"), length(theOrder) == 4)\n\n\n\tmat_events_withOrder <- theOrder$mat_events_withOrder\n\tlist_eventsOrder <- theOrder$individEventOrder\n\tsignifs <- theOrder$signifs\n\ttest <- theOrder$test\n\n\ttitle_testType = \"\"\n\t## Getting other things ready for plotting\n\n\tif (test==eventOrderTest$nonParam){\n\t\ttitle_testType = \"(Non-parametric)\"\n\t}\n\telse {\n\t\ttitle_testType = \"(Parametric)\"\n\t}\n\n\n\n\t# plotting constants\n\tsigEventsDiff_x = 0.5\n\tnonSigEventsDiff_x = 0.25\n\n\teventPtGraph_y = -1\n\tyLabelInit = -1.8\n\tyLabelSpace = 0.5\n\n\tlineDiff_y = 1\n\n\t# graphXStart = -1\n\teventStart_x = 0\n\n\tblockSpacingFmEvent_x = sigEventsDiff_x/2\n\tblockStart_x = eventStart_x - blockSpacingFmEvent_x\n\n\n\t#x_lineStart, y_lineStart, y_lineDecr, x_incr_sig, x_incr_nonSig\n\n\tyPos_eventPts = -1\n\n\t# plotting values\n\tlist_blocks <- getRectBlock(list_eventsOrder, signifs)\n\t# print(list_blocks)\n\n\tmat_eventPoints <- getTheClusLines(mat_events_withOrder, list_eventsOrder, signifs, list_blocks, eventStart_x, sigEventsDiff_x, nonSigEventsDiff_x, lineDiff_y)\n\n\n\teventEnd_x = max(as.numeric(mat_eventPoints[,cols_matFifty$col_x])) # + blockSpacingFmEvent_x\n\tblockEnd_x = eventEnd_x + blockSpacingFmEvent_x\n\n\tmat_bgRects <- getRectPoints(mat_eventPoints, list_blocks, blockStart_x, blockSpacingFmEvent_x)\n\n\n\t# mat_eventPoints <- adjustByBgRects(mat_bgRects, list_eventsOrder, mat_eventPoints)\n\n\n\tmat_grayLines <- getGrayLines(mat_eventPoints, signifs)\n\n\tmat_grayLines_v2 <- getGrayLines_v2(list_eventsOrder, mat_eventPoints, signifs)\n\n\n\tmat_clusConnLines <- getClusConnLines(mat_eventPoints, blockStart_x, blockEnd_x)\n\n\tmat_clusConnLines <- makeDecrBarOpaque(mat_clusConnLines, FALSE)\n\t# print(mat_clusConnLines)\n\tvec_labels <- getYaxisLabels(mat_eventPoints)\n\n\n\tmat_xLabelsClus <- getXaxisLabels(list_eventsOrder, mat_eventPoints, signifs, list_blocks, eventStart_x, sigEventsDiff_x, nonSigEventsDiff_x, yLabelInit, yLabelSpace);\n\n\n\n\t# a set of points to set up the graph.\n\t# print(mat_eventPoints)\n\tgraphics::plot(mat_eventPoints[,cols_matFifty$col_x], mat_eventPoints[,cols_matFifty$col_y], asp=NA, yaxt=\"n\", lwd=0.25, col=colors_orderedEvents$incr, pch=\".\", xlab=\"Temporal order\", ylab=\"Clusters\", main=paste(\"Temporal order of events in clusters\", title_testType, sep=\"\"), xlim=c(eventStart_x, eventEnd_x), ylim=c(-4, max(as.numeric(mat_eventPoints[,cols_matFifty$col_clus]))), xaxt=\"n\", bty=\"n\", cex.main = 0.8) #,\n\t# print(\"over here..\")\n\t# background gray rectangles.\n\tif (nrow(mat_bgRects) > 0){\n\t\tfor (rowNum in 1:nrow(mat_bgRects)){\n\t\t\tif (rowNum%%2 == 1){\n\t\t\t\tgraphics::rect(mat_bgRects[rowNum,1], lineDiff_y/2, mat_bgRects[rowNum,2], max(as.numeric(mat_eventPoints[,cols_matFifty$col_clus])) + (lineDiff_y/2), col = \"#ededed\", border=NA)\n\t\t\t}\n\n\t\t}\n\t}\n\n\t# axis labels on sides 2 and 4.\n\tgraphics::axis(side=2, las=1, at=seq(1,length(vec_labels)), labels=rev(vec_labels), cex=0.02, col = NA ) #, col.ticks = 1)\n\n\tgraphics::axis(side=4, las=1, at=seq(1,length(vec_labels)), labels=rev(vec_labels), cex=0.02, col = NA ) #, col.ticks = 1)\n\n\n\tgraphics::segments(x0=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_x0]), y0=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_y0]), x1=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_x1]), y1=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_y1]), col=\"#808080\", lty=\"dotted\", lwd=0.5)\n\t# C99999\n\n\n\n\t# rect(-0.5, 0, 0.5, 17.5, col = \"yellow\", border=\"#ededed\")\n\n\t# the cluster lines\n\tgraphics::segments(x0=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_x0]), y0=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_y0]), x1=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_x1]), y1=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_y1]), col=mat_clusConnLines[,cols_clusPlotObjs$col_col], lwd=16, lend=2)\n\n\n\t# the events (arrows) within a graph\n\tmat_upEvents = mat_eventPoints[mat_events_withOrder[,cols_matFifty$col_dir] == 1,]\n\tmat_downEvents = mat_eventPoints[mat_events_withOrder[,cols_matFifty$col_dir] == -1,]\n\n\n\t# print(mat_upEvents)\n\n\n\t## arrow bottoms\n\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01-0.2, y1=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=color_events$up, lwd=2, lend=2, arr.adj=0)\n\n\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25, y1=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25-0.2, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=color_events$down, lwd=2, lend=2, arr.adj=0)\n\n\n\t## sharp arrow heads\n\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01-0.2, y1=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01, arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=color_events$up, arr.adj=0, segment=FALSE)\n\n\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25, y1=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25-0.2, arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=color_events$down, arr.adj=0, segment=FALSE)\n\n\n\t# gray lines in events points maps\n\tstraightGrayLines = mat_grayLines_v2[mat_grayLines_v2[,cols_grayLines_v2$col_isSemiCirc] == FALSE,]\n\tgraphics::segments(x0=as.numeric(straightGrayLines[,cols_grayLines_v2$col_x0]), y0=rep(yPos_eventPts, length(straightGrayLines)), x1=as.numeric(straightGrayLines[,cols_grayLines_v2$col_x1]), y1=rep(yPos_eventPts, length(straightGrayLines)), lwd=1, col=\"#A2A2A2\") #, lty=\"dotted\")\n\n\t# gray curves in events points map\n\tmat_curvePoints = mat_grayLines_v2[mat_grayLines_v2[,cols_grayLines_v2$col_isSemiCirc] == TRUE,,drop=FALSE]\n\n\tif (length(mat_curvePoints) > 0 && nrow(mat_curvePoints) > 0){\n\t\tfor (i in 1:nrow(mat_curvePoints)){\n\t\t\tlist_pts = calcCurves(mat_curvePoints[i, cols_grayLines_v2$col_x0], mat_curvePoints[i, cols_grayLines_v2$col_x1], -1)\n\t\t\tgraphics::lines(list_pts[[1]], list_pts[[2]], col=\"#A2A2A2\")\n\t\t}\n\t}\n\n\n\n\n\t# printing up and down events (in arc events map)\n\ty_adjust = 0.15\n\n\t## arrow bottom lines\n\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=rep(-1.2, nrow(mat_upEvents)), y1=rep(-1, nrow(mat_upEvents)), arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=color_events$up, lwd=2, lend=2, arr.adj=0)\n\n\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=rep(-0.8, nrow(mat_downEvents)), y1=rep(-1, nrow(mat_downEvents)), arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=color_events$down, lwd=2, lend=2, arr.adj=0)\n\n\t## sharp arrow heads\n\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=rep(-1.2, nrow(mat_upEvents)), y1=rep(-1, nrow(mat_upEvents)), arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=color_events$up, arr.adj=0, segment=FALSE)\n\n\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=rep(-0.8, nrow(mat_downEvents)), y1=rep(-1, nrow(mat_downEvents)), arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=color_events$down, arr.adj=0, segment=FALSE)\n\n\n\t# vec_clusEvent = mat_eventPoints[,4]\n\t# print(vec_clusEvent)\n\t# vec_clusEvent[mat_eventPoints[mat_fiftyPoints[,cols_matFifty$col_dir] == 1]] = color_events$up\n\t# vec_clusEvent[mat_eventPoints[mat_fiftyPoints[,cols_matFifty$col_dir] == -1] = color_events$down\n\n\t# x label text.\n\tgraphics::text(x=as.numeric(mat_xLabelsClus[,1]), y=as.numeric(mat_xLabelsClus[,2]), labels=mat_xLabelsClus[,3], offset=0, cex=0.5, col=mat_xLabelsClus[,4])\n\n\n}\n\n#' @title\n#' Rearrange clusters by events\n#'\n#' @description\n#' After calculating the order of events, we can now rearrange clusters, so that the first cluster contains the first event and so on.\n#'\n#' @param clusters A vector with same length as number of profiles. The cluster labels are assumed to be numbers, starting from 1.\n#' @param theOrder A list containing information regarding the order of events and clusters generated via the \\code{calculateOrder} function.\n#'\n#'\n#' @return The returned vector now contains the cluster rearranged according to the computed ordering in \\code{theOrder}.\n#'\n#'\n#' @importFrom methods is\n#' @importFrom rlang duplicate\n#'\n#' @seealso \\code{\\link[e1071]{cmeans}} for clustering, \\code{\\link{calculateOrder}} to generate the order.\n#'\n#' @export\nrearrangeClusters <- function(clusters, theOrder){\n\n\tstopifnot(is(theOrder, \"list\"), length(theOrder) == 4)\n\n\n\tclusterOrder <- matrix(ncol=1, nrow=max(theOrder$mat_events_withOrder[,cols_matFifty_v2$clus]), data=NA) # the row numb stores the original order\n\t# print(clusterOrder)\n\torderCounter = 1\n\tfor (i in 1:length(theOrder$individEventOrder)){\n\t\tfor (j in 1:length(theOrder$individEventOrder[[i]])){\n\n\t\t\tclusNum = theOrder$mat_events_withOrder[theOrder$individEventOrder[[i]][j], cols_matFifty_v2$clus]\n\n\t\t\tif (is.na(clusterOrder[clusNum, 1])){\n\t\t\t\t# print(paste(clusNum, orderCounter))\n\t\t\t\tclusterOrder[clusNum, 1] <- orderCounter;\n\n\t\t\t\torderCounter = orderCounter + 1;\n\t\t\t\t# print(clusterOrder)\n\t\t\t}\n\t\t}\n\t}\n\t# return(clusterOrder)\n\n\torigClusters = clusters\n\t# centers = rlang::duplicate(clustered$centers)\n\tfor (origOrder in 1:nrow(clusterOrder)){\n\t\tif (!is.na(clusterOrder[origOrder,1])){\n\t\t\t# print(paste(origOrder, clusterOrder[origOrder,1]))\n\t\t\tclusters[origClusters == origOrder] = clusterOrder[origOrder,1]\n\t\t\t# clustered$center[clusterOrder[origOrder,1], ] = centers[origOrder,]\n\t\t}\n\t}\n\treturn (clusters)\n}\n\n\n\n\n\n\ncalcCurves <- function(x0, x1, yCentPos){\n\n\tx_10pts <- seq(x0, x1, length.out=50)\n\n\ty_10pts <- topSemiCircleEq(x_10pts, yCentPos)\n\n\tlist_pts <- list(x_10pts, y_10pts)\n\treturn (list_pts)\n\n}\n\ntopSemiCircleEq <- function(xPts, yCentPos){\n\tyPts = c()\n\n\n\tr = abs(xPts[1] - xPts[length(xPts)])/2\n\txCentPos = (xPts[1] + xPts[length(xPts)]) /2\n\n\tfor (xPt in xPts){\n\t\tyPt = sqrt(abs(r^2 - (xPt-xCentPos)^2)) + yCentPos + 0.4\n\t\tyPts = c(yPts, yPt)\n\t}\n\n\treturn (yPts)\n}\n\n\nappendOrder <- function(mat_fiftyPoints, list_eventsOrder){\n\n\t# mat_withOrder <- cbind(mat_fiftyPoints, rep(0,nrow(mat_fiftyPoints)))\n\n\tfor (i in 1:length(list_eventsOrder)){\n\t\teventNum <- list_eventsOrder[[i]]\n\n\t\tmat_fiftyPoints[eventNum, Col_events$order] = i\n\t}\n\n\tcolnames(mat_fiftyPoints)[Col_events$order] = \"order\";\n\treturn(mat_fiftyPoints)\n}\n\n################################## AUXILLARY\nadjustEvents <- function(list_eventsOrder, signifs){\n\tlist_newEventsOrder <- list()\n\ti_new = 1\n\n\tfor (i in 1:length(list_eventsOrder)){\n\t\t# print(list_eventsOrder[[i]])\n\t\tisAddedVec = FALSE\n\t\tfor (j in 1:length(list_eventsOrder[[i]])){\n\n\t\t\tif (isAddedVec == FALSE){ # add every row atleast once\n\t\t\t\t# add to list first\n\t\t\t\tlist_newEventsOrder[[length(list_newEventsOrder) + 1]] <- list_eventsOrder[[i]]\n\t\t\t\tisAddedVec = TRUE\n\t\t\t\t# print(list_newEventsOrder)\n\t\t\t}\n\n\t\t\tif (length(list_eventsOrder[[i]]) == 1){ # if only one element break\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif (isAnyOneNonSignifFromNextAll(list_eventsOrder, list_eventsOrder[[i]][j], i, signifs)){ # remove that element, and add to end.\n\t\t\t\t# add the jth one to a new next layer\n\t\t\t\t# print(\"here!\")\n\t\t\t\t# print(list_eventsOrder[[i]][j])\n\n\n\t\t\t\tlist_newEventsOrder <- rmElemAndAddSepElseNew(list_newEventsOrder, list_eventsOrder[[i]][j])\n\t\t\t\t# print(\"now list is\")\n\t\t\t\t# print(list_newEventsOrder)\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn (list_newEventsOrder)\n}\n\ncheckAndAddEventAtEnd <- function(anEvent, list_newEventsOrder){\n\tisFound = FALSE\n\tfor (i in 1:length(list_newEventsOrder)){\n\t\tif (anEvent %in% list_newEventsOrder){\n\t\t\tisFound = TRUE\n\t\t}\n\t}\n\n\tif (isFound == FALSE){\n\t\tlist_newEventsOrder <- append(list_newEventsOrder, c(anEvent))\n\t}\n\n\treturn(list_newEventsOrder)\n}\n\n\nrmElemAndAddSepElseNew <- function(list_newEventsOrder, theElem, theVec){\n\t# print(\"The eleme is \")\n\t# print(theElem)\n\n\tisDeleted = FALSE\n\tfor (i in 1:length(list_newEventsOrder)){\n\t\tif (theElem %in% list_newEventsOrder[[i]]){\n\t\t\tidx = match(theElem, list_newEventsOrder[[i]])\n\t\t\t# print(\" the idx is \")\n\t\t\t# print(idx)\n\t\t\tif (idx > 0){\n\n\t\t\t\tif (length (list_newEventsOrder[[i]]) > 1){\n\t\t\t\t\tlist_newEventsOrder[[i]] <- list_newEventsOrder[[i]][-idx]\n\t\t\t\t\tisDeleted = TRUE\n\t\t\t\t}\n\n\t\t\t\tif (length(list_newEventsOrder[[i]]) == 0){\n\t\t\t\t\tprint(\"Need to delete this here....?\")\n\t\t\t\t\tlist_newEventsOrder <- list_newEventsOrder[-i]\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t}\n\tif (isDeleted == TRUE){\n\t\tfor (i in 1:length(list_newEventsOrder)){\n\t\t\tif (length(list_newEventsOrder[[i]]) == 0){\n\t\t\t\tlist_newEventsOrder <- Filter(Negate(is.null), list_newEventsOrder)\n\t\t\t}\n\t\t}\n\t\tlist_newEventsOrder <- append(list_newEventsOrder, c(theElem))\n\t}\n\n\treturn (list_newEventsOrder)\n}\n\n\nrmElemAndAddSepElseNew_old <- function(list_newEventsOrder, theElem, theVec){\n\t# print(\"The eleme is \")\n\t# print(theElem)\n\tfor (i in 1:length(list_newEventsOrder)){\n\t\tif (theElem %in% list_newEventsOrder[[i]]){\n\t\t\tidx = match(theElem, list_newEventsOrder[[i]])\n\t\t\t# print(\" the idx is \")\n\t\t\t# print(idx)\n\t\t\tif (idx > 0){\n\t\t\t\tlist_newEventsOrder[[i]] <- list_newEventsOrder[[i]][-idx]\n\t\t\t}\n\n\n\t\t}\n\t}\n\n\tlist_newEventsOrder <- append(list_newEventsOrder, c(theElem))\n\n\treturn (list_newEventsOrder)\n}\n\n\nisVecInList <- function(theVec, theList, elemToRm){\n\n\tfor (subVec in theList){\n\t\tif (all(subVec==theVec)){\n\t\t\treturn (TRUE)\n\t\t}\n\t}\n\n\treturn (FALSE)\n}\n\nisAnyOneNonSignifFromNextAll <- function(list_eventsOrder, currEvent, currentLayer, signifs){\n\tif ((currentLayer + 1) >= length(list_eventsOrder)){\n\t\treturn (FALSE)\n\t}\n\n\tfor (i in seq((currentLayer + 1), length(list_eventsOrder))){\n\n\t\tisAny = isAnyNonSignifFromPrev(c(currEvent), list_eventsOrder[[i]], signifs)\n\n\t\tif (isAny == TRUE){\n\t\t\treturn (TRUE)\n\t\t}\n\t}\n\n\treturn (FALSE)\n}\n\n\n\ngetEventsOrderInGraph <- function(reducted, net){\n\tvec_roots <- getRoots(reducted) # get root nodes\n\tvec_linCurrNodes <- vec_roots\n\n\t# list_currNodes <- as.list(vec_roots)\n\n\n\tvec_visited <- c()\n\n\tlist_eventsOrder <- list()\n\n\n\twhile(length(vec_linCurrNodes) > 0){\n\n\t\t# list_prevNodes = list_currNodes\n\n\n\t\t# print(\"vec_linCurrNodes\")\n\t\t# print (vec_linCurrNodes)\n\n\t\tvec_newForVisit <- getNotVisitedBefore(vec_linCurrNodes, vec_visited)\n\n\t\tvec_newForVisit <- onlyPatron(vec_newForVisit, net)\n\n\n\t\t# print(\"to visit\")\n\t\t# print (vec_newForVisit)\n\n\n\t\tif (length(vec_newForVisit) > 0){\n\t\t\t# print(\"to visit\")\n\t\t\t# print (vec_newForVisit)\n\n\t\t\tlist_eventsOrder <- addNodesToOrderList(vec_newForVisit, list_eventsOrder)\n\t\t\tvec_visited <- visitNodes(vec_newForVisit, vec_visited)\n\t\t}\n\n\n\n\t\tlist_currNodes <- getAllInNextHop(net, vec_newForVisit, \"out\")\n\t\tvec_linCurrNodes <- convertToUniqueVec(list_currNodes)\n\n\t\tif (length(vec_linCurrNodes) == 0 && length(igraph::V(net)) != length(vec_visited)){\n\t\t\tvec_linCurrNodes <- setdiff(igraph::V(net), vec_visited)\n\t\t}\n\t}\n\treturn (list_eventsOrder)\n}\n\n\n\n\n\ncols_clusPlotObjs$col_x0 <- 1\ncols_clusPlotObjs$col_y0 <- 2\ncols_clusPlotObjs$col_x1 <- 3\ncols_clusPlotObjs$col_y1 <- 4\ncols_clusPlotObjs$col_col <- 5\n\n\n\n\n\ngetNumOfCrossingAndDir <- function(mat_fiftyPoints, clusNum){\n\n\ttotalNumOfCrossings <- 0\n\tlist_dir = list()\n\n\tfor (rowNum in 1:nrow(mat_fiftyPoints)){\n\t\tif (mat_fiftyPoints[rowNum, cols_matFifty$col_clus] == clusNum){\n\t\t\ttotalNumOfCrossings = totalNumOfCrossings + 1\n\t\t\tlist_dir = append(list_dir, mat_fiftyPoints[rowNum, cols_matFifty$col_dir])\n\t\t}\n\t}\n\n\treturn (list(totalNumOfCrossings, list_dir))\n}\n\ngenDistForEvent <- function(clusMat, dir, startTp, endTp, phosTh, dephosTh){\n\tmat_distribution <- matrix(ncol=4)\n\n\n\tfor (profNum in 1:nrow(clusMat)){\n\n\t\tif ((dir == 1 && clusMat[profNum, startTp] < clusMat[profNum, endTp]) || (dir == -1 && clusMat[profNum, startTp] > clusMat[profNum, endTp])){\n\t\t\t# direction holds; do calculation, and save.\n\t\t\t# print(clusMat[profNum, startTp:endTp])\n\n\t\t\tcrossPt <- calcCrossing_v3(clusMat[profNum, startTp:endTp], dir, (startTp -1), phosTh, dephosTh)\n\n\t\t\tmat_distribution <- addToMatrix(mat_distribution, profNum, crossPt[1], crossPt[2], dir)\n\n\t\t}\n\t\telse{\n\t\t\tmat_distribution <- addToMatrix(mat_distribution, profNum, NA, NA, dir)\n\t\t}\n\t}\n\n\tmat_distribution <- mat_distribution[-1,, drop=FALSE]\n\treturn (mat_distribution)\n}\n\n\ngetDistOfAllEvents_v2 <- function(mat_fiftyPoints, list_matrices, phosTh, dephosTh){\n\tlist_distributions <- list()\n\n\tfor (eventNum in 1:nrow(mat_fiftyPoints)){\n\t\tdist <- genDistForEvent(list_matrices[[mat_fiftyPoints[eventNum,cols_matFifty_v2$clus]]], mat_fiftyPoints[eventNum, cols_matFifty_v2$dir], mat_fiftyPoints[eventNum, cols_matFifty_v2$startTp], mat_fiftyPoints[eventNum, cols_matFifty_v2$endTp], phosTh, dephosTh)\n\n\t\tlist_distributions[[length(list_distributions) + 1]] <- dist\n\t}\n\n\treturn(list_distributions)\n}\n\n\nisComparisonPossible <- function(list1, list2){\n\tlist1 <- list1[!is.na(list1)]\n\tlist2 <- list2[!is.na(list2)]\n\n\t# print(list1)\n\n\tif(all(abs(list1 - mean(list1)) < 0.0001) && all(abs(list2 - mean(list2)) < 0.0001) && abs(mean(list1) - mean(list2)) < 0.0001) {\n\t\t# print(\"false!!!)\")\n\t\treturn (FALSE)\n\n\t}\n\n\n\treturn (TRUE)\n}\n\n\nperformWilcoxonSignedRankTabular <- function(list_distributions){\n\tmat_pVal = matrix(nrow=length(list_distributions), ncol=length(list_distributions))\n\tmat_statistic = matrix(nrow=length(list_distributions), ncol=length(list_distributions))\n\n\tfor (i in 1:length(list_distributions)){\n\t\tfor (j in 1:length(list_distributions)){\n\n\t\t\tif (i != j){\n\n\t\t\t\tif (!isComparisonPossible(list_distributions[[i]][,cols_matFifty$col_x], list_distributions[[j]][,cols_matFifty$col_x])){ # add as pval = 1 (being the exact same from a uniform distribution).\n\t\t\t\t\tmat_pVal[i, j] <- 1\n\t\t\t\t\tmat_statistic[i, j] <- NA\n\t\t\t\t}\n\t\t\t\telse{ # do the comparison\n\t\t\t\t\tres <- stats::wilcox.test(list_distributions[[i]][,cols_matFifty$col_x], list_distributions[[j]][,cols_matFifty$col_x], paired=FALSE, conf.int=TRUE)\n\n\t\t\t\t\t# if (stats::wilcox.test(list_distributions[[i]][,cols_matFifty$col_x], list_distributions[[j]][,cols_matFifty$col_x], paired=FALSE, conf.int=TRUE)){\n\t\t\t\t\t#\tprint(paste(\"The case here \", i, j))\n\n\t\t\t\t\t#}\n\t\t\t\t\t# return (res)\n\t\t\t\t\t# print (res)\n\t\t\t\t\tmat_pVal[i, j] <- res$p.value\n\t\t\t\t\tmat_statistic[i, j] <- res$estimate\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlist_pVal_stat <- list()\n\tlist_pVal_stat[[1]] <- mat_pVal\n\tlist_pVal_stat[[2]] <- mat_statistic\n\treturn (list_pVal_stat)\n}\n\n\n\nperformTtestsTabular <- function(list_distributions){\n\tmat_pVal = matrix(nrow=length(list_distributions), ncol=length(list_distributions))\n\tmat_statistic = matrix(nrow=length(list_distributions), ncol=length(list_distributions))\n\n\tfor (i in 1:length(list_distributions)){\n\t\tfor (j in 1:length(list_distributions)){\n\n\t\t\tif (i != j){\n\t\t\t\tif (!isComparisonPossible(list_distributions[[i]][,cols_matFifty$col_x], list_distributions[[j]][,cols_matFifty$col_x])){ # add as pval = 1 (being the exact same from a uniform distribution).\n\t\t\t\t\tmat_pVal[i, j] <- 1\n\t\t\t\t\tmat_statistic[i, j] <- NA\n\t\t\t\t}\n\t\t\t\telse{ # do the comparison\n\t\t\t\t\tres <- stats::t.test(list_distributions[[i]][,cols_matFifty$col_x], list_distributions[[j]][,cols_matFifty$col_x], paired=FALSE)\n\t\t\t\t\tmat_pVal[i, j] <- res$p.value\n\t\t\t\t\tmat_statistic[i, j] <- res$statistic\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlist_pVal_stat <- list()\n\tlist_pVal_stat[[1]] <- mat_pVal\n\tlist_pVal_stat[[2]] <- mat_statistic\n\treturn (list_pVal_stat)\n}\n\n\n################################ GRAPH_TRAVERSAL\n\ngetRoots <- function(reducted){\n\tvec_roots = c()\n\tfor (colNum in 1:nrow(reducted)){\n\n\t\tisAllZeros = TRUE\n\t\tfor (rowNum in 1:ncol(reducted)){\n\t\t\tif (reducted[rowNum, colNum] == 1){\n\t\t\t\tisAllZeros = FALSE\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif (isAllZeros == TRUE){\n\t\t\tvec_roots <- append(vec_roots, colNum)\n\t\t}\n\n\t}\n\n\treturn (vec_roots)\n}\n\n\n\ngetNotVisitedBefore <- function(vec_currNodes, vec_visited){\n\tvec_newForVisit <- c()\n\n\tfor (i in 1:length(vec_currNodes)){\n\n\t\tif (!(vec_currNodes[i] %in% vec_visited) && !(vec_currNodes[i] %in% vec_newForVisit)){\n\t\t\tvec_newForVisit <- c(vec_newForVisit, vec_currNodes)\n\t\t}\n\t}\n\n\treturn (vec_newForVisit)\n}\n\n\nonlyPatron <- function(vec_nodes, net){\n\n\t# only add a node if it is not a child of anything else in this set.\n\n\tvec_parentsOnly <- c()\n\n\tfor (i in 1:length(vec_nodes)){\n\t\tisChild = FALSE;\n\n\t\tvec_withoutCurr <- setdiff(vec_nodes, vec_nodes[i])\n\n\t\tif (length(vec_withoutCurr) > 0) {\n\t\t\tlist_children <- getAllInNextHop(net, vec_withoutCurr, 'out')\n\t\t\tvec_children <- convertToUniqueVec(list_children)\n\n\t\t\t# print(vec_children)\n\t\t\t# print(vec_nodes[i])\n\n\t\t\tif (vec_nodes[i] %in% vec_children){\n\t\t\t\tisChild = TRUE\n\t\t\t}\n\t\t\telse { # make sure that this node is also not in the downstream lineage.\n\t\t\t\tif (length(vec_children) > 0){\n\t\t\t\t\tfor (j in 1:length(vec_children)){\n\t\t\t\t\t\tif (igraph::are.connected(net, vec_children[j], vec_nodes[i]) == TRUE || igraph::vertex_connectivity(net, vec_children[j], vec_nodes[i]) == 1){\n\t\t\t\t\t\t\tisChild = TRUE\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif (isChild == FALSE){\n\t\t\tvec_parentsOnly <- c(vec_parentsOnly, vec_nodes[i])\n\t\t}\n\n\t}\n\n\treturn (vec_parentsOnly)\n}\n\n\naddNodesToOrderList <- function(vec_nodesInNewLayer, list_eventsOrder){\n\tpos <- length(list_eventsOrder) + 1\n\tlist_eventsOrder[[pos]] <- vec_nodesInNewLayer\n\treturn (list_eventsOrder)\n}\n\n\n\nvisitNodes <- function(vec_newForVisit, vec_visited){\n\n\tvec_visited <- c(vec_visited, vec_newForVisit)\n\n\treturn (vec_visited)\n}\n\n\n\ngetAllInNextHop <- function(network, list_nodes, edgeDir){\n\tlist_ <- igraph::adjacent_vertices(network, list_nodes, mode=\"out\")\n\n\n\treturn (list_)\n}\n\n\nconvertToUniqueVec <- function(list_nodes){\n\tvec_nodes <- c()\n\t# print(\"lvl1\")\n\tif (length(list_nodes) > 0){\n\t\tfor (i in 1:length(list_nodes)){\n\t\t\t# print(\"lvl2\")\n\t\t\tif (length(list_nodes[[i]]) > 0){\n\t\t\t\tfor(j in 1:length(list_nodes[[i]])){\n\t\t\t\t\t# print(c(i,j), sep=\"\\t\")\n\t\t\t\t\t# print(list_nodes)\n\t\t\t\t\tif (! (list_nodes[[i]][j] %in% vec_nodes)){\n\t\t\t\t\t\tvec_nodes <- c(vec_nodes, list_nodes[[i]][j])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t# print(list_nodes)\n\treturn (vec_nodes)\n}\n\n\n\n\n###################### FOR PLOTTING\ngetXaxisLabels <- function(list_eventsOrder, mat_eventPoints, signifs, list_blocks, eventStart_x, xSigIncr, xNonSigIncr, yLabelInit, yLabelSpace){\n\tmat_xLabelsClus = matrix(ncol=4) #x0, y0, labelNames, color\n\tx0 = eventStart_x;\n\teventsVisited = c()\n\n\tisFirst = TRUE\n\n\tfor (i in 1:length(list_eventsOrder)){\n\n\t\teventsVisited = c(eventsVisited, list_eventsOrder[[i]])\n\n\t\tif (i > 1 && isAnyNonSignifFromPrevAll(list_eventsOrder, i, signifs) == TRUE || isInSameBlock(list_eventsOrder[[i]], eventsVisited, list_blocks)){\n\t\t\tif (isFirst == FALSE){\n\t\t\t\tx0 = x0 + xNonSigIncr;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tisFirst = FALSE\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (isFirst == FALSE){\n\t\t\t\tx0 = x0 + xSigIncr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tisFirst = FALSE\n\t\t\t}\n\n\t\t}\n\n\t\ty0 = yLabelInit\n\n\t\tsortedEvents <- getSortedEventsByY(list_eventsOrder[[i]], mat_eventPoints)\n\n\n\t\tfor (event in sortedEvents){\n\n\t\t\t# print(mat_eventPoints[event, cols_matFifty$col_dir])\n\n\t\t\tcol = mat_eventPoints[event, cols_matFifty$col_dir]\n\t\t\t# col = color_events$up\n\n\t\t\t# if (mat_eventPoints[event, cols_matFifty$col_dir] != colors_orderedEvents$incr){\n\t\t\t# \tcol = color_events$down\n\t\t\t# }\n\n\t\t\trowVal = c(x0, y0, mat_eventPoints[event, cols_matFifty$col_clus], col)\n\t\t\tmat_xLabelsClus <- rbind(mat_xLabelsClus, rowVal)\n\n\t\t\ty0 = y0 - yLabelSpace;\n\t\t}\n\n\n\t}\n\n\tmat_xLabelsClus <- mat_xLabelsClus[-1,]\n\treturn (mat_xLabelsClus)\n}\n\ngetSortedEventsByY <- function(events, mat_eventPoints){\n\ttheOrder <- rev(order(as.numeric(mat_eventPoints[events, cols_matFifty$col_y])))\n\treturn(events[theOrder])\n}\n\n\ngetGrayLines_v2 <- function(list_eventsOrder, mat_eventPoints, signifs){\n\ttheGrayLines = matrix(ncol=4) # x0, x1, isSemiCircle, color\n\n\tfor (i in 1:nrow(signifs)){\n\t\tfor (j in i:ncol(signifs)){\n\t\t\tif (i != j){\n\t\t\t\tif (signifs[j, i] == FALSE){\n\t\t\t\t\t# if in same layer no need for line\n\n\t\t\t\t\tj_layer = getLayerNum(list_eventsOrder, j)\n\t\t\t\t\ti_layer = getLayerNum(list_eventsOrder, i)\n\n\t\t\t\t\tif (j_layer != i_layer){\n\t\t\t\t\t\tif (i_layer - 1 == j_layer || j_layer - 1 == i_layer){\n\t\t\t\t\t\t\trowVal <- c(mat_eventPoints[i, cols_matFifty$col_x], mat_eventPoints[j, cols_matFifty$col_x], FALSE, \"#808080\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\trowVal <- c(mat_eventPoints[i, cols_matFifty$col_x], mat_eventPoints[j, cols_matFifty$col_x], TRUE, \"#808080\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttheGrayLines <- rbind(theGrayLines, rowVal)\n\t\t\t\t\t}\n\t\t\t\t\t# if in diff layer\n\t\t\t\t\t\t# if in consecutive layer, draw straight line\n\n\t\t\t\t\t\t# if not, draw semicircle.\n\n\n\t\t\t\t\t# draw a gray50 line between the i and j events\n\n\n\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttheGrayLines <- theGrayLines[-1,]\n\n\t# print(theGrayLines)\n\treturn (theGrayLines)\n}\n\ngetLayerNum <- function(list_eventsOrder, event){\n\tfor (i in 1:length(list_eventsOrder)){\n\t\tif (event %in% list_eventsOrder[[i]]){\n\t\t\treturn (i)\n\t\t}\n\t}\n\n\treturn (-1)\n}\n\ngetGrayLines <- function(mat_eventPoints, signifs){\n\ttheGrayLines = matrix(ncol=5)\n\n\n\tfor (i in 1:nrow(signifs)){\n\t\tfor (j in i:ncol(signifs)){\n\t\t\tif (i != j){\n\t\t\t\tif (signifs[j, i] == FALSE){\n\t\t\t\t\t# draw a gray50 line between the i and j events\n\t\t\t\t\trowVal <- c(mat_eventPoints[i, cols_matFifty$col_x], mat_eventPoints[i, cols_matFifty$col_y], mat_eventPoints[j, cols_matFifty$col_x], mat_eventPoints[j, cols_matFifty$col_y], \"red\")\n\t\t\t\t\ttheGrayLines <- rbind(theGrayLines, rowVal)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttheGrayLines <- theGrayLines[-1,,drop=F]\n\n\treturn (theGrayLines)\n}\n\n\n\ngetRectPoints <- function(mat_eventPoints, list_blocks, rectStart, rectSpacingFmEvent){ #xStart, incr\n\tmat_rectPts = matrix(ncol=2) # [x0, x1]\n\n\tfor (i in 1:length(list_blocks)){\n\t\txVal <- max(as.numeric(mat_eventPoints[list_blocks[[i]], cols_matFifty$col_x])) + rectSpacingFmEvent\n\n\t\tif (i == 1){\n\t\t\tx0 <- rectStart\n\t\t}\n\t\telse{\n\t\t\tx0 <- mat_rectPts[nrow(mat_rectPts), cols_rectPoints$x1]\n\t\t}\n\n\t\tmat_rectPts <- rbind(mat_rectPts, c(x0, xVal))\n\n\t}\n\tmat_rectPts <- mat_rectPts[-1, ]\n\treturn (mat_rectPts)\n}\n\n\ngetRectBlock <- function(list_eventsOrder, signifs){\n\t\tlist_blocks <- list()\n\n\t\tprevBlock <- c()\n\t\tcurrBlock <- list_eventsOrder[[1]]\n\n\n\t\tif(length(list_eventsOrder) > 1) {\n\t\t\tfor (i in 2:length(list_eventsOrder)){\n\n\n\t\t\t\tisAny = isAnyNonSignifFromPrev(list_eventsOrder[[i]], currBlock, signifs)\n\n\t\t\t\tif (isAny == TRUE){\n\t\t\t\t\tcurrBlock <- c(currBlock, list_eventsOrder[[i]])\n\n\t\t\t\t}\n\t\t\t\telse{\n\n\t\t\t\t\tprevBlock <- c(prevBlock, currBlock)\n\t\t\t\t\tlist_blocks[[length(list_blocks)+1]] <- currBlock\n\t\t\t\t\tcurrBlock <- list_eventsOrder[[i]]\n\t\t\t\t\t# rectPoints <- addToRectPoints(rectPoints, list_eventsOrder[[i]], mat_eventPoints)\n\n\t\t\t\t\t # can improve further - i.e. take max of prevBlock listEvents x value (done)\n\t\t\t\t}\n\n\t\t\t\t# if (i == length(list_eventsOrder)){\n\t\t\t#\t\tif (list_blocks[[length(list_blocks)]])\n\t\t\t#\t}\n\n\t\t\t\tif (length(list_blocks) > 0 && length(prevBlock) > 0 && length(currBlock) > 0 && isAnyNonSignifFromPrev(currBlock, prevBlock, signifs) == TRUE){\n\n\t\t\t\t\t# print(length(list_blocks))\n\t\t\t\t\t# theCurrVec = list_blocks[[length(list_blocks)]]\n\t\t\t\t\t# theIdx = prevBlock == theCurrVec\n\n\t\t\t\t\t# print(theCurrVec)\n\t\t\t\t\t# print(prevBlock)\n\n\t\t\t\t\t# prevBlock <- prevBlock[!theIdx]\n\t\t\t\t\tprevBlock <- setdiff(prevBlock, list_blocks[[length(list_blocks)]])\n\t\t\t\t\t# prevBlock <- prevBlock[!prevBlock == joiningEvents]\n\t\t\t\t\tcurrBlock <- c(currBlock, list_blocks[[length(list_blocks)]])\n\t\t\t\t\tlist_blocks <- list_blocks[-length(list_blocks)]\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t# print(currBlock)\n\t\t\tif (length(list_blocks) > 0 && any(currBlock %in% list_blocks[[length(list_blocks)]]) == TRUE && all(currBlock %in% list_blocks[[length(list_blocks)]]) == FALSE ){\n\t\t\t\tlist_blocks[[length(list_blocks)]] <- currBlock\n\t\t\t}\n\t\t\telse if (length(list_blocks) > 0 && all(currBlock %in% list_blocks[[length(list_blocks)]]) == FALSE){\n\t\t\t\tlist_blocks[[length(list_blocks)+1]] <- currBlock\n\t\t\t}\n\n\t\t}\n\t\t# print(\"list blocks in getRectBlock\")\n\t\t# print(list_blocks)\n\t\t# print(\"The list_blocks\")\n\t\t# print(list_blocks)\n\t\treturn (list_blocks)\n\n\n}\n\n\naddToRectPoints <- function(rectPoints, events, mat_eventPoints){\n\t# print(max(as.numeric(mat_eventPoints[events, cols_matFifty$col_x])))\n\tmaxX <- max(as.numeric(mat_eventPoints[events, cols_matFifty$col_x]))\n\n\trowVal = c()\n\tif (nrow(rectPoints) <= 1){\n\t\trowVal <- c(-1, maxX-0.5)\n\n\t}\n\telse{\n\t\trowVal <- c(rectPoints[nrow(rectPoints), 2], maxX-0.5)\n\t}\n\t# print(\"here\")\n\t# print(rowVal)\n\n\trectPoints <- rbind(rectPoints, rowVal)\n\treturn (rectPoints)\n}\n\n\nmakeDecrBarOpaque <- function(mat_clusConnLines, isCombined){\n\n\tif (isCombined == TRUE){\n\t\tfor (i in 1:length(Color_multiomics)){\n\t\t\tidx <- mat_clusConnLines[,cols_clusPlotObjs$col_col] == Color_multiomics[[i]]$decr\n\n\t\t\tmat_clusConnLines[idx,cols_clusPlotObjs$col_col] = colors_orderedEvents$decr\n\n\n\n\t\t\tidx <- mat_clusConnLines[,cols_clusPlotObjs$col_col] == Color_multiomics[[i]]$incr\n\n\t\t\tmat_clusConnLines[idx,cols_clusPlotObjs$col_col] = Color_multiomics[[i]]$bar\n\n\t\t}\n\t}\n\n\tif (isCombined == FALSE){\n\t\tidx <- mat_clusConnLines[,cols_clusPlotObjs$col_col] == color_events$down\n\n\t\tmat_clusConnLines[idx,cols_clusPlotObjs$col_col] = colors_orderedEvents$decr\n\n\t\tidx <- mat_clusConnLines[,cols_clusPlotObjs$col_col] == color_events$up\n\n\t\tmat_clusConnLines[idx,cols_clusPlotObjs$col_col] = colors_orderedEvents$incr\n\t}\n\n\treturn (mat_clusConnLines)\n}\n\n\ngetClusConnLines <- function(mat_eventPoints, xStart, xEnd){\n\tmat_clusConnLines = matrix(ncol=5,nrow=nrow(mat_eventPoints))\n\tmat_basalConnLines = matrix(ncol=5,nrow=max(as.numeric(mat_eventPoints[,cols_matFifty$col_clus]))) # only need 1 for each cluster\n\n\tbasalCounter = 1\n\tprevClus = -1\n\n\tfor(i in 1:nrow(mat_eventPoints)){\n\n\n\t\t# adding start point\n\t\tmat_clusConnLines[i, cols_clusPlotObjs$col_x0] <- mat_eventPoints[i, cols_matFifty$col_x]\n\t\tmat_clusConnLines[i, cols_clusPlotObjs$col_y0] <- mat_eventPoints[i, cols_matFifty$col_y]\n\n\t\t# adding end y\n\t\tmat_clusConnLines[i, cols_clusPlotObjs$col_y1] <- mat_eventPoints[i, cols_matFifty$col_y]\n\n\n\t\t# adding end x\n\t\tmat_clusConnLines[i, cols_clusPlotObjs$col_x1] <- getTheEndX(mat_eventPoints, i, xEnd)\n\n\n\t\t# adding color\n\t\tmat_clusConnLines[i, cols_clusPlotObjs$col_col] <- mat_eventPoints[i, cols_matFifty$col_dir]\n\n\n\t\t## handling the adding of the basal\n\t\tif (prevClus == -1 ){\n\t\t\t# just store everything\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x0] = xStart;\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x1] = mat_clusConnLines[i, cols_clusPlotObjs$col_x0];\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_y0] = mat_clusConnLines[i, cols_clusPlotObjs$col_y0];\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_y1] = mat_clusConnLines[i, cols_clusPlotObjs$col_y1];\n\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_col] <- getOppColor(mat_eventPoints[i, cols_matFifty$col_dir])\n\n\t\t\tprevClus = mat_eventPoints[i,cols_matFifty$col_clus]\n\t\t\t# print(prevClus)\n\t\t}\n\t\telse if (prevClus == as.integer(mat_eventPoints[i,cols_matFifty$col_clus])){\n\t\t\t# update x if smaller (and then also color to be opposite)\n\n\t\t\tif (as.numeric(mat_clusConnLines[i, cols_clusPlotObjs$col_x0]) < as.numeric(mat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x1]) ){\n\t\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x0] = mat_clusConnLines[i, cols_clusPlotObjs$col_x0];\n\t\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_col] <- getOppColor(mat_eventPoints[i, cols_matFifty$col_dir])\n\t\t\t}\n\t\t}\n\t\telse if (prevClus != mat_eventPoints[i,cols_matFifty$col_clus]){\n\t\t\tprevClus = mat_eventPoints[i,cols_matFifty$col_clus]\n\t\t\tbasalCounter = basalCounter + 1\n\t\t\t# store everything again\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x0] = xStart;\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_x1] = mat_clusConnLines[i, cols_clusPlotObjs$col_x0];\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_y0] = mat_clusConnLines[i, cols_clusPlotObjs$col_y0];\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_y1] = mat_clusConnLines[i, cols_clusPlotObjs$col_y1];\n\n\t\t\tmat_basalConnLines[basalCounter, cols_clusPlotObjs$col_col] <- getOppColor(mat_eventPoints[i, cols_matFifty$col_dir])\n\n\n\t\t}\n\n\t}\n\n\tmat_clusConnLines = rbind(mat_clusConnLines, mat_basalConnLines)\n\t# print(mat_clusConnLines)\n\t# print(mat_eventPoints)\n\treturn (mat_clusConnLines)\n\n}\n\ngetOppColor <- function (thisCol){\n\t# omics colors\n\tif (thisCol == color_events$up){\n\t\treturn (color_events$down)\n\t}\n\telse if (thisCol == color_events$down){\n\t\treturn (color_events$up)\n\t}\n\n\t# multiomics colors\n\tfor (i in 1:length(Color_multiomics)){\n\t\tif (thisCol == Color_multiomics[[i]]$incr){\n\t\t\treturn (Color_multiomics[[i]]$decr)\n\t\t}\n\t\telse if (thisCol == Color_multiomics[[i]]$decr){\n\t\t\treturn (Color_multiomics[[i]]$incr)\n\t\t}\n\t}\n\n\treturn (\"black\")\n}\n\ngetTheEndX <- function(mat_eventPoints, eventNum, defaultEndX){\n\tendX <- defaultEndX\n\n\tstartX <- mat_eventPoints[eventNum, cols_matFifty$col_x]\n\n\tfor (i in 1:nrow(mat_eventPoints)){\n\t\tif (i != eventNum){ # if not the current event\n\t\t\tif (mat_eventPoints[i, cols_matFifty$col_clus] == mat_eventPoints[eventNum, cols_matFifty$col_clus]){ # if same cluster\n\t\t\t\tif (as.numeric(mat_eventPoints[i, cols_matFifty$col_x]) > as.numeric(startX) && as.numeric(mat_eventPoints[i, cols_matFifty$col_x]) < as.numeric(endX)){ # if newX > startX && < endX; then update\n\t\t\t\t\tendX <- mat_eventPoints[i, cols_matFifty$col_x]\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn (endX)\n}\n\ngetYaxisLabels <- function(mat_eventPoints){\n\tord <- order(as.numeric(mat_eventPoints[,cols_matFifty$col_x]))\n\tclusNums <- as.numeric(mat_eventPoints[ord,1])\n\tclusNumLabels <- c()\n\n\tfor(i in 1:length(clusNums)){\n\t\tif (! clusNums[[i]] %in% clusNumLabels){\n\t\t\tclusNumLabels <- append(clusNumLabels, clusNums[[i]])\n\t\t}\n\t}\n\tvec_labels = as.vector(clusNumLabels)\n\n\treturn (vec_labels)\n}\n\n\ngetYIfClusPres <- function(currClusNum, mat_eventPoints){\n\n\tfor (rowNum in 1:nrow(mat_eventPoints)){\n\t\tif (!is.na(mat_eventPoints[rowNum, cols_matFifty$col_clus]) && currClusNum == mat_eventPoints[rowNum, cols_matFifty$col_clus]){\n\t\t\treturn (mat_eventPoints[rowNum, cols_matFifty$col_y])\n\t\t}\n\t}\n\n\treturn (-1)\n}\n\nisAnyNonSignifFromPrevAll <- function(list_eventsOrder, currLayerNum, signifs){\n\n\tfor (i in seq(1, (currLayerNum - 1))){\n\t\tisAny = isAnyNonSignifFromPrev(list_eventsOrder[[currLayerNum]], list_eventsOrder[[i]], signifs)\n\t\tif (isAny == TRUE){\n\t\t\treturn (TRUE)\n\t\t}\n\t}\n\n\treturn (FALSE)\n}\n\n\ngetColorIfMultiOmics <- function(eventNum, mat_events, dir){\n\tdatasetNum <- mat_events[eventNum, Col_events$combinedDatasetNum]\n\n\tif (is.na(datasetNum) && dir == 1){\n\t\treturn(color_events$up)\n\t}\n\telse if (is.na(datasetNum) && dir == -1){\n\t\treturn(color_events$down)\n\t}\n\n\n\t# otherwise its a multiomics data sets.\n\tif (dir == 1){\n\t\treturn(Color_multiomics[[datasetNum]]$incr)\n\t}\n\n\telse if(dir == -1){\n\t\treturn(Color_multiomics[[datasetNum]]$decr)\n\t}\n\n}\n\n\ngetTheClusLines <- function(mat_fiftyPoints, list_eventsOrder, signifs, list_blocks, xStart, xIncrSig, xIncrNonSig, yDecr){ #xStart, yStart, y_decr, x_incr_sig, x_incr_nonSig\n\n\tmat_eventPoints <- matrix(nrow=nrow(mat_fiftyPoints), ncol=4)\n\n\tx <- xStart\n\ty <- max(mat_fiftyPoints[,1])\n\n\teventsVisited = c()\n\n\tfor (i in 1:length(list_eventsOrder)){\n\t\tfor (j in 1:length(list_eventsOrder[[i]])){\n\t\t\teventNum <- list_eventsOrder[[i]][j]\n\n\t\t\t# adding y coordinate\n\t\t\tprevY <- getYIfClusPres(mat_fiftyPoints[eventNum, cols_matFifty$col_clus], mat_eventPoints)\n\t\t\tif (prevY == -1){\n\t\t\t\tmat_eventPoints[eventNum, cols_matFifty$col_y] <- y\n\t\t\t\ty <- y - yDecr\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmat_eventPoints[eventNum, cols_matFifty$col_y] <- prevY\n\t\t\t}\n\n\t\t\t# assigning color\n\n\t\t\t# if (mat_fiftyPoints[eventNum, cols_matFifty$col_dir] == 1){\n\t\t\ttheColor <- getColorIfMultiOmics(eventNum, mat_fiftyPoints, mat_fiftyPoints[eventNum, cols_matFifty$col_dir])\n\n\t\t\tmat_eventPoints[eventNum, cols_matFifty$col_dir] = theColor\n\t\t\t# }\n\t\t\t#else{\n\t\t\t#\ttheColor <- getColorIfMultiOmics(eventNum, mat_fiftyPoints, -1)\n\t\t\t#\tmat_eventPoints[eventNum, cols_matFifty$col_dir] = theColor\n\t\t\t#}\n\n\t\t\t# assigning cluster number\n\t\t\tmat_eventPoints[eventNum, cols_matFifty$col_clus] <- mat_fiftyPoints[eventNum, cols_matFifty$col_clus]\n\n\t\t\teventsVisited <- c(eventsVisited, eventNum)\n\t\t}\n\n\t\t# adding x coordinate\n\t\tif (i == 1){\n\t\t\t#print(\"over here..?\")\n\t\t\tmat_eventPoints <- addXForAll(list_eventsOrder[[i]], mat_eventPoints, x)\n\t\t}\n\t\telse{\n\t\t\t# if (isAnyNonSignifFromPrev(list_eventsOrder[[i]], list_eventsOrder[[i-1]], signifs) == TRUE){ # place events closer together\n\t\t\tif (isAnyNonSignifFromPrevAll(list_eventsOrder, i, signifs) == TRUE || isInSameBlock(list_eventsOrder[[i]], eventsVisited, list_blocks)){\n\t\t\t\tx <- x + xIncrNonSig\n\t\t\t}\n\t\t\telse {\n\t\t\t\tx <- x + xIncrSig\n\t\t\t}\n\n\t\t\tmat_eventPoints <- addXForAll(list_eventsOrder[[i]], mat_eventPoints, x)\n\n\t\t}\n\t}\n\n\t# print(\"The mat event points:\")\n\t# print (mat_eventPoints)\n\treturn (mat_eventPoints)\n\n}\n\nisInSameBlock <- function(events, eventsVisited, list_blocks){\n\n\t# 1. find block.\n\t# 2. exclude events from block, and from eventsVisited.\n\t# 3. See if others in block, which are also visited.\n\t# if so, return true, else return false.\n\n\n\n\tblockNum <- findBlock(events[1], list_blocks)\n\n\n\teventsInBlock <- as.vector(list_blocks[[blockNum]])\n\totherEventsInBlock <- setdiff(eventsInBlock, events)\n\n\totherEventsVisited <- setdiff(eventsVisited, events)\n\n\tif (length(otherEventsInBlock) > 0 && length(otherEventsVisited) > 0 && (any(otherEventsVisited %in% otherEventsInBlock) || any(otherEventsInBlock %in% otherEventsVisited))) {\n\t\treturn (TRUE)\n\t}\n\n\treturn (FALSE)\n}\n\nfindBlock <- function(event, list_blocks){\n\ti = -1\n\tfor (i in 1:length(list_blocks)){\n\t\tif (event %in% list_blocks[[i]]){\n\t\t\treturn (i)\n\t\t}\n\t}\n\n\treturn (i)\n}\n\n\n\nisAnyNonSignifFromPrev <- function(vec_curr, vec_prev, signifs){\n\n\tfor (i in 1:length(vec_curr)){\n\t\tfor (j in 1:length(vec_prev)){\n\n\t\t\t# print(paste(i, j, length(vec_curr), length(vec_prev), signifs[vec_curr[i], vec_prev[j]]))\n\n\t\t\tif (signifs[vec_curr[i], vec_prev[j]] == FALSE){\n\t\t\t\treturn (TRUE)\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn (FALSE)\n}\n\naddXForAll <- function(vec_curr, mat_eventPoints, x){\n\n\tfor (i in 1:length(vec_curr)){\n\t\tmat_eventPoints[vec_curr[i], cols_matFifty$col_x] <- x\n\t}\n\n\treturn (mat_eventPoints)\n}\n", "meta": {"hexsha": "6400f0e3add7b2c0c93b88eebc6add22629f1d31", "size": 43418, "ext": "r", "lang": "R", "max_stars_repo_path": "R/orderedEvents.r", "max_stars_repo_name": "ODonoghueLab/Minardo-Model", "max_stars_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-25T03:08:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T10:14:50.000Z", "max_issues_repo_path": "R/orderedEvents.r", "max_issues_repo_name": "ODonoghueLab/Minardo-Model", "max_issues_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-08T09:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T02:36:36.000Z", "max_forks_repo_path": "R/orderedEvents.r", "max_forks_repo_name": "ODonoghueLab/Minardo-Model", "max_forks_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.067867036, "max_line_length": 422, "alphanum_fraction": 0.7170758672, "num_tokens": 13288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}} {"text": "################################################################################\r\n# 1 2 3 4 5 6 7 8 \r\n#2345678901234567890123456789012345678901234567890123456789012345678901234567890\r\n################################################################################\r\n# PARAMETER FUNCTION\r\n# functions used in estimation of parameters for warmouth model\r\n#-------------------------------------------------------------------------------\r\n# Growth functions\r\n\r\n# Function to est growth based on VB relationship\r\n# can use form with t0 or form with L0\r\n# use of either form based on specification of t0 or L0\r\n# can only specify 1 and other must be NA\r\nVB.growth <- function(t, Linf, K, t0 = NA, L0 = NA, names = FALSE) {\r\n \r\n if(is.na(L0[1])){\r\n L <- Linf * (1 - exp(-K * (t - t0))) # t0 form\r\n } else if (is.na(t0[1])) {\r\n L <- Linf - (Linf - L0) * exp(-K * t) # L0 form\r\n }\r\n if(names == TRUE) names(L) <- paste0(\"L\", t)\r\n L\r\n}\r\n\r\n# function to est age from VB growth function\r\n# can use form with t0 or form with L0\r\n# use of either form based on specification of t0 or L0\r\n# can only specify 1 and other must be NA\r\nagebyVB <- function(L, Linf, K, t0 = NA, L0 = NA){\r\n \r\n if(is.na(L0[1])){\r\n t <- -1 / K * log( 1 - L / Linf) + t0 # t0 form\r\n } else if (is.na(t0[1])) {\r\n t <- log(-((L - Linf) / (Linf - L0)))/-K # L0 form\r\n }\r\n t\r\n}\r\n\r\n#-------------------------------------------------------------------------------\r\n# Estimate population growth rate and predict confidence/prediction interval\r\n# Based on data and fit from Randall et al (1995) and adjustemnt to relationship\r\n# from Randall and Minns (2000)\r\n\r\nr_max_pred <- function(w, # prediction weight\r\n h, # prediction habitat (1 = lake; 2 = river)\r\n interval){ # confidence or prediction interval\r\n \r\n # Data from Randall et al. (1995)\r\n data <- as.data.frame(list(\r\n Production = c(30.3, 3.8, 2.0, 228.5, 15.5, 4.7, 21.5, 30.8, 5.7, 85.7, 8.6,\r\n 270.0, 596.0, 198.0, 140.0, 100.0, 74.0, 52.0, 30.0, 174.5,\r\n 280.3, 243.5, 226.4, 375.4, 379.1, 217.6, 500.6, 297.2, 110.3,\r\n 128.8, 161.4, 83.4, 807.2, 228.0, 329.0, 168.7, 57.2, 147.3,\r\n 54.8, 76.5, 30.7, 35.3, 261.5, 98.3, 39.3, 33.3, 47.5, 26.1,\r\n 31.2, 53.0, 456.2, 80.3, 29.4),\r\n biomass = c(73.0, 7.3, 9.2, 372.2, 32.2, 11.2, 28.9, 11.6, 24.4, 277.8, 29.5,\r\n 161.2, 198.0, 95.0, 75.0, 59.0, 51.0, 129.0, 62.0, 124.4,\r\n 274.8, 228.4, 149.9, 376.0, 278.7, 127.5, 217.5, 187.2, 111.2,\r\n 241.0, 307.5, 50.2, 310.5, 142.5, 86.6, 45.6, 10.8, 40.9, 49.8,\r\n 42.5, 38.4, 37.4, 173.0, 71.0, 30.5, 21.3, 38.5, 21.5, 27.1, 36.0,\r\n 233.4, 80.2, 15.4),\r\n weight = c(18.0246914, 3.5540409, 25.8426966, 6.6786291, 24.2105263, 37.8378378,\r\n 17.8947368, 5.7058534, 219.8198198, 13.6712598, 64.2701525, 1.24,\r\n 0.2544987, 1.4843750, 3.0, 2.4583333, 5.6666667, 18.4285714, 15.5,\r\n 2.4777915, 2.3869707, 1.4815487, 0.7197976, 3.7586469, 1.3582997,\r\n 2.0675564, 1.6603053, 0.6602313, 2.8333376, 13.9872316, 6.1428743,\r\n 2.1183222, 9.3047648, 4.2462529, 4.4194948, 0.4892704, 1.6410880,\r\n 0.8880686, 7.9935795, 0.9173916, 5.9222702, 10.0700054, 0.8397202,\r\n 1.3179144, 1.9223497, 2.1759117, 3.3804548, 2.6022755, 3.7215051,\r\n 2.7067669, 5.1344098, 12.0819524, 0.6273679),\r\n habitat = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r\n 1, 1, 1, 1, 1, 1, 1, 1, 1)\r\n ))\r\n \r\n # fit regression model\r\n mod = lm(log10(Production/biomass) ~ log10(weight) + habitat, data = data)\r\n \r\n # x prediction values\r\n pred.data = data.frame(weight = w, habitat = h)\r\n \r\n # make prediction with desired interval estiamte\r\n rmax = (predict(mod, pred.data, interval = interval))\r\n \r\n # retransform and multiply by 2 (Randall and Minns 2000)\r\n 10^rmax*2\r\n}\r\n\r\n\r\n#-------------------------------------------------------------------------------\r\n# OTHER\r\n\r\n# function to calc geometric mean between sequenital values in a vector\r\ngeom_mean_seq <- function(vec) {\r\n n = length(vec)\r\n sqrt(vec[2:n]*vec[1:(n-1)])\r\n}\r\n\r\n# geometric mean of a vector\r\ngeom_mean <- function(vec, na.rm = FALSE) {\r\n exp(mean(log(vec), na.rm = na.rm))\r\n}\r\n\r\n#-------------------------------------------------------------------------------\r\n# For parameterizing projection matrix from expression \r\n\r\npmx_eval = function(mx, vars){\r\n matrix(sapply(mx, eval, vars), sqrt(length(mx)), sqrt(length(mx)), byrow = T)\r\n}\r\n\r\n#===============================================================================\r\n# Distribution functions\r\n\r\n# Function to estimate shape parameters of the beta distribution\r\n# from the defined mean and variance of data\r\nbeta_val <- function(mean, var){\r\n \r\n a <- mean * ((mean * (1 - mean)) / var - 1)\r\n b <- (1 - mean) * ((mean * (1 - mean)) / var - 1)\r\n \r\n list(a = a, b = b)\r\n}\r\n\r\n# Function to estimate shape parameters of the streched beta distribution\r\n# from the defined mean and variance of data\r\n# Streched beta is a beta dist'n scaled to outside (0,1) limits\r\n# shape parameters give regulare beat dist'n which must be scaled with\r\n# (max - min) + min when generating values with rbeta\r\nbeta_stretch_val <- function(mean, var = NA, sd = NA){\r\n \r\n if(is.na(var[1])) var = sd^2 # calc variance if not given\r\n if(is.na(sd[1])) sd = sqrt(var) # calc sd if not given\r\n \r\n # estimate mins and max of distribution\r\n min = qnorm(1e-6, mean, sd = sd)\r\n max = qnorm(1 - 1e-6, mean, sd = sd)\r\n \r\n # Scale means and variance to between 0 and 1\r\n mean.b <- (mean - min) / (max - min)\r\n var.b <- var * (1 / (max - min))^2\r\n \r\n # estimate beta dist'n shape parameters\r\n a <- mean.b * ((mean.b * (1 - mean.b)) / var.b - 1)\r\n b <- (1 - mean.b) * ((mean.b * (1 - mean.b)) / var.b - 1)\r\n \r\n # output\r\n list(a = a, b = b, min = min, max = max)\r\n}\r\n\r\n#===============================================================================\r\n# Initial population size vector\r\n# est. pop vector from desire adult population size\r\n\r\ninit_pop <- function(mx, # Population Matrix \r\n Nt, # desire adult density\r\n p.rep # maturity vector - 1: mature; 0: Juvenle; length Tmax + 1\r\n) \r\n{\r\n \r\n SS <- stable.stage(mx) # Stable stage distn\r\n Na <- SS * p.rep / sum(SS * p.rep) * Nt # Calc adult pop\r\n Nj <- SS * (1-p.rep)/ sum(SS * p.rep) * Nt # Calc juv pop\r\n N <- Nj + Na \r\n N\r\n}\r\n\r\n#===============================================================================\r\n\r\n# Function to project population size including density dependence effects\r\nProjection <- function(mx, # projection matrix expression\r\n data, # life history data\r\n lh_mean, # mean life history data\r\n N0, # initial age1+ population size pop size \r\n years, # years to run simulation\r\n p.cat, # Probability of castastrophe\r\n density_dependence = FALSE, # Boolean; if density-depedence included\r\n demographic_stoch = FALSE, # Boolean: if dempgraphic stochasticity included\r\n allee = FALSE # Boolean: if allee effects included\r\n){\r\n #-----------------------------------------------------------------------------\r\n \r\n # needs popbio library\r\n require(popbio)\r\n \r\n # Castastrophes\r\n Catastrophe = sample(c(1,0), years, replace = TRUE,\r\n prob = c(p.cat / data$gen.time, 1 - p.cat / data$gen.time))\r\n \r\n # effect on castastrophe on pop size (percent recuction) - scaled Beta dist'n fit from Reed et al. (2003)\r\n e.cat <- sapply(Catastrophe, function(x) {\r\n ifelse(x == 0, NA, rbeta(1, shape1 = 0.762, shape2 = 1.5) * (1 - .5) + .5)\r\n })\r\n \r\n # Initialize parameters\r\n lh <- lh_mean \r\n \r\n fs <- f_rand(with(lh, c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n ss <- s_rand(with(lh, c(s0, s1, s2, s3)), cv = data$M.cv)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n # Population matrix\r\n A <- pmx_eval(mx, lh)\r\n \r\n # Initial population structure\r\n N <- as.vector(stable.stage(A) * N0 ) \r\n #N <- as.vector(A %*% init_pop(A, Na, data$p.rep) ) \r\n \r\n # initialize output vectors \r\n Nvec <- rep(NA, years + 1); Nvec[1] <- sum(N) # * data$p.rep) # Adult pop vector\r\n Evec <- rep(NA, years + 1);\r\n s0s <- NULL # density dependent parameters\r\n Ns <- list(N) # age-specific annual population size \r\n lambdas <- rep(NA, years) # population growth rate\r\n \r\n # stochastic parameters\r\n fts <- list(fs)\r\n sts <- list(ss$ss)\r\n \r\n #-----------------------------------------------------------------------------\r\n # loop through years\r\n for(t in 1:years){\r\n \r\n #---------------------------------------------------------------------------\r\n # Density Dependence\r\n \r\n # Allee Effects\r\n if(allee) {\r\n \r\n lh$a.f <- sum(N*data$p.rep) ^ 2 / (data$a ^ 2 + sum(N*data$p.rep) ^ 2)\r\n if(is.finite(lh$a.f) == F) lh$a.f = 0\r\n \r\n }\r\n \r\n # Survival Density-Dependence\r\n Et <- E_est(lh, N) # Egg count\r\n Evec[t] <- Et # save egg count in vector\r\n if(density_dependence) {\r\n \r\n #s0.d <- data$s0.max * exp(-data$b * Et)\r\n s0.d <- data$s0.max / (1 + data$b * Et) \r\n if(s0.d < 1e-300) s0.d <- 1e-300\r\n \r\n # Mean survival rate\r\n lh_mean$s0 <- s0.d\r\n } \r\n \r\n # Demographic Stochasticity\r\n # simlulates random variation in vital rates when pop size is small.\r\n # make N random drawns for each age class for vital rates. as N increase the\r\n # draw will be closer to the mean, samller Ns will be more stochastic\r\n if(demographic_stoch) {\r\n # Survival rate\r\n # Binomial distribution - Sum N drawn and divide by N to give mean Survival\r\n lh$s0 <- lh_mean$s0\r\n lh$s1 <- lh$s2 <- lh$s3 <- ifelse(sum(N) > 1 & sum(N) < 500, \r\n sum(rbinom(sum(N), 1, lh_mean$s1))/sum(N), \r\n lh_mean$s1)\r\n \r\n # Fecundity\r\n # Poison dist. - take mean of N/2 (females) draws to give mean fecundity\r\n lh$f1 <- lh$f2 <- lh$f3 <- lh$f4 <- ifelse(sum(N*data$p.rep) > 2 & sum(N*data$p.rep) < 500, \r\n mean(rpois(sum(N*data$p.rep)/2, lh_mean$f2)), \r\n lh_mean$f2) \r\n }else { \r\n lh <- lh_mean \r\n }\r\n \r\n #---------------------------------------------------------------------------\r\n # Stochasticity\r\n \r\n # Fecundity\r\n fs <- f_rand(with(lh, c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n # Survival\r\n ss <- s_rand(with(lh, c(s0, s1, s2, s3)), cv = data$M.cv)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n #---------------------------------------------------------------------------\r\n # Population\r\n \r\n # Projection matrix\r\n A <- pmx_eval(mx, lh) \r\n \r\n # project the population 1 year ahead.\r\n if(Catastrophe[t] == 1){\r\n N <- N * (1 - e.cat[t])\r\n } else {\r\n N <- as.vector(A %*% N ) \r\n }\r\n \r\n Nvec[t + 1] <- sum(N) # Number of mature fish in pop\r\n s0s <- c(s0s, lh_mean$s0)\r\n \r\n Ns[t + 1] <- list(N)\r\n \r\n lambdas[t] <- Nvec[t + 1]/Nvec[t] # pop growth rate\r\n \r\n fts[t + 1] <- list(fs)\r\n sts[t + 1] <- list(ss$ss)\r\n \r\n }\r\n \r\n #-----------------------------------------------------------------------------\r\n # output\r\n list(pop = as.data.frame(list(year = 0:years,\r\n N = Nvec,\r\n E = Evec,\r\n s0 = c(s0s, NA))),\r\n \r\n N = do.call(rbind, Ns),\r\n \r\n lambdas = lambdas,\r\n vars = list(\r\n ft = do.call(rbind, fts),\r\n st = do.call(rbind, sts)\r\n ),\r\n Cat = as.data.frame(list(\r\n Cat = Catastrophe,\r\n e.cat = e.cat\r\n ))\r\n \r\n )\r\n}\r\n\r\n#===============================================================================\r\n# Repatriation\r\n\r\nrepatriation <- function(mx, # projection matrix expression\r\n data, # life history data\r\n lh_mean, # mean life history data\r\n Ninit = 0, # initial adult population size pop size\r\n Nt.vec, # transfered population as vector of ages 0:tmax\r\n s.t, # survvial rate during translocation\r\n t.time, # when stocking takes place =\"pre.spawn\" OR \"post.spawn\" \r\n stock.month, # num. months post spawned stocking takes place\r\n stock.max, # number of stocking events to take place\r\n years, # years to run simulation\r\n p.cat # Probability of castastrophe\r\n){\r\n #-----------------------------------------------------------------------------\r\n \r\n # needs popbio library\r\n require(popbio)\r\n \r\n # Castastrophes\r\n Catastrophe = sample(c(1,0), years, replace = TRUE,\r\n prob = c(p.cat / data$gen.time, 1 - p.cat / data$gen.time))\r\n \r\n # effect on castastrophe on pop size (percent recuction) - scaled Beta dist'n fit from Reed et al. (2003)\r\n e.cat <- sapply(Catastrophe, function(x) {\r\n ifelse(x == 0, NA, rbeta(1, shape1 = 0.762, shape2 = 1.5) * (1 - .5) + .5)\r\n })\r\n \r\n # Initialize parameters\r\n lh <- lh_mean \r\n \r\n fs <- f_rand(with(lh_mean , c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n ss <- s_rand(with(lh_mean , c(s0, s1, s2, s3)), cv = data$M.cv)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n # Population matrix\r\n A <- pmx_eval(mx, lh)\r\n \r\n # Initial population structure\r\n N <- as.vector(stable.stage(A) * Ninit ) \r\n \r\n # initialize output vectors \r\n Nvec <- rep(NA, years); #Adult pop vector\r\n Ns <- list(N) # age-specific annual population size \r\n \r\n # stock counter\r\n stock.count <- 0\r\n \r\n #-----------------------------------------------------------------------------\r\n # loop through years\r\n for(t in 1:years){\r\n \r\n # stocking pre spawning\r\n if(t.time == \"pre.spawn\" & stock.count < stock.max){\r\n N <- N + Nt.vec * s.t \r\n stock.count <- stock.count + 1\r\n }\r\n \r\n #---------------------------------------------------------------------------\r\n # Density Dependence\r\n \r\n # Allee\r\n lh$a.f <- sum(N*data$p.rep) ^ 2 / (data$a ^ 2 + sum(N*data$p.rep) ^ 2)\r\n if(is.finite(lh$a.f) == F) lh$a.f = 0\r\n \r\n # SURVIVAL\r\n Et <- E_est(lh, N)\r\n \r\n #s0.d <- data$s0.max * exp(-data$b * Et)\r\n s0.d <- data$s0.max / (1 + data$b * Et) \r\n if(s0.d < 1e-300) s0.d <- 1e-300\r\n \r\n # Mean survival rate\r\n lh$s0 <- s0.d\r\n\r\n #---------------------------------------------------------------------------\r\n # Demographic Stochasticity\r\n # simlulates random variation in vital rates when pop size is small.\r\n # make N random drawns for each age class for vital rates. as N increase the\r\n # draw will be closer to the mean, samller Ns will be more stochastic\r\n \r\n # Survival rate\r\n # Binomial distribution - Sum N drawn and divide by N to give mean Survival\r\n lh$s1 <- lh$s2 <- lh$s3 <- ifelse(sum(N) > 1 & sum(N) < 500, \r\n sum(rbinom(sum(N), 1, lh_mean$s1))/sum(N), \r\n lh_mean$s1)\r\n \r\n # Fecundity\r\n # Poison dist. - take mean of N/2 (females) draws to give mean fecundity\r\n lh$f1 <- lh$f2 <- lh$f3 <- lh$f4 <- ifelse(sum(N*data$p.rep) > 2 & sum(N*data$p.rep) < 500, \r\n mean(rpois(sum(N*data$p.rep)/2, lh_mean$f2)), \r\n lh_mean$f2) \r\n \r\n #---------------------------------------------------------------------------\r\n # Stochasticity\r\n \r\n # Fecundity\r\n fs <- f_rand(with(lh, c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n # Survival\r\n ss <- s_rand(means = with(lh, c(s0, s1, s2, s3)), cv = data$M.cv, X = NA)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n #---------------------------------------------------------------------------\r\n # Population\r\n \r\n # Projection matrix\r\n A <- pmx_eval(mx, lh) \r\n \r\n # project the population 1 year ahead.\r\n if(Catastrophe[t] == 1){\r\n N <- N * (1 - e.cat[t])\r\n } else {\r\n N <- as.vector(A %*% N ) \r\n }\r\n \r\n # Stocking - post spawning\r\n # Stocked fish must survival the year before spawning - included stochasticity\r\n if(t.time == \"post.spawn\" & stock.count < stock.max){\r\n \r\n # Demographic stochasticity\r\n lh.s <- lh\r\n lh.s$s1 <- lh.s$s2 <- lh.s$s3 <- ifelse(sum(Nt.vec) > 1 & sum(Nt.vec) < 500, \r\n sum(rbinom(sum(Nt.vec), 1, lh_mean$s1))/sum(Nt.vec), \r\n lh_mean$s1)\r\n \r\n # Environmental stochasticity - same residuals as in matrix (X = ss$X)\r\n ss <- s_rand(with(lh.s, c(s0, s1, s2, s3)), cv = data$M.cv, X = ss$X)\r\n lh.s$s0 <- ss$ss[1]; lh.s$s1 <- ss$ss[2]; lh.s$s2 <- ss$ss[3]; lh.s$s3 <- ss$ss[4]; \r\n \r\n # add stocked fish to pop vector - include mortality scaled to time remaiing in year\r\n N <- N + Nt.vec * s.t * with(lh.s, c(s1, s2, s3, 0)) ^ ((12 - stock.month)/12)\r\n \r\n # increment stocking counter\r\n stock.count <- stock.count + 1\r\n }\r\n \r\n # outputs\r\n Nvec[t] <- sum(N) # Number of mature fish in pop\r\n\r\n Ns[t] <- list(N) # Pop vector for output\r\n \r\n \r\n }\r\n #-----------------------------------------------------------------------------\r\n # output\r\n list(pop = as.data.frame(list(year = 1:years,\r\n N = Nvec)),\r\n \r\n N = do.call(rbind, Ns)\r\n )\r\n}\r\n\r\n#===============================================================================\r\n# Source Population Harm\r\n\r\n# Function to project population size including density dependence effects\r\nsource_harm <- function(mx, # projection matrix expression\r\n data, # life history data\r\n lh_mean, # mean life history data\r\n Ninit , # initial adult population size pop size\r\n Nt.vec, # transfered population as vector of ages 0:tmax\r\n t.time, # when stocking takes place =\"pre.spawn\" OR \"post.spawn\" \r\n stock.max, # number of stocking events to take place\r\n years, # years to run simulation\r\n p.cat # Probability of castastrophe \"Length\" and or \"Survival\"\r\n){\r\n #-----------------------------------------------------------------------------\r\n \r\n # needs popbio library\r\n require(popbio)\r\n \r\n # Castastrophes\r\n Catastrophe = sample(c(1,0), years, replace = TRUE,\r\n prob = c(p.cat / data$gen.time, 1 - p.cat / data$gen.time))\r\n \r\n # effect on castastrophe on pop size (percent recuction) - scaled Beta dist'n fit from Reed et al. (2003)\r\n e.cat <- sapply(Catastrophe, function(x) {\r\n ifelse(x == 0, NA, rbeta(1, shape1 = 0.762, shape2 = 1.5) * (1 - .5) + .5)\r\n })\r\n \r\n # Initialize parameters\r\n lh <- lh_mean \r\n \r\n fs <- f_rand(with(lh_mean , c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n ss <- s_rand(with(lh_mean , c(s0, s1, s2, s3)), cv = data$M.cv)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n # Population matrix\r\n A <- pmx_eval(mx, lh)\r\n \r\n # Initial population structure\r\n N <- as.vector(stable.stage(A) * Ninit) \r\n \r\n # initialize output vectors \r\n Nvec <- rep(NA, years + 1); Nvec[1] <- sum(N)# * data$p.rep) # Adult pop vector\r\n Ns <- list(N) # age-specific annual population size \r\n\r\n # stock counter\r\n stock.count <- 0\r\n \r\n #-----------------------------------------------------------------------------\r\n # loop through years\r\n for(t in 1:years){\r\n \r\n # stocking pre spawning\r\n if(t.time == \"pre.spawn\" & stock.count < stock.max){\r\n N <- N - Nt.vec \r\n N <- ifelse(N > 1, N, 0)\r\n stock.count <- stock.count + 1\r\n }\r\n\r\n #---------------------------------------------------------------------------\r\n # Density Dependence\r\n \r\n # Allee Effects\r\n lh$a.f <- sum(N*data$p.rep) ^ 2 / (data$a ^ 2 + sum(N*data$p.rep) ^ 2)\r\n if(is.finite(lh$a.f) == F) lh$a.f = 0\r\n \r\n # Survival Density-Dependence\r\n Et <- E_est(lh, N) # Egg count\r\n s0.d <- data$s0.max / (1 + data$b * Et) \r\n if(s0.d < 1e-300) s0.d <- 1e-300\r\n \r\n # Mean survival rate\r\n lh_mean$s0 <- s0.d\r\n \r\n # Demographic Stochasticity\r\n # simlulates random variation in vital rates when pop size is small.\r\n # make N random drawns for each age class for vital rates. as N increase the\r\n # draw will be closer to the mean, samller Ns will be more stochastic\r\n\r\n # Survival rate\r\n # Binomial distribution - Sum N drawn and divide by N to give mean Survival\r\n lh$s0 <- lh_mean$s0\r\n lh$s1 <- lh$s2 <- lh$s3 <- ifelse(sum(N) > 1 & sum(N) < 500, \r\n sum(rbinom(sum(N), 1, lh_mean$s1))/sum(N), \r\n lh_mean$s1)\r\n \r\n # Fecundity\r\n # Poison dist. - take mean of N/2 (females) draws to give mean fecundity\r\n lh$f1 <- lh$f2 <- lh$f3 <- lh$f4 <- ifelse(sum(N*data$p.rep) > 2 & sum(N*data$p.rep) < 500, \r\n mean(rpois(sum(N*data$p.rep)/2, lh_mean$f2)), \r\n lh_mean$f2) \r\n \r\n #---------------------------------------------------------------------------\r\n # Stochasticity\r\n \r\n # Fecundity\r\n fs <- f_rand(with(lh_mean , c(f1, f2, f3, f4)), sd = data$f.logsd)\r\n lh$f1 <- fs[1]; lh$f2 <- fs[2]; lh$f3 <- fs[3]; lh$f4 <- fs[4]; \r\n \r\n # Survival\r\n ss <- s_rand(with(lh_mean , c(s0, s1, s2, s3)), cv = data$M.cv)\r\n lh$s0 <- ss$ss[1]; lh$s1 <- ss$ss[2]; lh$s2 <- ss$ss[3]; lh$s3 <- ss$ss[4]; \r\n \r\n #---------------------------------------------------------------------------\r\n # Population\r\n \r\n # Projection matrix\r\n A <- pmx_eval(mx, lh) \r\n \r\n # project the population 1 year ahead.\r\n if(Catastrophe[t] == 1){\r\n N <- N * (1 - e.cat[t])\r\n } else {\r\n N <- as.vector(A %*% N ) \r\n }\r\n N <- ifelse(N > 1, N, 0)\r\n \r\n #output\r\n Nvec[t + 1] <- sum(N) # Number of age-1+ fish in pop\r\n Ns[t + 1] <- list(N) # pop vector\r\n \r\n # Stocking - post spawning\r\n if(t.time == \"post.spawn\" & stock.count < stock.max){\r\n N <- N - Nt.vec \r\n N <- ifelse(N > 1, N, 0)\r\n stock.count <- stock.count + 1\r\n }\r\n \r\n }\r\n \r\n #-----------------------------------------------------------------------------\r\n # output\r\n list(pop = as.data.frame(list(year = 0:years,\r\n N = Nvec\r\n )),\r\n \r\n N = do.call(rbind, Ns)\r\n )\r\n}\r\n\r\n#===============================================================================", "meta": {"hexsha": "6265621b56fc728c3ef65e8227736b4e768228f4", "size": 24368, "ext": "r", "lang": "R", "max_stars_repo_path": "Rscript 01 - functions.r", "max_stars_repo_name": "KarlLamothe/TranslocationMatModels", "max_stars_repo_head_hexsha": "9b618e58f438b3be679d2b30a1c24e6832ba959d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rscript 01 - functions.r", "max_issues_repo_name": "KarlLamothe/TranslocationMatModels", "max_issues_repo_head_hexsha": "9b618e58f438b3be679d2b30a1c24e6832ba959d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rscript 01 - functions.r", "max_forks_repo_name": "KarlLamothe/TranslocationMatModels", "max_forks_repo_head_hexsha": "9b618e58f438b3be679d2b30a1c24e6832ba959d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8644338118, "max_line_length": 108, "alphanum_fraction": 0.4528069599, "num_tokens": 7110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143777, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4856691551570026}} {"text": "DL = function(y,sW){\nk = length(y)\nw = sW^2\nsum.w = sum(w)\nmu.hat = sum(y*w)/sum.w\nW = sum.w - (sum(w^2)/sum.w)\nQ = sum(w*(y-mu.hat)^2)\ntypS = sum(w*(k-1))/(sum.w^2 - sum(w^2))\nQp = 1-pchisq(Q,k-1)\n\ntausq.hat = max(0,(Q-(k-1))/W)\nw.tauhat = 1/((1/w)+tausq.hat)\n\nreturn(tausq.hat)\n\n}\n\n\n\neff <- c(0.1, 0.2, 0.21, 0.5, 0.3)\nse <- c(0.02, 0.3, 0.03, 0.07, 0.1)\n\n\n\n\na <- rma(yi=eff, sei=se, method=\"FE\")\nb <- rma(yi=eff, sei=se, method=\"DL\")\n\n\n\n\nDL = function(y=logHR, s = se.logHR)\n{\n\tk = length(y)\n\tw = 1/s^2\n\tsum.w = sum(w)\n\tmu.hat = sum(y*w)/sum.w\n\tW = sum.w - (sum(w^2)/sum.w)\n\tQ = sum(w*(y-mu.hat)^2)\n\ttypS = sum(w*(k-1))/(sum.w^2 - sum(w^2))\n\tQp = 1-pchisq(Q,k-1)\n\n\t# fixed effects estimate\n\n\tVar.muhat = 1/sum(w)\n\tmuFE.CI = mu.hat + c(-1.96,1.96)*sqrt(Var.muhat)\n\tZfe = (mu.hat)/sqrt(Var.muhat)\n\tFEp = 2*(1 - pnorm(abs(Zfe)))\n\n\t# DL random effects estimate\n\n\ttausq.hat = max(0,(Q-(k-1))/W)\n\tw.tauhat = 1/(s^2+tausq.hat)\n\tmu.tau.hat = sum(w.tauhat*y)/sum(w.tauhat)\n\tVar.mutauhat = 1/sum(w.tauhat)\n\tmuRE.CI = mu.tau.hat + c(-1.96,1.96)*sqrt(Var.mutauhat)\n\tIsq = tausq.hat/(tausq.hat+typS)\n\tZre = (mu.tau.hat)/sqrt(Var.mutauhat)\n\tREp = 2*(1 - pnorm(abs(Zre)))\n\n\tsum.wre = sum(w.tauhat)\n\n\tsummary = c(k,Q,Qp,(100*Isq),mu.hat,muFE.CI,\n\t FEp,mu.tau.hat,muRE.CI,REp)\n\n\tout = list(\n\t\tfe=mu.hat,\n\t\tfe_se = sqrt(Var.muhat),\n\t\tre=mu.tau.hat,\n\t\tre_se = sqrt(Var.mutauhat)\n\t)\n\n\treturn(out)\n}\n\nDL(eff, se)\n\n\n\n\nrs1100405 t c -0.0178 0.0132 0.177 +-- 0.0 0.388 2 0.8237 0.01514304 0.02311397 0.9879\n\n\n\nCHR\tPOS\tSNP\tN\tEFFECT_ALLELE\tNON_EFFECT_ALLELE\tEFFECT_ALLELE_FREQ\tBETA\tSE\tr2\tr2hat\tP_VAL\n7\t43517495\trs1100405\t1467\t4\t2\t0.342195\t0.00101\t0.03945\t4.47e-07\t0.996\t0.9798\n\nCHR POS SNP STRAND EFFECT_ALLELE NON_EFFECT_ALLELE FREQ_EFFECT N BETA SE r2 PVALUE r2hat\n7 43517495 rs1100405 + C T 0.665 1233 0.023 0.016 0.00152 0.1674 0.9958\n\nSNP\tCHR\tPOS\tRsq\tAL1\tAL2\tFREQ1\tTRAIT\tEFFECT\tSE\tH2\tLOD\tPVALUE\nrs1100405\t7\t43517495\t0.9986\tC\tT\t0.666\tglucose_ND\t0.011\t0.029\t0.008\t0.032\t0.7029\n\n\n\nlibrary(metafor)\n\nrma(y=c(-0.00101, 0.023, 0.011), sei=c(0.03945, 0.016, 0.029), method=\"FE\")\nrma(y=c(-0.00101, 0.023, 0.011), sei=c(0.03945, 0.016, 0.029), method=\"DL\")\n\nDL(c(-0.00101, 0.023, 0.011), c(0.03945, 0.016, 0.029))\n\n\n\n\n\n\n\nrs2433681 a g -0.0149 0.0225 0.5072 -+- 68.2 6.297 2 0.04292 -0.03706755 0.04442108 0.9704\n\n\n\nCHR\tPOS\tSNP\tN\tEFFECT_ALLELE\tNON_EFFECT_ALLELE\tEFFECT_ALLELE_FREQ\tBETA\tSE\tr2\tr2hat\tP_VAL\n2\t169498916\trs2433681\t1467\t1\t3\t0.0978187\t-0.1559\t0.06133\t0.004391\t0.946\t0.0118\n\n\nCHR POS SNP STRAND EFFECT_ALLELE NON_EFFECT_ALLELE FREQ_EFFECT N BETA SE r2 PVALUE r2hat\n2 169498916 rs2433681 + G A 0.926 1233 -0.014 0.029 0.00018 0.6296 0.9918\n\n\nSNP\tCHR\tPOS\tRsq\tAL1\tAL2\tFREQ1\tTRAIT\tEFFECT\tSE\tH2\tLOD\tPVALUE\nrs2433681\t2\t169498916\t0.967\tG\tA\t0.894\tglucose_ND\t0.009\t0.044\t0.002\t0.008\t0.8466\n\n\nrma(y=c(-0.1559, 0.014, -0.009), sei=c(0.06133, 0.029, 0.044), method=\"FE\")\nrma(y=c(-0.1559, 0.014, -0.009), sei=c(0.06133, 0.029, 0.044), method=\"DL\")\n\n", "meta": {"hexsha": "b751eb7f2f22101601a9ac0958aa29fca6547da7", "size": 3230, "ext": "r", "lang": "R", "max_stars_repo_path": "tests/misc.r", "max_stars_repo_name": "explodecomputer/random-metal", "max_stars_repo_head_hexsha": "c79bc9d3f0c6ed29f967b17f43f39e7eb476272c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-29T22:58:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T19:07:25.000Z", "max_issues_repo_path": "tests/misc.r", "max_issues_repo_name": "explodecomputer/random-metal", "max_issues_repo_head_hexsha": "c79bc9d3f0c6ed29f967b17f43f39e7eb476272c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-28T14:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:14:03.000Z", "max_forks_repo_path": "tests/misc.r", "max_forks_repo_name": "explodecomputer/random-metal", "max_forks_repo_head_hexsha": "c79bc9d3f0c6ed29f967b17f43f39e7eb476272c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.234375, "max_line_length": 134, "alphanum_fraction": 0.5826625387, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.485516667175071}} {"text": " # About ============================\n # @author: Adail Carvalho\n # @since : 2018-03-24\n # __________________________________\n \n #Required Libs ====\n checkAndInstallRequiredLib <- function(libname, extralib = NULL) {\n if (!require(libname)) {\n install.packages(libname)\n }\n \n if (!missing(extralib)) {\n if (!require(extralib)) {\n install.packages(extralib) \n }\n }\n }\n # Plotly: library that provides beaultiful chart tools.\n library(plotly)\n\n # Webshot: provides chart exports capabilities.\n library(webshot)\n \n # Matrices / DFrames headers ====\n modelHeader <- c(\"Coefficients\", \"Predictions\", \"RMSErrorRate\", \"Dataset\", \"YDependent\", \"XIndependent\")\n lmHeader <- c(\"Observed Y\",\"Predicted Y\", \"Residual E\")\n \n #Error messages ====\n insuficientArgsException <- simpleError(\"Missing one or more required variables to proceed = \")\n insuficientArgsWarning <- \"Missing one or more required variables to do the requested operation = \"\n illegalArgsException <- simpleError(\"Invalid args: \")\n notSupportedException <- simpleError(\"Operation with the passed args are not supported yet.\")\n \n \n # Main ====\n ' Entry point for our Linear Model program\n # input\n @filePath CSV file that represents the dataset\n @delimiter The CSV file delimiter (if its a TSV, then use \"\\t\")\n @dependentVar Represents the Y column name in the dataset, where Y represents the dependent variable in the Linear Model.\n Colum Y must be numeric.\n @... Represents one or more datasets X columns names, where X represents the independent variables in the Linear Model.\n Columns X must be numerics.\n \n # returns\n @ model A List containing both Predictions and the Linear Model coefficients.\n $Coefficients : list containing the values founded for the linear model coeficients \n $Predictions : matrix that shows the predicted values, the real values for Y and the E residuals\n $RMSErrorRate : rating used to know how good our model is. A good model is always between -1< R <=1.\n $Dataset: a matrix representation of the original dataset.\n # usage\n \n beearModel <- linearModel(\"C:/opt/beer_delivery.csv\",\"\\t\", \"Tempo\", \"NumCaixas\", \"Distancia\")\n houses <- linearModel(\"C:/opt/houses_set.csv\", \",\", \"SalePrice\", \"OverallQual\", \"YearBuilt\", \"MSSubClass\", \"BedroomAbvGr\")\n \n # checking values\n \n houses$Coefficients\n houses$Predictions\n '\n linearModel <- function (filePath, delimiter, dependentVar, ...) {\n independentVarList <- list(...)\n \n if (is.null(dependentVar) || length(independentVarList) == 0) {\n stop(paste(insuficientArgsException, \"{dependentVar, independentVarList}\")) \n }\n \n matrixDataSet <- getFileToMatrix(filePath, delimiter)\n if (length(independentVarList) == 1) {\n model <- simpleLinearModel(matrixDataSet, dependentVar, independentVarList[[1]])\n } else {\n model <- multiLinearModel(matrixDataSet, dependentVar, independentVarList) \n }\n \n returnValue(model)\n }\n \n # Handle general operations to get the results\n # @returns results A list containing the coefficient values, RMSE error and the made predictions.\n simpleLinearModel <- function (matrixDataSet, dependentVar, independentVar) {\n if (!is.matrix(matrixDataSet)) {\n stop(illegalArgsException)\n }\n \n dependentIndex <- grep(dependentVar, colnames(matrixDataSet))\n independentIndex <- grep(independentVar, colnames(matrixDataSet))\n dependentVector <- matrixDataSet[,dependentIndex]\n independentVector <- matrixDataSet[,independentIndex]\n \n slope <- getSLRSlope(independentVector, dependentVector)\n intercept <- getSLRIntercept(independentVector, dependentVector, slope)\n \n resultModel <- doSimplePredictions(intercept, slope, independentVector, dependentVector)\n \n coefficientsMatrix <- matrix(nrow = 1, ncol = 2, dimnames = list(c(1),c(\"Intercept\", independentVar)))\n coefficientsMatrix[,1] <- intercept\n coefficientsMatrix[,2] <- slope\n \n modelErrorRate <- estimateModelError(resultModel[,2])\n \n linearModel <- cbind(dependentVector,resultModel)\n colnames(linearModel) <- lmHeader\n \n # Gather generetade values\n model <- list(coefficientsMatrix, linearModel, modelErrorRate, matrixDataSet, dependentVar, independentVar)\n \n returnValue(model)\n }\n \n '\n Handle general operations to get the results\n @returns results A list containing the coefficient values, RMSE error and the made predictions. \n \n # Usage (directly)\n \n myModel <- multiLinearModel(dataMatrix, \"Y var\", as.list(c(\"var x1\", \"var x2\", \"var xn\")))\n '\n multiLinearModel <- function (matrixDataSet, dependentVar, independentVarList) {\n if (!is.matrix(matrixDataSet)) {\n stop(illegalArgsException)\n }\n \n dependentColIndex <- grep(dependentVar, colnames(matrixDataSet))\n dependentMatrix <- matrixDataSet[,dependentColIndex]\n \n independentMatrix <- getIndependentVarsAsMatrix(matrixDataSet, independentVarList)\n \n levelsMatrix <- getRegressionLevelsMatrix(as.matrix(independentMatrix))\n \n xProductMatrix <- matrixTranposeAndMultiply(levelsMatrix, NULL)\n xProductMatrix <- getInverseMatrix(xProductMatrix)\n yProductMatrix <- matrixTranposeAndMultiply(levelsMatrix, as.matrix(dependentMatrix))\n \n coefficientsMatrix <- getMLRCoefficients(xProductMatrix, yProductMatrix, independentMatrix, independentVarList)\n \n resultModel <- doMultivariantPredictions(coefficientsMatrix, independentMatrix, dependentMatrix)\n \n modelErrorRate <- estimateModelError(resultModel[,2])\n \n linearModel <- cbind(dependentMatrix,resultModel)\n colnames(linearModel) <- lmHeader\n \n model <- list(coefficientsMatrix, linearModel, modelErrorRate, matrixDataSet, dependentVar, independentVarList)\n model <- handleDataHeaders(model, modelHeader)\n \n returnValue(model)\n }\n \n # Linear Model ====\n \n # Estimates the values for Y, using the calculated coefficients.\n # Apllies the following rule: ~Yi : B0 + (B1 * Xi)\n # Where ~Yi = estimated value for dependent value Y, B0 = Slope coefficient, B1 = Intercept coefficient, Xi = observed value for X, \n # and i, the iterator value over the X independent vector\n # returns a Matrix with the estimated values for Y and the residuals E, where E = real value of Y - estimated value for Y\n doSimplePredictions <- function(coefficientB0, coefficientB1, independentVector, dependentVector) {\n predictedY <- vector(\"numeric\", length(dependentVector))\n residuals <- vector(\"numeric\", length(independentVector))\n \n for (i in 1:length(independentVector)) {\n predictedY[i] <- coefficientB0 + (coefficientB1 * independentVector[i])\n }\n \n residualVector <- dependentVector - predictedY\n returnValue(cbind(predictedY, residualVector))\n }\n \n # Estimates the values for Y, using the calculated coefficients.\n # Apllies the following rule: ~Y : B0 + B1(X1 - ~X1) + B2(X2 - ~X2) + ... + Bn(Xn - ~Xn)\n # Where ~Y = estimated value for dependent value Y, Bi = Coeficient values, Xi = observed value for X, ~Xi = mean of X variable.\n # returns a Matrix with the estimated values for Y and the residuals E, where E = real value of Y - estimated value for Y\n doMultivariantPredictions <- function(coefficientsMatrix, independentMatrix, dependentMatrix = NULL) {\n predictedY <- matrix(0, nrow = nrow(independentMatrix), ncol = 1)\n residualMatrix <- matrix(0 , nrow = nrow(independentMatrix), ncol = 1)\n \n for (r in 1:nrow(independentMatrix)) {\n for (coe in 2:ncol(coefficientsMatrix)) {\n predictedY[r,1] <- predictedY[r,1] + (coefficientsMatrix[,coe] * independentMatrix[r,coe - 1])\n }\n predictedY[r,1] <- predictedY[r,1] + coefficientsMatrix[,1]\n }\n \n predictions <-NULL\n if (missing(dependentMatrix)) {\n predictions <- predictedY \n } else {\n residualMatrix <- dependentMatrix - predictedY\n predictions <- cbind(predictedY, residualMatrix)\n }\n \n returnValue(predictions)\n }\n \n # Matrices general operations ====\n getMLRCoefficients <- function(xProductMatrix, yProductMatrix, independentMatrix, xLabels) {\n avgIndMat <- colMeans(independentMatrix)\n \n coefficientsMatrix <- matrixMultiply(xProductMatrix, yProductMatrix)\n coefficientsMatrix <- t(coefficientsMatrix)\n slope <- coefficientsMatrix[,1]\n \n for(c in 2:ncol(coefficientsMatrix)) {\n slope <- slope + (coefficientsMatrix[,c] * (-avgIndMat[c - 1]))\n }\n coefficientsMatrix[,1] <- slope\n colnames(coefficientsMatrix) <-c(\"[Intercept]\", xLabels)\n returnValue(coefficientsMatrix)\n \n }\n # Returns the (matriz)-¹ of a given matrix.\n # inv(x) is a funtion provided by the package matlib*\n getInverseMatrix <- function(matriz) {\n invertedMatrix <- solve(matriz)\n returnValue(invertedMatrix)\n }\n \n # Returns the mean of independent variables in multivariant linear model\n getRegressionLevelsMatrix <- function(matriz) {\n avgIndependentsVarMatrix <- t(as.matrix(colMeans(matriz)))\n levelsMatrix <- cbind(getX0Dimension(matriz), matriz)\n \n for (c in colnames(matriz)) {\n x <- matriz[,c]\n l <- vector(class(x), length(x))\n for (i in 1:length(x)) {\n l[i] <- x[i] - avgIndependentsVarMatrix[,c]\n }\n levelsMatrix[,c] <- l\n }\n returnValue(levelsMatrix) \n }\n \n # Represents the x0 coeficient in the lm equation, where x0 = 1. In the matrix of independent values, it is placed in the first column.\n getX0Dimension <- function(matriz) {\n numRows <- nrow(matriz)\n returnValue(matrix(rep(1, numRows), dimnames = list(c(1:numRows), c(\"X0\"))))\n }\n \n \n # Return product of two matrices \n matrixMultiply <- function(matrixA, matrixB) {\n resultMatrix <- matrix(0, nrow = nrow(matrixA), ncol = ncol(matrixB))\n for (r in 1:nrow(matrixA)) {\n for (c in 1:ncol(matrixB)) {\n for (kol in 1:ncol(matrixA)) {\n resultMatrix[r,c] <- resultMatrix[r,c] + (matrixA[r,kol] * matrixB[kol, c])\n }\n }\n }\n \n returnValue(resultMatrix)\n \n }\n \n # Returns the product of matrices\n matrixTranposeAndMultiply <- function(matriz, matrixB) {\n transpMatrix <- t(matriz)\n \n if (is.null(matrixB)) {\n matrixY <- matriz\n } else {\n matrixY <- matrixB\n } \n \n returnValue(matrixMultiply(transpMatrix, matrixY))\n }\n \n # Linear Regression Rules Application ====\n # Estimate erros using RootMeanSquareError(RMSE).\n # @residualVector Vector that holds the E residuals of our model.\n estimateModelError <- function(residualVector) {\n rmse <- sqrt(sum(residualVector ** 2) / length(residualVector))\n returnValue(rmse)\n }\n \n # Returns SLR Slope value\n getSLRSlope <- function(independentVector, dependentVector) {\n levelsVectorX <- independentVector - mean(independentVector)\n levelsVectorY <- dependentVector - mean(dependentVector)\n \n numeratorB1 <- sum(levelsVectorX * levelsVectorY)\n denominatorB1 <- sum(levelsVectorX ** 2) \n slope <- numeratorB1 / denominatorB1\n \n returnValue(slope)\n }\n \n # Returns SLR Intercept value\n getSLRIntercept <- function (independentVector, dependentVector, slope) {\n intercept <- mean(dependentVector) - (slope * mean(independentVector))\n returnValue(intercept)\n }\n \n # Utils ====\n getIndependentVarsAsMatrix <- function(matrixData, independentVarList) {\n independentMatrix <- matrix(0, nrow = nrow(matrixData), ncol = length(independentVarList))\n colnames(independentMatrix) <- independentVarList\n \n for (i in independentVarList) {\n name <- grep(i, colnames(matrixData))\n independentMatrix[,i] <- matrixData[,name] \n }\n returnValue(independentMatrix)\n }\n \n getFileToMatrix <- function(filePath, delimiter) {\n rawDataSet <- read.csv(filePath, sep = delimiter, header = TRUE)\n returnValue(data.matrix(rawDataSet))\n }\n \n ' Export charts as images.\n @p A chart object\n @filename Name of the file to be saved.\n @ext File extension\n '\n exportChartAsImg <- function(p, filename, ext) {\n export(p, paste(filename, ext)) \n }\n \n handleDataHeaders <- function(data, header) {\n names(data) <- modelHeader \n returnValue(data)\n }\n \n \n # Charts ####\n # Add to a chart labels and title\n applyLayout <- function(p, xLabel, yLabel, chartTitle) {\n title <- NULL\n if (missing(chartTitle)) {\n title <- paste(yLabel, \" by \", xLabel)\n } else {\n title <- chartTitle\n }\n \n p <- layout(p, title = title,\n xaxis = list(title = xLabel),\n yaxis = list (title = yLabel))\n returnValue(p)\n \n }\n \n 'Export models as simple X vs Y line charts, from a given model.\n @ model A LinearRegressor object.\n @ dirToSave The directory where the plots will be exported\n '\n createChartsFromModel <- function(model, dirToSave = NULL) {\n for (x in model$XIndependent) {\n if (isTRUE(grepl('^[0-9]', x))) {\n x <- paste(\"X\", x, sep = \"\")\n } \n \n print(paste(\"Generating chart for => \", x))\n \n p <- lmYXLineChart(model$Dataset[,x], \n model$Dataset[,model$YDependent], \n model$Predictions[,\"Predicted Y\"],\n model$Predictions[,\"Residual E\"],\n x,\n model$YDependent)\n \n exportChartAsImg(p, paste(dirToSave, model$YDependent, \" by \", x), \".png\")\n }\n }\n \n # Creates a line chart, by ploting y in the y axis and x in the x axis. \n # lmYXLineChart(TipoMoradores, PrecoVenda, PrecoPrevisto, ResiduoModelo, \"TipoMoradores\", \"PrecoVenda\")\n lmYXLineChart <- function(xData, yData, yPredicted, eResid, xLabel, yLabel) {\n xName <- xLabel\n yName <- yLabel\n if (missing(xName)) {\n xName <- \"X\"\n }\n \n if (missing(yName)) {\n yName <- \"Y\"\n }\n \n chartFrame <- data.frame(xData, yData, yPredicted, eResid) \n aggData <- aggregate(chartFrame, by = list(chartFrame$xData), FUN = mean)\n \n lmPlot<- plot_ly(aggData, x = ~aggData$xData, name = xName)\n \n lmPlot <- add_trace(lmPlot, y= ~aggData$yData, name = yName, type = 'scatter', mode = 'lines')\n lmPlot <- add_trace(lmPlot, y = ~aggData$yPredicted, name = paste(yName, \"(Pred)\"), type = 'scatter', mode = 'lines')\n lmPlot <- add_trace(lmPlot, y = ~aggData$eResid, name = 'Residual', type = 'scatter', mode = 'markers')\n\n lmPlot <- applyLayout(lmPlot, xName, yName)\n returnValue(lmPlot)\n \n }", "meta": {"hexsha": "d6b1886012e17d3d2116a876ccff879cac046a69", "size": 14567, "ext": "r", "lang": "R", "max_stars_repo_path": "src/main/LinearRegressor.r", "max_stars_repo_name": "AdailCarvalho/R-linear-regression", "max_stars_repo_head_hexsha": "775374b40042f3cc60bdfb7ca41698dd8c8be9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-30T13:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-30T13:18:51.000Z", "max_issues_repo_path": "src/main/LinearRegressor.r", "max_issues_repo_name": "AdailCarvalho/R-linear-regression", "max_issues_repo_head_hexsha": "775374b40042f3cc60bdfb7ca41698dd8c8be9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-06T16:10:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-06T19:05:05.000Z", "max_forks_repo_path": "src/main/LinearRegressor.r", "max_forks_repo_name": "AdailCarvalho/R-linear-regression", "max_forks_repo_head_hexsha": "775374b40042f3cc60bdfb7ca41698dd8c8be9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2557544757, "max_line_length": 137, "alphanum_fraction": 0.6701448479, "num_tokens": 3668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4843579814056898}} {"text": "# have all phylogenies in one file\n# have a file with the chromosome and window for each tree in the correct order\n# have a popmap with the individual names and groupings wished to test\n# have the outgroup labeled once in the popmap as \"outgroup\"\n\nlibrary(ape)\nlibrary(phytools)\n\noptions(scipen=999)\n\n# read in trees, info, and popmap for 50kbp trees\nx_trees <- read.tree(\"certhia_50kbp.trees\")\nx_info <- read.table(\"certhia_50kbp_tree_info.txt\", sep=\"\\t\", stringsAsFactors=F)\nx_popmap <- read.table(\"gsi_popmap.txt\", sep=\"\\t\", stringsAsFactors=F)\nx_output <- \"b_gsi_50kbp_output.txt\"\n\n# define outgroup\noutgroup <- x_popmap[x_popmap[,2] == \"outgroup\", 1]\n\n# remove outgroup from popmap\nx_popmap <- x_popmap[x_popmap[,2] != \"outgroup\", ]\n\n# write initial line of output\nwrite(c(\"chr\", \"start\", \"end\", \"pop\", \"gsi\"), file=x_output, sep=\"\\t\", ncolumns=5)\n\n# loop for each tree\nfor(a in 1:length(x_trees)) {\n\t# select the tree\n\tx <- x_trees[a][[1]]\n\t# reroot\n\tx <- midpoint.root(x)\n\tx <- root(x, outgroup, resolve.root=T)\n\t\n\t# define the groups\n\tgroups <- unique(x_popmap[,2])\n\t\n\t# loop for each group of interest\n\tfor(g in 1:length(groups)) {\n\t\t# define the group of interest\n\t\tgroup_of_interest <- x_popmap[x_popmap[,2] == groups[g],1]\n\t\t\n\t\t# calculate MRCA of group of interest\n\t\tgroup_mrca <- getMRCA(x, tip = group_of_interest)\n\t\t\n\t\t# calculate number of ndoes to reach common ancestor for each individual in group\n\t\t# and then remove redundant nodes\n\t\tnodes_needed <- c()\n\t\tfor(b in 1:length(group_of_interest)) {\n\t\t\t# what is the number of this individual?\n\t\t\tb_number <- match(group_of_interest[b], x$tip.label)\n\t\t\t\t\n\t\t\t# loop throup edge table until reaching MRCA\n\t\t\twhile_loop <- 0\n\t\t\twhile(while_loop != group_mrca) {\n\t\t\t\t# add node\n\t\t\t\tnodes_needed <- c(nodes_needed, x$edge[x$edge[,2]==b_number,1])\n\t\t\n\t\t\t\t# change new number to that node and update the while_loop object to the node\n\t\t\t\tb_number <- x$edge[x$edge[,2]==b_number,1]\n\t\t\t\twhile_loop <- b_number\n\t\t\t}\n\t\t\t# add the MRCA to the nodes_needed object\n\t\t\tnodes_needed <- c(nodes_needed, group_mrca)\n\t\n\t\t\t# only keep unique nodes\n\t\t\tnodes_needed <- unique(nodes_needed)\n\t\t}\n\n\t\t# calculate gsi\n\n\t\t# gs \n\t\tgs <- (length(group_of_interest) - 1) / length(nodes_needed)\n\n\t\t# max gs = 1\n\t\tmax_gs <- 1\n\n\t\t# min gs = minimum number of nodes to connect all individuals (n - 1) / total number of nodes\n\t\tmin_gs <- (length(group_of_interest) - 1) / length(unique(x$edge[,1]))\n\n\t\t# equation 4 of Cummings et al. 2008 (GSI paper)\n\t\tgsi <- (gs - min_gs) / (max_gs - min_gs)\n\n\t\t# write output\n\t\twrite(c(x_info[a,1], x_info[a,2], x_info[a,3], groups[g], gsi), file=x_output, sep=\"\\t\", ncolumns=5, append=T)\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n# read in trees, info, and popmap for 100kbp trees\nx_trees <- read.tree(\"certhia_100kbp.trees\")\nx_info <- read.table(\"certhia_100kbp_tree_info.txt\", sep=\"\\t\", stringsAsFactors=F)\nx_popmap <- read.table(\"gsi_popmap.txt\", sep=\"\\t\", stringsAsFactors=F)\nx_output <- \"b_gsi_100kbp_output.txt\"\n\n# define outgroup\noutgroup <- x_popmap[x_popmap[,2] == \"outgroup\", 1]\n\n# remove outgroup from popmap\nx_popmap <- x_popmap[x_popmap[,2] != \"outgroup\", ]\n\n# write initial line of output\nwrite(c(\"chr\", \"start\", \"end\", \"pop\", \"gsi\"), file=x_output, sep=\"\\t\", ncolumns=5)\n\n# loop for each tree\nfor(a in 1:length(x_trees)) {\n\t# select the tree\n\tx <- x_trees[a][[1]]\n\t# reroot\n\tx <- midpoint.root(x)\n\tx <- root(x, outgroup, resolve.root=T)\n\t\n\t# define the groups\n\tgroups <- unique(x_popmap[,2])\n\t\n\t# loop for each group of interest\n\tfor(g in 1:length(groups)) {\n\t\t# define the group of interest\n\t\tgroup_of_interest <- x_popmap[x_popmap[,2] == groups[g],1]\n\t\t\n\t\t# calculate MRCA of group of interest\n\t\tgroup_mrca <- getMRCA(x, tip = group_of_interest)\n\t\t\n\t\t# calculate number of ndoes to reach common ancestor for each individual in group\n\t\t# and then remove redundant nodes\n\t\tnodes_needed <- c()\n\t\tfor(b in 1:length(group_of_interest)) {\n\t\t\t# what is the number of this individual?\n\t\t\tb_number <- match(group_of_interest[b], x$tip.label)\n\t\t\t\t\n\t\t\t# loop throup edge table until reaching MRCA\n\t\t\twhile_loop <- 0\n\t\t\twhile(while_loop != group_mrca) {\n\t\t\t\t# add node\n\t\t\t\tnodes_needed <- c(nodes_needed, x$edge[x$edge[,2]==b_number,1])\n\t\t\n\t\t\t\t# change new number to that node and update the while_loop object to the node\n\t\t\t\tb_number <- x$edge[x$edge[,2]==b_number,1]\n\t\t\t\twhile_loop <- b_number\n\t\t\t}\n\t\t\t# add the MRCA to the nodes_needed object\n\t\t\tnodes_needed <- c(nodes_needed, group_mrca)\n\t\n\t\t\t# only keep unique nodes\n\t\t\tnodes_needed <- unique(nodes_needed)\n\t\t}\n\n\t\t# calculate gsi\n\n\t\t# gs \n\t\tgs <- (length(group_of_interest) - 1) / length(nodes_needed)\n\n\t\t# max gs = 1\n\t\tmax_gs <- 1\n\n\t\t# min gs = minimum number of nodes to connect all individuals (n - 1) / total number of nodes\n\t\tmin_gs <- (length(group_of_interest) - 1) / length(unique(x$edge[,1]))\n\n\t\t# equation 4 of Cummings et al. 2008 (GSI paper)\n\t\tgsi <- (gs - min_gs) / (max_gs - min_gs)\n\n\t\t# write output\n\t\twrite(c(x_info[a,1], x_info[a,2], x_info[a,3], groups[g], gsi), file=x_output, sep=\"\\t\", ncolumns=5, append=T)\n\t}\n}\n", "meta": {"hexsha": "cc6704ea0a28cf05bddcc1176ce25f00e4487c5c", "size": 5037, "ext": "r", "lang": "R", "max_stars_repo_path": "08e_gsi.r", "max_stars_repo_name": "jdmanthey/certhia_phylogeography", "max_stars_repo_head_hexsha": "7830f496419252149f5e4f1a657ce19c80ec05da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "08e_gsi.r", "max_issues_repo_name": "jdmanthey/certhia_phylogeography", "max_issues_repo_head_hexsha": "7830f496419252149f5e4f1a657ce19c80ec05da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08e_gsi.r", "max_forks_repo_name": "jdmanthey/certhia_phylogeography", "max_forks_repo_head_hexsha": "7830f496419252149f5e4f1a657ce19c80ec05da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T17:45:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T17:45:18.000Z", "avg_line_length": 29.1156069364, "max_line_length": 112, "alphanum_fraction": 0.6799682351, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.48434720970779294}} {"text": "\\name{joint_estimate}\n\\alias{joint_estimate}\n%- Also NEED an '\\alias' for EACH other topic documented here.\n\\title{\n Joint inference of attachment function and node fitnesses \n}\n\\description{\n This function jointly estimates the attachment function \\eqn{A_k} and node fitnesses \\eqn{\\eta_i}. It first performs a cross-validation to select the optimal parameters \\eqn{r} and \\eqn{s}, then estimates \\eqn{A_k} and \\eqn{eta_i} using that optimal pair with the full data (Ref. 2).\n}\n\\usage{\njoint_estimate(net_object , \n net_stat = get_statistics(net_object), \n p = 0.75 ,\n stop_cond = 10^-8 ,\n mode_reg_A = 0 , \n ...)\n}\n%- maybe also 'usage' for other objects documented here.\n\\arguments{\n \\item{net_object}{\n an object of class \\code{PAFit_net} that contains the network.\n }\n \\item{net_stat}{\n An object of class \\code{PAFit_data} which contains summarized statistics needed in estimation. This object is created by the function \\code{\\link{get_statistics}}. The default value is \\code{get_statistics(net_object)}.\n }\n\\item{p}{Numeric. This is the ratio of the number of new edges in the learning data to that of the full data. The data is then divided into two parts: learning data and testing data based on \\code{p}. The learning data is used to learn the node fitnesses and the testing data is then used in cross-validation. Default value is \\code{0.75}.} \n\\item{stop_cond}{Numeric. The iterative algorithm stops when \\eqn{abs(h(ii) - h(ii + 1)) / (abs(h(ii)) + 1) < stop.cond} where \\eqn{h(ii)} is the value of the objective function at iteration \\eqn{ii}. We recommend to choose \\code{stop.cond} at most equal to \\eqn{10^(- number of digits of h - 2)}, in order to ensure that when the algorithm stops, the increase in posterior probability is less than 1\\% of the current posterior probability. Default is \\code{10^-8}. This threshold is good enough for most applications.}\n\n\\item{mode_reg_A}{Binary. Indicates which regularization term is used for \\eqn{A_k}:\n\\itemize{\n\\item \\code{0}: This is the regularization term used in Ref. 1 and 2. Please refer to Eq. (4) in the tutorial for the definition of the term. It approximately enforces the power-law form \\eqn{A_k = k^\\alpha}. This is the default value. \n\\item \\code{1}: Unlike the default, this regularization term exactly enforces the functional form \\eqn{A_k = k^\\alpha}. Please refer to Eq. (6) in the tutorial for the definition of the term. Its main drawback is it is significantly slower to converge, while its gain over the default one is marginal in most cases. \n}\n}\n \\item{\\dots}{\n %% ~~Describe \\code{\\dots} here~~\n }\n}\n\n\\value{\n Outputs a \\code{Full_PAFit_result} object, which is a list containing the following fields:\n \\itemize{\n \\item \\code{cv_data}: a \\code{CV_Data} object which contains the cross-validation data. This is the testing data.\n \n \\item \\code{cv_result}: a \\code{CV_Result} object which contains the cross-validation result. Normally the user does not need to pay attention to this data.\n \n \\item \\code{estimate_result}: this is a \\code{PAFit_result} object which contains the estimated attachment function \\eqn{A_k}, the estimated fitnesses \\eqn{\\eta_i} and their confidence intervals. In particular, the important fields are: \n \\itemize{\n \\item \\code{ratio}: this is the selected value for the hyper-parameter \\eqn{r}.\n \\item \\code{shape}: this is the selected value for the hyper-parameter \\eqn{s}.\n \\item \\code{k} and \\code{A}: a degree vector and the estimated PA function.\n \\item \\code{var_A}: the estimated variance of \\eqn{A}.\n \\item \\code{var_logA}: the estimated variance of \\eqn{log A}.\n \\item \\code{upper_A}: the upper value of the interval of two standard deviations around \\eqn{A}.\n \\item \\code{lower_A}: the lower value of the interval of two standard deviations around \\eqn{A}.\n \n \\item \\code{center_k} and \\code{theta}: when we perform binning, these are the centers of the bins and the estimated PA values for those bins. \\code{theta} is similar to \\code{A} but with duplicated values removed.\n \\item \\code{var_bin}: the variance of \\code{theta}. Same as \\code{var_A} but with duplicated values removed.\n \\item \\code{upper_bin}: the upper value of the interval of two standard deviations around \\code{theta}. Same as \\code{upper_A} but with duplicated values removed.\n \\item \\code{lower_bin}: the lower value of the interval of two standard deviations around \\code{theta}. Same as \\code{lower_A} but with duplicated values removed.\n \\item \\code{g}: the number of bins used.\n \\item \\code{alpha} and \\code{ci}: \\code{alpha} is the estimated attachment exponent \\eqn{\\alpha} (when assume \\eqn{A_k = k^\\alpha}), while \\code{ci} is the confidence interval.\n \\item \\code{loglinear_fit}: this is the fitting result when we estimate \\eqn{\\alpha}. \n \\item \\code{f}: the estimated node fitnesses.\n \\item \\code{var_f}: the estimated variance of \\eqn{\\eta_i}.\n \\item \\code{upper_f}: the estimated upper value of the interval of two standard deviations around \\eqn{\\eta_i}.\n \\item \\code{lower_f}: the estimated lower value of the interval of two standard deviations around \\eqn{\\eta_i}.\n \\item \\code{objective_value}: values of the objective function over iterations in the final run with the full data.\n \\item \\code{diverge_zero}: logical value indicates whether the algorithm diverged in the final run with the full data.\n}\n\\item \\code{contribution}: a list containing an estimate of the contributions of preferential attachment and fitness mechanisms in the growth process of the network. The calculation adapts a quantification method proposed in Section 3 of Ref. 4, which is for preferential attachment and transitivity, to preferential attachment and fitness.\n\\itemize{\n\\item \\code{PA_contribution}: an array containing the contributions of preferential attachment at each time-step \n\\item \\code{fit_contribution}: an array containing the contributions of the fitness mechanism at each time-step \n\\item \\code{mean_PA_contrib}: the average contribution of preferential attachment through the whole growth process\n\\item \\code{mean_fit_contrib}: the average contribution of the fitness mechanism through the whole growth process}\n}\n}\n\\author{\n Thong Pham \\email{thongphamthe@gmail.com}\n}\n\\references{\n 1. Pham, T., Sheridan, P. & Shimodaira, H. (2015). PAFit: A Statistical Method for Measuring Preferential Attachment in Temporal Complex Networks. PLoS ONE 10(9): e0137796. (\\doi{10.1371/journal.pone.0137796}).\n \n 2. Pham, T., Sheridan, P. & Shimodaira, H. (2016). Joint Estimation of Preferential Attachment and Node Fitness in Growing Complex Networks. Scientific Reports 6, Article number: 32558. (\\doi{10.1038/srep32558}).\n \n 3. Pham, T., Sheridan, P. & Shimodaira, H. (2020). PAFit: An R Package for the Non-Parametric Estimation of Preferential Attachment and Node Fitness in Temporal Complex Networks. Journal of Statistical Software 92 (3). (\\doi{10.18637/jss.v092.i03}).\n\n4. Inoue, M., Pham, T. & Shimodaira, H. (2020). Joint Estimation of Non-parametric Transitivity and Preferential Attachment Functions in Scientific Co-authorship Networks. Journal of Informetrics 14(3). (\\doi{10.1016/j.joi.2020.101042}).\n}\n\\seealso{\n See \\code{\\link{get_statistics}} for how to create summarized statistics needed in this function.\n \n See \\code{\\link{Jeong}}, \\code{\\link{Newman}} and \\code{\\link{only_A_estimate}} for functions to estimate the attachment function in isolation.\n \n See \\code{\\link{only_F_estimate}} for a function to estimate node fitnesses in isolation.\n}\n\n\\examples{\n\\dontrun{\n \n library(\"PAFit\")\n #### Example 1: a linear preferential attachment kernel, i.e., A_k = k ############\n set.seed(1)\n # size of initial network = 100\n # number of new nodes at each time-step = 100\n # Ak = k; inverse variance of the distribution of node fitnesse = 5\n net <- generate_BB(N = 1000 , m = 50 , \n num_seed = 100 , multiple_node = 100,\n s = 5)\n net_stats <- get_statistics(net)\n \n # Joint estimation of attachment function Ak and node fitness\n result <- joint_estimate(net, net_stats)\n \n summary(result)\n \n # plot the estimated attachment function\n true_A <- pmax(result$estimate_result$center_k,1) # true function\n plot(result , net_stats, max_A = max(true_A,result$estimate_result$theta))\n lines(result$estimate_result$center_k, true_A, col = \"red\") # true line\n legend(\"topleft\" , legend = \"True function\" , col = \"red\" , lty = 1 , bty = \"n\")\n \n # plot the estimated node fitnesses and true node fitnesses\n plot(result, net_stats, true = net$fitness, plot = \"true_f\")\n \n #############################################################################\n #### Example 2: a non-log-linear preferential attachment kernel ############\n set.seed(1)\n # size of initial network = 100\n # number of new nodes at each time-step = 100\n # A_k = alpha* log (max(k,1))^beta + 1, with alpha = 2, and beta = 2\n # inverse variance of the distribution of node fitnesse = 10\n net <- generate_net(N = 1000 , m = 50 , \n num_seed = 100 , multiple_node = 100,\n s = 10 , mode = 3, alpha = 2, beta = 2)\n net_stats <- get_statistics(net)\n \n # Joint estimation of attachment function Ak and node fitness\n result <- joint_estimate(net, net_stats)\n \n summary(result)\n \n # plot the estimated attachment function\n true_A <- 2 * log(pmax(result$estimate_result$center_k,1))^2 + 1 # true function\n plot(result , net_stats, max_A = max(true_A,result$estimate_result$theta))\n lines(result$estimate_result$center_k, true_A, col = \"red\") # true line\n legend(\"topleft\" , legend = \"True function\" , col = \"red\" , lty = 1 , bty = \"n\")\n \n # plot the estimated node fitnesses and true node fitnesses\n plot(result, net_stats, true = net$fitness, plot = \"true_f\")\n #############################################################################\n #### Example 3: another non-log-linear preferential attachment kernel ############\n set.seed(1)\n # size of initial network = 100\n # number of new nodes at each time-step = 100\n # A_k = min(max(k,1),sat_at)^alpha, with alpha = 1, and sat_at = 100\n # inverse variance of the distribution of node fitnesse = 10\n net <- generate_net(N = 1000 , m = 50 , \n num_seed = 100 , multiple_node = 100,\n s = 10 , mode = 2, alpha = 1, sat_at = 100)\n net_stats <- get_statistics(net)\n \n # Joint estimation of attachment function Ak and node fitness\n result <- joint_estimate(net, net_stats)\n \n summary(result)\n \n # plot the estimated attachment function\n true_A <- pmin(pmax(result$estimate_result$center_k,1),100)^1 # true function\n plot(result , net_stats, max_A = max(true_A,result$estimate_result$theta))\n lines(result$estimate_result$center_k, true_A, col = \"red\") # true line\n legend(\"topleft\" , legend = \"True function\" , col = \"red\" , lty = 1 , bty = \"n\")\n \n # plot the estimated node fitnesses and true node fitnesses\n plot(result, net_stats, true = net$fitness, plot = \"true_f\")\n }\n}\n\n\\concept{preferential attachment}\n\\concept{attachment function}\n\\concept{fitness}\n\n", "meta": {"hexsha": "56422c1e53745beb7fa4037500c0a2eff95b1ce3", "size": 11538, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/joint_estimate.rd", "max_stars_repo_name": "thongphamthe/PAFit", "max_stars_repo_head_hexsha": "e1c3b32e0f886eb0b90a8bcbed0c3719bd28ef44", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-08-22T14:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T18:38:48.000Z", "max_issues_repo_path": "man/joint_estimate.rd", "max_issues_repo_name": "thongphamthe/PAFit", "max_issues_repo_head_hexsha": "e1c3b32e0f886eb0b90a8bcbed0c3719bd28ef44", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T01:01:52.000Z", "max_forks_repo_path": "man/joint_estimate.rd", "max_forks_repo_name": "thongphamthe/PAFit", "max_forks_repo_head_hexsha": "e1c3b32e0f886eb0b90a8bcbed0c3719bd28ef44", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-12T04:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T12:09:33.000Z", "avg_line_length": 62.7065217391, "max_line_length": 519, "alphanum_fraction": 0.6859074363, "num_tokens": 2979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.4843471936755471}} {"text": "## Replication Code for\n# A. Abadie, A. Diamond, and J. Hainmueller. 2014.\n# Comparative Politics and the Synthetic Control Method\n# American Journal of Political Science.\n\nrm(list=ls())\nlibrary(foreign)\nlibrary(\"Synth\")\nlibrary(xtable)\n\n# Load Data \nd <- read.dta(\"repgermany.dta\")\n\n## Table 1 & 2, Figure 1, 2, & 3\n\n## pick v by cross-validation\n# data setup for training model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\", 1971:1980, c(\"mean\")),\n list(\"schooling\",c(1970,1975), c(\"mean\")),\n list(\"invest70\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1971:1980,\n time.optimize.ssr = 1981:1990,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n\n# fit training model\nsynth.out <- \n synth(\n data.prep.obj=dataprep.out,\n Margin.ipop=.005,Sigf.ipop=7,Bound.ipop=6\n )\n\n# data prep for main model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\" ,1981:1990, c(\"mean\")),\n list(\"schooling\",c(1980,1985), c(\"mean\")),\n list(\"invest80\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1981:1990,\n time.optimize.ssr = 1960:1989,\n unit.names.variable = 2,\n time.plot = 1960:2003\n)\n\n# fit main model with v from training model\nsynth.out <- synth(\n data.prep.obj=dataprep.out,\n custom.v=as.numeric(synth.out$solution.v)\n )\n\n#### Table 2\nsynth.tables <- synth.tab(\n dataprep.res = dataprep.out,\n synth.res = synth.out\n ); synth.tables\n \n# Replace means for OECD sample (computed externally using proper pop weighting)\nsynth.tables$tab.pred[,3] <- c(8021.1,31.9,7.4,34.2,44.1,25.9)\ncolnames(synth.tables$tab.pred)[3] <- \"Rest of OECD Sample\"\nrownames(synth.tables$tab.pred) <- c(\"GDP per-capita\",\"Trade openness\",\n \"Inflation rate\",\"Industry share\",\n \"Schooling\",\"Investment rate\")\n\nxtable(round(synth.tables$tab.pred,1),digits=1)\n\n#### Table 1\n# synth weights\ntab1 <- data.frame(synth.tables$tab.w)\ntab1[,1] <- round(tab1[,1],2) \n# regression weights\nX0 <- cbind(1,t(dataprep.out$X0))\nX1 <- as.matrix(c(1,dataprep.out$X1))\nW <- X0%*%solve(t(X0)%*%X0)%*%X1\nWdat <- data.frame(unit.numbers=as.numeric(rownames(X0)),\n regression.w=round(W,2))\ntab1 <- merge(tab1,Wdat,by=\"unit.numbers\")\ntab1 <- tab1[order(tab1[,3]),]\n\nxtable(cbind(tab1[1:9,c(3,2,4)],\n tab1[10:18,c(3,2,4)]\n )\n )\n\n#### Figure 1: Trends in Per-Capita GDP: West Germany vs. Rest of the OECD Sample\nText.height <- 23000\nCex.set <- .8\n#pdf(file = \"ger_vs_oecd.pdf\", width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\nplot(1960:2003,dataprep.out$Y1plot,\n type=\"l\",ylim=c(0,33000),col=\"black\",lty=\"solid\",\n ylab =\"per-capita GDP (PPP, 2002 USD)\",\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",\n lwd=2\n )\nlines(1960:2003,aggregate(d[,c(\"gdp\")],by=list(d$year),mean,na.rm=T)[,2]\n ,col=\"black\",lty=\"dashed\",lwd=2) # mean 2\nabline(v=1990,lty=\"dotted\")\nlegend(x=\"bottomright\",\n legend=c(\"West Germany\",\"rest of the OECD sample\")\n ,lty=c(\"solid\",\"dashed\"),col=c(\"black\",\"black\")\n ,cex=.8,bg=\"white\",lwd=c(2,2))\narrows(1987,Text.height,1989,Text.height,col=\"black\",length=.1)\ntext(1982.5,Text.height,\"reunification\",cex=Cex.set)\n#dev.off()\n\n#### Figure 2: Trends in Per-Capita GDP: West Germany vs. Synthetic West Germany\n#pdf(file = \"ger_vs_synthger2.pdf\", width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\nsynthY0 <- (dataprep.out$Y0%*%synth.out$solution.w)\nplot(1960:2003,dataprep.out$Y1plot,\n type=\"l\",ylim=c(0,33000),col=\"black\",lty=\"solid\",\n ylab =\"per-capita GDP (PPP, 2002 USD)\",\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",\n lwd=2\n )\nlines(1960:2003,synthY0,col=\"black\",lty=\"dashed\",lwd=2)\nabline(v=1990,lty=\"dotted\")\nlegend(x=\"bottomright\",\n legend=c(\"West Germany\",\"synthetic West Germany\")\n ,lty=c(\"solid\",\"dashed\"),col=c(\"black\",\"black\")\n ,cex=.8,bg=\"white\",lwd=c(2,2))\narrows(1987,Text.height,1989,Text.height,col=\"black\",length=.1)\ntext(1982.5,Text.height,\"reunification\",cex=Cex.set)\n#dev.off()\n\n### Figure 3: Per-Capita GDP Gap Between West Germany and Synthetic West Germany\n#pdf(file = \"ger_vs_synthger_gaps2.pdf\", width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\ngap <- dataprep.out$Y1-(dataprep.out$Y0%*%synth.out$solution.w)\nplot(1960:2003,gap,\n type=\"l\",ylim=c(-4500,4500),col=\"black\",lty=\"solid\",\n ylab =c(\"gap in per-capita GDP (PPP, 2002 USD)\"),\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",\n lwd=2\n )\nabline(v=1990,lty=\"dotted\")\nabline(h=0,lty=\"dotted\")\narrows(1987,1000,1989,1000,col=\"black\",length=.1)\ntext(1982.5,1000,\"reunification\",cex=Cex.set)\n#dev.off()\n\n### Figure 4: Placebo Reunification 1975 - Trends in Per-Capita GDP: West Germany vs. Synthetic West Germany\n\n# data prep for training model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\",1971, c(\"mean\")),\n list(\"schooling\",c(1960,1965), c(\"mean\")),\n list(\"invest60\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1960:1964,\n time.optimize.ssr = 1965:1975,\n unit.names.variable = 2,\n time.plot = 1960:1990\n )\n\n# fit training model\nsynth.out <- synth(\n data.prep.obj=dataprep.out,\n Margin.ipop=.005,Sigf.ipop=7,Bound.ipop=6\n)\n\n\n# data prep for main model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\" ,1971:1975, c(\"mean\")),\n list(\"schooling\",c(1970,1975), c(\"mean\")),\n list(\"invest70\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1965:1975,\n time.optimize.ssr = 1960:1975,\n unit.names.variable = 2,\n time.plot = 1960:1990\n )\n\n# fit main model\nsynth.out <- synth(\n data.prep.obj=dataprep.out,\n custom.v=as.numeric(synth.out$solution.v)\n)\n\nCex.set <- 1\n#pdf(file = \"2intimeplacebo1975.pdf\", width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\nplot(1960:1990,dataprep.out$Y1plot,\n type=\"l\",ylim=c(0,33000),col=\"black\",lty=\"solid\",\n ylab =\"per-capita GDP (PPP, 2002 USD)\",\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",\n lwd=2\n )\nlines(1960:1990,(dataprep.out$Y0%*%synth.out$solution.w),col=\"black\",lty=\"dashed\",lwd=2)\nabline(v=1975,lty=\"dotted\")\nlegend(x=\"bottomright\",\n legend=c(\"West Germany\",\"synthetic West Germany\")\n ,lty=c(\"solid\",\"dashed\"),col=c(\"black\",\"black\")\n ,cex=.8,bg=\"white\",lwd=c(2,2))\narrows(1973,20000,1974.5,20000,col=\"black\",length=.1)\ntext(1967.5,20000,\"placebo reunification\",cex=Cex.set)\n#dev.off()\n\n\n### Figure 5: Ratio of post-reunification RMSPE to pre-reunification RMSPE: West Germany and control countries.\n\n# loop across control units\nstoregaps <- \n matrix(NA,\n length(1960:2003),\n length(unique(d$index))-1\n )\nrownames(storegaps) <- 1960:2003\ni <- 1\nco <- unique(d$index)\n\nfor(k in unique(d$index)[-7]){\n \n # data prep for training model\n dataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\",1971:1980, c(\"mean\")),\n list(\"schooling\" ,c(1970,1975), c(\"mean\")),\n list(\"invest70\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = k,\n controls.identifier = co[-which(co==k)],\n time.predictors.prior = 1971:1980,\n time.optimize.ssr = 1981:1990,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n\n # fit training model\n synth.out <-\n synth(\n data.prep.obj=dataprep.out,\n Margin.ipop=.005,Sigf.ipop=7,Bound.ipop=6\n )\n\n # data prep for main model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\" ,1981:1990, c(\"mean\")),\n list(\"schooling\",c(1980,1985), c(\"mean\")),\n list(\"invest80\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = k,\n controls.identifier = co[-which(co==k)],\n time.predictors.prior = 1981:1990,\n time.optimize.ssr = 1960:1989,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n\n# fit main model\nsynth.out <- synth(\n data.prep.obj=dataprep.out,\n custom.v=as.numeric(synth.out$solution.v)\n )\n\n storegaps[,i] <- \n dataprep.out$Y1-\n (dataprep.out$Y0%*%synth.out$solution.w)\n i <- i + 1\n} # close loop over control units\nd <- d[order(d$index,d$year),]\ncolnames(storegaps) <- unique(d$country)[-7]\nstoregaps <- cbind(gap,storegaps)\ncolnames(storegaps)[1] <- c(\"West Germany\")\n\n# compute ratio of post-reunification RMSPE \n# to pre-reunification RMSPE \nrmse <- function(x){sqrt(mean(x^2))}\npreloss <- apply(storegaps[1:30,],2,rmse)\npostloss <- apply(storegaps[31:44,],2,rmse)\n\n#pdf(\"2ratio_post_to_preperiod_rmse2a.pdf\")\ndotchart(sort(postloss/preloss),\n xlab=\"Post-Period RMSE / Pre-Period RMSE\",\n pch=19)\n#dev.off()\n\n### Figure 6: Leave-one-out distribution of the synthetic control for West Germany\n\n# loop over leave one outs\nstoregaps <- \n matrix(NA,\n length(1960:2003),\n 5)\ncolnames(storegaps) <- c(1,3,9,12,14)\nco <- unique(d$index)[-7]\n\nfor(k in 1:5){\n\n# data prep for training model\nomit <- c(1,3,9,12,14)[k] \n dataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\",1971:1980, c(\"mean\")),\n list(\"schooling\" ,c(1970,1975), c(\"mean\")),\n list(\"invest70\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = co[-which(co==omit)],\n time.predictors.prior = 1971:1980,\n time.optimize.ssr = 1981:1990,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n \n # fit training model\n synth.out <- synth(\n data.prep.obj=dataprep.out,\n Margin.ipop=.005,Sigf.ipop=7,Bound.ipop=6\n )\n \n# data prep for main model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\" ,1981:1990, c(\"mean\")),\n list(\"schooling\",c(1980,1985), c(\"mean\")),\n list(\"invest80\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = co[-which(co==omit)],\n time.predictors.prior = 1981:1990,\n time.optimize.ssr = 1960:1989,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n \n # fit main model \n synth.out <- synth(\n data.prep.obj=dataprep.out,\n custom.v=as.numeric(synth.out$solution.v)\n )\n storegaps[,k] <- (dataprep.out$Y0%*%synth.out$solution.w)\n} # close loop over leave one outs\n\nText.height <- 23000\nCex.set <- .8\n#pdf(file = \"1jackknife2.pdf\", width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\nplot(1960:2003,dataprep.out$Y1plot,\n type=\"l\",ylim=c(0,33000),col=\"black\",lty=\"solid\",\n ylab =\"per-capita GDP (PPP, 2002 USD)\",\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",lwd=2\n )\n\nabline(v=1990,lty=\"dotted\")\narrows(1987,23000,1989,23000,col=\"black\",length=.1)\n for(i in 1:5){\n lines(1960:2003,storegaps[,i],col=\"darkgrey\",lty=\"solid\")\n }\nlines(1960:2003,synthY0,col=\"black\",lty=\"dashed\",lwd=2)\nlines(1960:2003,dataprep.out$Y1plot,col=\"black\",lty=\"solid\",lwd=2)\ntext(1982.5,23000,\"reunification\",cex=.8)\nlegend(x=\"bottomright\",\n legend=c(\"West Germany\",\n \"synthetic West Germany\",\n \"synthetic West Germany (leave-one-out)\")\n ,lty=c(\"solid\",\"dashed\",\"solid\"),\n col=c(\"black\",\"black\",\"darkgrey\")\n ,cex=.8,bg=\"white\",lwdc(2,2,1))\n#dev.off()\n\n\n### Table 3: Synthetic Weights from Combinations of Control Countries\nrm(list=ls())\nlibrary(gtools)\nlibrary(kernlab)\n\n# data prep for training model\nd <- read.dta(\"repgermany.dta\")\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\", 1971:1980, c(\"mean\")),\n list(\"schooling\",c(1970,1975), c(\"mean\")),\n list(\"invest70\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1971:1980,\n time.optimize.ssr = 1981:1990,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n\n# fit training model\nsynth.out <- \n synth(\n data.prep.obj=dataprep.out,\n Margin.ipop=.005,Sigf.ipop=7,Bound.ipop=6\n )\n\n# data prep for main model\ndataprep.out <-\n dataprep(\n foo = d,\n predictors = c(\"gdp\",\"trade\",\"infrate\"),\n dependent = \"gdp\",\n unit.variable = 1,\n time.variable = 3,\n special.predictors = list(\n list(\"industry\" ,1981:1990, c(\"mean\")),\n list(\"schooling\",c(1980,1985), c(\"mean\")),\n list(\"invest80\" ,1980, c(\"mean\"))\n ),\n treatment.identifier = 7,\n controls.identifier = unique(d$index)[-7],\n time.predictors.prior = 1981:1990,\n time.optimize.ssr = 1960:1989,\n unit.names.variable = 2,\n time.plot = 1960:2003\n )\n\n# fit main model with v from training model\nsynth.out <- synth(\n data.prep.obj=dataprep.out,\n custom.v=as.numeric(synth.out$solution.v)\n)\n\nsynth.tables <- synth.tab(\n dataprep.res = dataprep.out,\n synth.res = synth.out\n)\n\ntable3 <- list()\nsynth.tables$tab.w[,1] <- round(synth.tables$tab.w[,1],2)\ntable3[[5]] <-synth.tables$tab.w[order(-1*synth.tables$tab.w[,1]),2:1][1:5,]\n\n# compute loss for all combinations \n# of 4, 3, 2, 1 sized donor pools\n\n# get W and v\nsolution.w <- round(synth.out$solution.w,3)\nV <- diag(as.numeric(synth.out$solution.v))\n\n# compute scaled Xs\nnvarsV <- dim(dataprep.out$X0)[1]\nbig.dataframe <- cbind(dataprep.out$X0, dataprep.out$X1)\ndivisor <- sqrt(apply(big.dataframe, 1, var))\nscaled.matrix <-\n t(t(big.dataframe) %*% ( 1/(divisor) *\n diag(rep(dim(big.dataframe)[1], 1)) ))\nX0.scaled <- scaled.matrix[,c(1:(dim(dataprep.out$X0)[2]))]\nX1.scaled <- as.matrix(scaled.matrix[,dim(scaled.matrix)[2]])\n\ndn <- d[d$year==1970,c(\"country\",\"index\")]\ndn <- dn[order(dn$index),]\ndn <- dn[-7,]\n\ntable2store <- matrix(NA,nrow(dataprep.out$X1),4)\nfig7store <- matrix(NA,length(1960:2003),4) \n\n# loop through number of controls\nfor(pp in 4:1){\n store <- combinations(length(unique(d$index)[-7]),\n r=pp, v=unique(d$index)[-7])\n store.loss <- matrix(NA,nrow=nrow(store),1)\n store.w <- matrix(NA,nrow=nrow(store),pp)\n store.c <- store.w\n\n# loop through combinations \n for(k in 1:nrow(store)){\n # index positions of control units\n posvector <- c()\n for(i in 1:pp){\n posvector <- c(posvector,which(dn$index==store[k,i]))\n }\n \n # run quad optimization \n X0temp <- X0.scaled[ , posvector ]\n H <- t(X0temp) %*% V %*% (X0temp)\n c <- -1*c(t(X1.scaled) %*% V %*% (X0temp) )\n\n if(pp == 1){\n solution.w <- matrix(1)\n } else { \n res <- ipop(c = c, H = H, A = t(rep(1, length(c))),\n b = 1, l = rep(0, length(c)),\n u = rep(1, length(c)), r = 0,\n margin = 0.005,sigf = 7, bound = 6)\n solution.w <- as.matrix(primal(res))\n }\n loss.w <- t(X1.scaled - X0temp %*% solution.w) %*% V %*% (X1.scaled - X0temp %*% solution.w)\n \n store.loss[k] <- loss.w\n store.w[k,] <- t(solution.w)\n store.c[k,] <- dn$country[posvector]\n } # close loop over combinations\n \n# get best fitting combination\n dat <- data.frame(store.loss,\n store,\n store.c,\n store.w\n )\n colnames(dat) <- c(\"loss\",\n paste(\"CNo\",1:pp,sep=\"\"),\n paste(\"CNa\",1:pp,sep=\"\"),\n paste(\"W\",1:pp,sep=\"\")\n )\n dat <- dat[order(dat$loss),]\n Countries <- dat[1,paste(\"CNo\",1:pp,sep=\"\")]\n Cweights <- as.numeric(dat[1,paste(\"W\",1:pp,sep=\"\")])\n \n outdat <- data.frame(unit.names=as.vector(\n (t(as.vector(dat[1,paste(\"CNa\",1:pp,sep=\"\")])))),\n w.weights=round(Cweights,2))\n\ntable3[[pp]]<- outdat[order(-1*outdat$w.weights),]\n \n # get posvector for fitting\n posvector <- c()\n if(pp == 1 ){\n posvector <- c(posvector,which(dn$index==Countries))\n } else {\n for(i in 1:pp){\n posvector <- c(posvector,which(dn$index==Countries[1,i]))\n }\n }\n \n X0t <- as.matrix(dataprep.out$X0[,posvector])%*% as.matrix(Cweights)\n table2store[,(4:1)[pp]] <- X0t\n\n fig7store[,(4:1)[pp]] <- \n dataprep.out$Y0[,posvector]%*%as.matrix(Cweights)\n\n} # close loop over number of countries\n\n# Table 3\ntable3\n\n# Table 4\nsynth.tables$tab.pred[,3] <- c(8021.1,31.9,7.4,34.2,44.1,25.9)\ntable4 <- round(\n cbind(synth.tables$tab.pred[,1:2],\n table2store,\n synth.tables$tab.pred[,3]),1)\nrownames(table4) <- c(\"GDP per-capita\",\"Trade openness\",\n \"Inflation rate\",\"Industry share\",\n \"Schooling\",\"Investment rate\")\ncolnames(table4)[2:7] <- c(5:1,\"OECD Sample\")\ntable4\n\n## Figure 7: Per-Capita GDP Gaps Between West Germany and Sparse Synthetic Controls\nText.height <- 23000\nCex.set <- .8\n\npar(mfrow=c(2,2)) \nfor(pp in 4:1){\n#pdf(file = paste(\"2ger_vs_synth\",\"CValt\",pp,\".pdf\",sep=\"\"), width = 5.5, height = 5.5, family = \"Times\",pointsize = 12)\n plot(1960:2003,dataprep.out$Y1,\n type=\"l\",ylim=c(0,33000),col=\"black\",lty=\"solid\",\n ylab =\"per-capita GDP (PPP, 2002 USD)\",\n xlab =\"year\",\n xaxs = \"i\", yaxs = \"i\",\n lwd=2,\n main=paste(\"No. of control countries: \",pp,sep=\"\")\n )\n lines(1960:2003,fig7store[,c(4:1)[pp]],col=\"black\",lty=\"dashed\",lwd=2)\n abline(v=1990,lty=\"dotted\")\n legend(x=\"bottomright\",\n legend=c(\"West Germany\",\"synthetic West Germany\")\n ,lty=c(\"solid\",\"dashed\"),col=c(\"black\",\"black\")\n ,cex=.8,bg=\"white\",lwd=c(2,2))\n arrows(1987,Text.height,1989,Text.height,col=\"black\",length=.1)\n text(1982.5,Text.height,\"reunification\",cex=Cex.set)\n #dev.off()\n}\n\n\n\n", "meta": {"hexsha": "f1b77a1dd2659fba3633241497bca39a3a327a5f", "size": 19138, "ext": "r", "lang": "R", "max_stars_repo_path": "R/2020-07/rep_original.r", "max_stars_repo_name": "datenzauberai/btsa", "max_stars_repo_head_hexsha": "81dc8ffc8283672f9c047b8454f6ffe7d75fd49c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2020-06-02T17:20:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:07:10.000Z", "max_issues_repo_path": "R/2020-07/rep_original.r", "max_issues_repo_name": "datenzauberai/btsa", "max_issues_repo_head_hexsha": "81dc8ffc8283672f9c047b8454f6ffe7d75fd49c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:41:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-07T13:39:55.000Z", "max_forks_repo_path": "R/2020-07/rep_original.r", "max_forks_repo_name": "datenzauberai/btsa", "max_forks_repo_head_hexsha": "81dc8ffc8283672f9c047b8454f6ffe7d75fd49c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-06-02T19:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:47:39.000Z", "avg_line_length": 29.856474259, "max_line_length": 120, "alphanum_fraction": 0.5955167729, "num_tokens": 6305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4836256079433935}} {"text": ".II \"bc^tutorial\"\n.ds TL \"bc Desk Calculator\"\n.NH \"bc Desk Calculator Language\" 1\n.PP\nThis tutorial introduces\n.BR bc ,\nthe calculator language for \\*(OS.\nIf you have not used\n.B bc\nbefore, this tutorial will introduce you to its\nfeatures and functions.\nIf you are familiar with\n.BR bc ,\nyou can use it as a reference.\n.PP\n\\fBbc\\fR is a language that can calculate\nto high precision.\nIt automatically adjusts\nthe number of digits in a number to represent it correctly.\nIt is like having a powerful calculator at your fingertips.\n.Sh \"Entry and Exit\"\n.PP\nThe \\fBbc\\fR calculator for \\*(OS is easy to use.\nWhenever you wish to invoke\n.B bc ,\nall you do is type its name (\\fBbc\\fR), followed by\na stroke of the carriage return key.\nWhen you are finished using the calculator and wish to exit,\njust type the word \\*(Qlquit\\*(Qr or\n.if \\nX=0 \\fB\\fR.\n.if \\nX=1 \\fB\\fR.\n.B bc\nexits and returns control to \\*(OS.\n.Sh \"Example of Simple Use\"\n.PP\n\\fBbc\\fR performs calculations on formulas that you type into it.\nThe formulas are laid out as you would naturally write them.\nFor example, to invoke \\fBbc\\fR, have it add \n2+2, and then exit, type:\n.DM\n\tbc\n\t2 + 2\n.DE\n.B bc\nreplies:\n.DM\n\t4\n.DE\nThen, leave \\fBbc\\fR by typing:\n.DM\n\tquit\n.DE\n.B bc\nis an arbitrary precision calculator:\nthe number of digits carried by \\fBbc\\fR depends upon \nthe requirements of the calculation,\nand is automatically expanded by \\fBbc\\fR.\nThus, \\fBbc\\fR will never overflow.\nThe number of digits it carries is \nlimited only by the amount of available computer memory.\nFor example, invoke\n.B bc\nand then try this calculation:\n.DM\n\t2^500\n.DE\nThe circumflex \\*(Ql^\\*(Qr character signifies a superscript; thus,\nwe are asking \\fBbc\\fR to raise 2 to the 500th power.\nAfter a moment, \\fBbc\\fR will reply:\n.DM\n\t327339060789614187001318969682759915221664\\e\n\t204604306478948329136809613379640467455488\\e\n\t327009232590415715088668412756007100921725\\e\n\t6545885393053328527589376\n.DE\n.II \"bc^exponentiation operator\"\nYou have probably already noticed one nice thing about this calculator:\nyou don't have to include a print statement as part of your command, because\n.B bc\nautomatically prints the results onto your terminal screen.\nWhen \\fBbc\\fR sees any expression, like \\*(QL2+2\\*(QR or \\*(QL37\\-7\\*(QR,\nit prints the result.\n.PP\n.B bc\nprovides the\ncommon arithmetic operators\nfor add, subtract, multiply, and divide, as\nillustrated by the following commands:\n.DM\n\t7 + 5\n\t7 - 5\n\t7 * 5\n\t7 / 5\n.DE\n.PP\n\\fBbc\\fR also provides the\nremainder operator\n\\*(Ql\\fB%\\fR\\*(Qr.\nTo get a sense of how it works, type:\n.DM\n\t7 % 5\n\t5 % 7\n.DE\nHere, \\fBbc\\fR prints the \\fIremainder\\fR of the first number\ndivided by the second; in the case of the first example,\n\\fBbc\\fR prints 2, and in the second prints 5.\nAs you saw above, \\fBbc\\fR also includes\nthe exponentiation operator \\*(Ql\\fB^\\fR\\*(Qr.\n.PP\nWith \\fBbc\\fR, you can also enter numbers with fractional parts.\nType the following to illustrate:\n.DM\n\t9.999 * 9.999\n.DE\n\\fBbc\\fR replies:\n.DM\n\t99.980\n.DE\nYou can save temporary calculations or repeated constants in\n\\fIvariables\\fR.\nThe following example shows you first how to define variables,\nand second how to use them:\n.DM\n\ta = 1.1\n\tb = 2.2\n\ta\n\tb\n\ta * b\n.DE\nVariable names can be longer than one letter.\n.PP\nThe basic calculations in the above examples show only part of what\n.B bc\ncan do.\nThe following section describes simple statements \\(em the assignment of\nvariables and abbreviations \\(em that allow you to perform\ncomplex calculations easily.\n.SH \"Simple Statements\"\n.PP\nAlthough you can use \\fBbc\\fR as a simple calculator\nfor manipulating numbers, you \ncan take advantage of its greater power by using \\fIvariables\\fR.\nVariables, as noted above, store parts of calculations or constants that \nyou will use repeatedly in calculations.\nVariable names are simply \\*(QLwords\\*(QR that you make up.\nHere are some examples of possible variable names:\n.DM\n\ta\n\tb\n\ttotaltaxesdue\n\tratio\n.DE\nTo use variables, simply give them a value, use\nthem in a calculation in place of a number, or print them out.\n.PP\nTo see how a variable can save you repetitive typing, and protect\nyou from possible errors, invoke \\fBbc\\fR and type the following:\n.DM\n\tx = 9.999\n\tx\n\tx * x\n\tx = x * x\n\tx\n.DE\nThe following gives the example with \\fBbc\\fR's replies \\fIin italics\\^\\fR:\n.DM\n\tx = 9.999\n\tx\n\t\\fI9.999\\fP\n\tx * x\n\t\\fI99.980\\fP\n\tx = x * x\n\tx\n\t\\fI99.980\\fP\n.DE\n.II bc^assignment\n.B bc\ndid not reply to the\nassignment statements \\fBx=9.999\\fR and \\fBx=x*x\\fR.\nHowever, it did print the value of \\fBx\\fR when requested,\nand the results of arithmetic using \\fBx\\fR.\n.PP\nCalculations executed with hand-held calculators,\nwith programming languages like C, or with \\fBbc\\fR\noften use the following formula:\n.DM\n\tx = x + 1\n.DE\nTo decrease the likelihood of error,\n\\fBbc\\fR offers you a shorthand expression for this common phrase:\n.DM\n\tx += 1\n.DE\nWhat it means is, \\*(QLadd one to \\fBx\\fR\\*(QR.\nType the following example into \\fBbc\\fR to see how this expression works:\n.DM\n\tx = 1\n\tx * x\n\tx += 1\n\tx * x\n\tx += 1\n.DE\nLikewise, \\fBbc\\fR provides an abbreviation for:\n.DM\n\tx = x - 2\n.DE\nThe form should now be familiar:\n.DM\n\tx \\(mi= 2\n.DE\nThe number to the right of the \\fB-=\\fR or \\fB+=\\fR operator can be replaced\nwith a variable or even another calculation.\nWhen you type:\n.DM\n\ti = 4\n\tx = 48\n\tx \\(mi= i\n\tx\n.DE\n\\fBbc\\fR replies:\n.DM\n\t44\n.DE\nAlternatively, if you type:\n.DM\n\ti = 4\n\tx = 48\n\tx \\(mi= i * i\n\tx\n.DE\nthen \\fBbc\\fR replies:\n.DM\n\t32\n.DE\nSimilar abbreviations are provided for multiplication,\ndivision, remainder, and exponentiation.\nHere is a summary of this class of operation.\n.DS\n.ta 0.5i 1.5i\n\t\\fIa \\fB+=\\fR 2\tReplace \\fIa\\fR with a plus 2\n\t\\fIb \\fB+= \\fIa\\fR\tReplace \\fIb\\fR with \\fIb\\fR plus \\fIa\\fR\n\t\\fIb \\fB\\(mi=\\fR \\fIa\\fR\tReplace \\fIb\\fR with \\fIb\\fR minus \\fIa\\fR\n\t\\fIc \\fB*= \\fIb\\fR\tReplace \\fIc\\fR with \\fIc\\fR multiplied by \\fIb\\fR\n\t\\fIc \\fB/= \\fIa\\fR\tReplace \\fIc\\fR with \\fIc\\fR divided by \\fIa\\fR\n\t\\fIc \\fB%= \\fIb\\fR\tReplace \\fIc\\fR with remainder of \\fIc\\fR divided by \\fIb\\fR\n\t\\fId \\fB^= \\fI3\\fR\tReplace \\fId\\fR with \\fId\\fR raised to the third power\n.DE\n.B bc\nalso has an operator that increases a variable by one:\n\\*(Ql\\fB++\\fR\\*(Qr.\nWhen you type:\n.DM\n\ta = 1\n\t++a\n.DE\nthen \\fBbc\\fR replies:\n.DM\n\t2\n.DE\nTo use this operator in an expression, combine it\nwith a variable anywhere that a variable would normally be used.\nFor example, entering\n.DM\n\tb = 1\n\ta = 3\n\tb = ++a\n\ta\n\tb\n.DE\nyields:\n.DM\n\t4\n\t4\n.DE\nThe \\*(Ql\\fB++\\fR\\*(Qr operator can also be put after a name.\nThe resulting value in the expression is the value of the\nname \\fIbefore\\fR it is incremented.\nHowever, after the expression is evaluated,\nthe name will have an incremented value.\nThe following example shows the use of \\*(Ql\\fB++\\fR\\*(Qr\nboth before and after a name:\n.DM\n\ta = 1\n\tb = 1\n\ta++\n\t++b\n\ta\n\tb\n.DE\n\\fBbc\\fR replies:\n.DM\n\t1\n\t2\n\t2\n\t2\n.DE\nOperators are used in this manner:\n.DM\n\ta = 1\n\tb = 2\n\tc = a++ + ++b\n.DE\nSimilar to \\*(Ql\\fB++\\fR\\*(Qr is \\*(Ql\\fB\\(mi\\(mi\\fR\\*(Qr.\nIt behaves the same way, except that rather than adding one,\nit subtracts one.\n.SH \"Numbers with Fractions\"\n.PP\nMost of the examples presented earlier use whole numbers (integers).\nHowever, \\fBbc\\fR can use numbers with fractional parts.\nThis section discusses the use of fractional numbers in \\fBbc\\fR and their\nprecision\nunder different operations.\n.Sh \"The Scale of Numbers\"\n.PP\nThe number of digits to the left of the decimal point carried by\n.B bc\ndepends upon the requirements of the calculation.\nIf you calculate a large number, as in:\n.DM\n\t2^500\n.DE\nthe result will contain as many digits as needed to express the product.\n.PP\nThe number of digits to the right of a decimal point is\ncalled the\n.I scale\nof the number.\nScale depends upon the operation that produces the\nnumber of digits, and a variable called\n.B scale\nthat will be described shortly.\n.PP\nTo illustrate simple uses of numbers with fractions, invoke\n.B bc\nand then type:\n.DM\n\ta = .01\n\tb = 0.99\n\ta + b\n.DE\n\\fBbc\\fR replies:\n.DM\n\t1.00\n.DE\n.Sh \"Addition and Subtraction\"\n.PP\n\\fBbc\\fR will dynamically adjust the number of digits in the calculation.\nIt deals similarly with fractional numbers.\nTo the following example\n.DM\n\ta = 0.01\n\tb = 0.001\n\ta + b\n.DE\n\\fBbc\\fR reply:\n.DM\n\t.011\n.DE\nIn addition and subtraction, the scale of the result\nis the \\fIlarger\\fR of the scales of the two numbers involved.\nResults are not truncated in addition or subtraction operations.\n.Sh \"Scale During Multiplication\"\n.PP\nOther arithmetic operations act differently with numbers \nthat contain fractions.\nIn the multiplication of two numbers, the scale of \nthe product will at least equal the larger of the scales of the two numbers.\nFor example, the input:\n.DM\n\t1.1 * 1.11\n.DE\nresults in:\n.DM\n\t1.22\n.DE\n.Sh \"Setting the Scale of Results\"\n.PP\nTo increase the number of fractional digits for higher accuracy,\n.B bc\nprovides the built-in variable \\fBscale\\fR.\nThe following example illustrates the \\fBscale\\fR variable:\n.DM\n\tscale = 3\n\t1.1 * 1.11\n.DE\nThe result from this example is:\n.DM\n\t1.221\n.DE\nNote, however, the scale of the product of a multiplication procedure\nnever exceeds the sum of the scales of the two numbers being multiplied.\nFor example,\n.DM\n\tscale = 10\n\t1.1 * 1.11\n.DE\nyields the result:\n.DM\n\t1.221\n.DE\nIf the variable \\fBscale\\fR is less than the \nsum of the scales of the numbers being multiplied, then the product\nwill have a scale equal to that of the variable \\fBscale\\fR.\nFor example,\n.DM\n\tscale = 4\n\t1.11 * 2.222\n.DE\nyields:\n.DM\n\t2.4664\n.DE\nThe scales of the operands are 2 and 3.\nThe larger scale is 3, so the result of a multiplication \nwill have a scale of at least 3, no matter what \\fBscale\\fR is set to.\nAlso, the sum of the scales is 5, so the result will never\nhave more than 5 digits to the right of the decimal point.\nIn this example, \\fBscale\\fR has been set to a scale of 4.\nTherefore, the result has four digits to the right of the decimal point.\n.Sh \"Scale for Divisions\"\n.PP\nFor division and remainder, the scale of the result is determined \nonly by the value of the variable \\fBscale\\fR.\nFor example,\n.DM\n\tscale = 13\n\t14 / 13\n\t14 % 13\n.DE\nyields:\n.DM\n\t1.0769230769230\n\t.0000000000010\n.DE\nFor non-whole numbers, as well as for integers,\nthe definition of remainder is chosen so that the relationship\n.DM\n\tdividend = (divisor * quotient) + remainder\n.DE\nis true.\n.Sh \"Scale From Exponentiation\"\n.PP\n.B bc\nsets the \\fBscale\\fR of a result of exponentiation as\nif repeated multiplications had been performed.\nThus, for\n.DM\n\t5.992 ^ 5\n.DE\nthe scale is chosen as if you typed:\n.DM\n\tn = 5.992\n\tn * n * n * n * n\n.DE\nThat is, the default is the scale of the largest (or, in this case,\nthe only) number being multiplied; and scale cannot exceed the\nsum of the scales of the numbers being multiplied.\nThus, the scale of the product in this example\nhas a default setting of 3, and can be reset up to 15.\n.Sh \"What Is the Current Scale?\"\n.PP\nThe variable \\fBscale\\fR is just like other variables:\nyou can assign values to it, as above.\nBecause it is like regular variables, you can also use it\nin operations, as in this example:\n.DM\n\tscale += 1\n.DE\nYou can also print its value:\n.DM\n\tscale\n.DE\nThe value of the \\fBscale\\fR variable is zero until you explicitly change it.\n.SH \"The if Statement\"\n.PP\nThe statements shown so far have been either assignment statements, \ngiving a new value to a variable; or an expression, which prints \nthe resulting value.\nSeveral other kinds of statements are available.\nThese give you power to write programs that make\ndecisions and perform iterative computations.\n.Sh \"Using the if Statement\"\n.PP\nTo see the\n.B if\nstatement in action, type the following example into \\fBbc\\fR:\n\n.DM\n\tx = 3\n\tif (x < 5) x\n\tif (x > 5) -x\n.DE\n.B bc\nreplies:\n.DM\n\t3\n.DE\nIf the input is:\n.DM\n\tx = 6\n\tif (x < 5) x\n\tif (x > 5) -x\n\t\n.DE\n\\fBbc\\fR replies:\n.DM\n\t-6\n.DE\nThe part of the\n.B if\nstatement in parentheses, such as \\fB(x > 5)\\fR, determines whether\n.B bc\nexecutes the statement that follows it, such as\n.BR -x .\nIf the expression is false, the following statement is not executed.\nIf the expression is true, the following statement is executed.\n.Sh \"Comparisons\"\n.PP\nThe decision expression in an \\fBif\\fR statement is enclosed in parentheses.\nThe decision can be based upon a comparison of two operands, or numbers.\nThe kinds of comparisons that can be done are:\n.DS\n\t\\fB==\\fR\tFirst operand equal to second\n\t\\fB!=\\fR\tFirst operand not equal to second\n\t\\fB<=\\fR\tFirst operand less than or equal to second\n\t\\fB<\\fR\tFirst operand less than second\n\t\\fB>=\\fR\tFirst operand greater than or equal to second\n\t\\fB>\\fR\tFirst operand greater than second\n.DE\nThe \\fBif\\fR statement can include the sorts of\nthe simple statements already shown.\nYou can also include an \\fBif\\fR statement, as well as the \\fBwhile\\fR,\n\\fBdo\\fR, and \\fBfor\\fR statements, \nwhich will be discussed below.\nThe following example illustrates the use of an \\fBif\\fR\nstatement within an \\fBif\\fR statement:\n.DM\n\ta = 2\n\tb = 6\n\tif (a >= 2) if (b > a) a + b\n\t\n.DE\n\\fBbc\\fR replies, simply:\n.DM\n\t8\n.DE\nBecause both of the \\fBif\\fR conditions were true,\n\\fBbc\\fR proceeded to add \\fBa\\fR and \\fBb\\fR.\nNote that nested\n.B if\nstatements must appear on the same line.\nTherefore, \n.DM\n\tif (a == 3) if (b > a) a + b\n.DE\ndoes not print the result of\n.B \"a + b\"\nbecause not both conditions were true.\nHowever\n.DM\n\tif (a == 3)\n\tif (b > a) a + b\n.DE\nprints the result of\n.B \"a + b\"\nbecause\n.B bc\ntreats\n.B if\nstatements one by one, and the second\n.B if\nstatement's condition is true.\n.Sh \"Grouped Statements\"\n.PP\nYou can place more than one statement after the expression part of the \n\\fBif\\fR statement by using grouping braces \\*(Ql\\fB{\\fR\\*(Qr\nand \\*(Ql\\fB}\\fR\\*(Qr.\nThis can be useful if you want to perform several calculations \nbased on the result of an \\fBif\\fR statement comparison.\nThe following example prints the value of \\fBa\\fR and \n\\fBb\\fR if the value of \\fBb\\fR is less than the value of \\fBa\\fR:\n.DM\n\ta = 1\n\tb = .99\n\tif (a > b) {\n\t a\n\t b\n\t}\n.DE\n\\fBbc\\fR replies:\n.DM\n\t1\n\t.99\n.DE\nAny statement may be enclosed within the group braces, as\nthe following example shows:\n.DM\n\ta = 1\n\tb = .99\n\tif (a > b) {\n\t a\n\t b\n\t if ((a + b) >= 2) a + b\n\t}\n.DE\n.Sh \"Many Statements Per Line\"\n.PP\nTo this point, all of our examples typed each statement on its own line.\nThis includes the group braces \\*(Ql\\fB{\\fR\\*(Qr and \\*(Ql\\fB}\\fR\\*(Qr,\nthe latter of which must appear on a line by itself.\nYou can, however, place several statements on one line if you separate them\nwith semicolons.\nIf you do this, remember that the semicolon rather than the\ncarriage return separates the statements.\nFor example, if you type:\n.DM\n\ta = 1;b = 2;c = 3\n\ta;b;c\n.DE\n\\fBbc\\fR replies:\n.DM\n\t1\n\t2\n\t3\n.DE\nYou can use this in combination with the group braces:\n.DM\n\ta = 1;b = 2;c = 3\n\tif ((a + b) >= c) {\n\t a; b; c; a + b; }\n.DE\nThe reply from \\fBbc\\fR is:\n.DM\n\t1\n\t2\n\t3\n\t3\n.DE\nThis example can be compressed even further by putting all of the \\fBif\\fR\nstatement on one line:\n.DM\n\ta = 1;b = 2;c = 3\n\tif ((a + b) >= c) { a; b; c; a + b; }\n.DE\nYou do not need to follow the \\*(Ql\\fB}\\fR\\*(Qr with a semicolon.\n.SH \"The while Statement\"\n.PP\nThe \\fBwhile\\fR statement repeats calculations.\nThis is useful in successive approximation calculations.\nThe following example of the \\fBwhile\\fR loop \nprints the numbers one through ten:\n.DM\n.ta 1.0i 1.5i\n\ti = 1\n\twhile (i <= 10) {\n\t\ti\n\t\ti = i + 1\n\t}\n.DE\n.B bc\nreplies:\n.DM\n\t1\n\t2\n\t3\n\t4\n\t5\n\t6\n\t7\n\t8\n\t9\n\t10\n.DE\nThe statement\n.DM\n\ti = i + 1\n.DE\nadds 1 to the variable \\fBi\\fR.\nThe expression\n.DM\n\t(i <= 10)\n.DE\ncompares \\fBi\\fR with ten.\nWhile \\fBi\\fR is less than or equal to ten, the \\fBwhile\\fR \nloop executes.\nWhen \\fBi\\fR is increased to greater than ten, the loop stops executing.\n.PP\n.B bc\nchecks the comparison expression for the \\fBwhile\\fR loop\nbefore the loop is entered for the first time.\nIf the comparison fails, the loop is not executed at all;\notherwise the processing repeats as long as the comparison is true.\nFor example, the following statements do not print anything:\n.DM\n\ti = 0\n\twhile (i > 1) i\n\tquit\n.DE\n.Sh \"Abbreviations in the while Statement\"\n.PP\nIf we recall the assignment statements from the previous section,\nwe can shorten\nthe \\fBwhile\\fR counting-to-ten example to:\n.DM\n\ti = 1\n\twhile (i <= 10) {\n\t\ti\n\t\ti += 1\n\t}\n.DE\nThe result remains the same \\(em a list of numbers from one to ten.\n.PP\nAnother abbreviation of the example uses the \\*(Ql\\fB++\\fR\\*(Qr operator.\nThe variable \\fBi\\fR is incremented, then tested in the \\fBwhile\\fR\nexpression, which simplifies the entire example to:\n.DM\n\ti = 0\n\twhile (++i <= 10) i\n.DE\nBefore the \\fBwhile\\fR is executed, \\fBi\\fR is set to zero.\nThen, the \\fBwhile\\fR expression increments the\nvalue of \\fBi\\fR before it is used or compared,\nThus, the first value compared, then printed, is one.\n.PP\nFinally, the example calculation can be shortened to one line.\nIf a variable in \\fBbc\\fR is used before it is initialized, it will\nhave the value of zero.\nFor example:\n.DM\n\tzip\n.DE\nprints:\n.DM\n\t0\n.DE\nUsing this in our counting-to-ten example yields:\n.DM\n\twhile (++n <= 10) n\n.DE\n.SH \"The for Statement\"\n.PP\n.B for\nis a statement that controls the execution of other\n.B bc\nstatements.\nYou should use\n\\fBfor\\fR to write a formula \nto control the number of times a value is computed.\n.PP\nThe previous section demonstrated how to print the numbers one to \nten using a \\fBwhile\\fR statement.\nThe following does the same task with a \\fBfor\\fR statement:\n.DM\n\tfor (i=1; i <= 10; ++i) i\n.DE\n.Sh \"Three Parts of the for Statement\"\n.PP\nThe \\fBfor\\fR statement is more complex than the \\fBwhile\\fR statement;\nits controlling expressions have three parts.\n.PP\nThe first part, shown here in italics\n.DM\n\tfor (\\fIi=1\\^\\fP; i <= 10; ++i) i\n.DE\nsets up the initial condition.\nThe second part\n.DM\n\tfor (i=1; \\fIi <= 10\\^\\fP; ++i) i\n.DE\ntests whether more iterations should be performed.\n.B bc\nperforms this test\n.I before\nit executes the statements that are subordinate to the\n.B for\nstatement.\nIf the test fails, no more iterations are performed.\n.PP\nThe third part\n.DM\n\tfor (i=1; i <= 10; \\fI++i\\^\\fP) i\n.DE\nis performed at the end of each iteration.\nIn practically every instance, this part of the\n.B for\nstatement modifies the value of the variable that the second part tests.\n.PP\nTaken together, these statements (1) set \\fBi\\fR to zero; (2) check whether\n\\fBi\\fR is less than or equal to ten; (3) if \\fBi\\fR proves to be so,\nprints \\fBi\\fR, and then increases it by one.\n.PP\nThe following example of the \\fBfor\\fR statement adds\nthe squares of the numbers one through ten, prints each square,\nand then prints the sum of the squares at the end.\n.DM\n\tsum = 0\n\tfor (n=1; n <= 10; ++n) {\n\t sq = n * n\n\t sq\n\t sum += sq\n\t}\n\tsum\n.DE\nThe result is:\n.DM\n\t1\n\t4\n\t9\n\t16\n\t25\n\t36\n\t49\n\t64\n\t81\n\t100\n\t385\n.DE\n.Sh \"Similarities Between the for and while Statements\"\n.PP\nTo illustrate the similarity between the \\fBfor\\fR statement and\nthe simpler \\fBwhile\\fR statement, the following rewrites the\nabove example, substituting the \\fBwhile\\fR for the \\fBfor\\fR:\n.DM\n\tsum = 0\n\tn = 0\n\twhile (++n <= 10) {\n\t\tsq = n * n\n\t\tsq\n\t\tsum += sq\n\t}\n\tsum\n.DE\n.SH \"Functions in bc\"\n.PP\n.B bc\nallows you to name routines that you use repeatedly.\nYou can then call them by name without having to retype them;\nobviously, this can be a great time-saver.\nThese named routines are called\n.IR functions .\nThis section shows you how to define and use functions\nfor your \\fBbc\\fR calculations.\n.Sh \"Example of Function Use\"\n.PP\nThe following example defines a function that calculates the area of\na circle from its radius.\n.DM\n\tscale = 5\n\tpi = 3.14159\n\tdefine area (radius) {\n\t\tr2 = radius * radius\n\t\treturn (pi * r2);\n\t}\n\tarea (1.00)\n\tarea (2.00)\n\tarea (56)\n.DE\nThe results will be:\n.DM\n\t3.14159\n\t12.56636\n\t9852.02624\n.DE\nThe \\fBdefine\\fR keyword tells \\fBbc\\fR that you are defining a function.\nThe name of the function follows.\nThen, in parentheses, come the \\fIparameters\\fR of the function.\nIn this example, the only parameter, or \\fIargument\\fR,\nof the function is \\fBradius\\fR.\nMost functions have arguments, but they are not mandatory.\n.PP\nThe \\fBreturn\\fR statement defines the value of the function.\nIn the\n.B area\nexample, the expression\n.DM\n\tarea (1.00)\n.DE\nreferences the function \\fBarea\\fR.\n\\fBbc\\fR then performs the calculation described by your definition\nof the function\n.BR area .\nThe number\n.DM\n\t1.00\n.DE\nis substituted wherever the parameter \\fBradius\\fR is shown.\n.PP\nThe statement\n.DM\n\tr2 = radius * radius\n.DE\nis then executed, yielding this result:\n.DM\n\t1.00\n.DE\nThen, the statement\n.DM\n\treturn (pi * r2)\n.DE\ncalculates the area and returns its value.\nThe statement\n.DM\n\tarea (1.00)\n.DE\nthen has the value calculated in the return statement.\n.Sh \"Functions Using Other Functions\"\n.PP\nFunctions in \\fBbc\\fR perform calculations using the\nsame expressions as the rest of the \\fBbc\\fR program.\nThis includes the use of functions.\nThe \\fBarea\\fR program can be written using another function,\n\\fBsq\\fR, to calculate the square of a number:\n.DM\n\tscale = 5\n\tpi = 3.14159\n\tdefine sq (number) {\n\t\treturn (number * number)\n\t\t}\n\tdefine area (radius) {\n\t\treturn (sq (radius) * pi)\n\t\t}\n\tarea (1.00)\n\tarea (2.00)\n\tarea (56)\n.DE\nAgain, the results will be identical:\n.DM\n\t3.14159\n\t12.56636\n\t9852.02624\n.DE\n.Sh \"Functions That Call Themselves\"\n.PP\nNot only can functions call other functions and perform\nregular calculations; a function can use itself in calculations.\nAn example of this is the Fibonacci calculation:\n.DM\n\tdefine fib (f) {\n\t\tif (f == 0) return (0)\n\t\tif (f == 1) return (1)\n\t\tif (f > 1) return (fib (f - 1) + fib (f - 2))\n\t}\n\tfib (5)\n\tfib (20)\n.DE\nFibonacci numbers are defined in the following way:\nFibonacci number zero is zero; similarly, Fibonacci number one is one.\nAny other Fibonacci number is defined as the sum of the two previous\nFibonacci numbers.\nFibonacci numbers are defined only for non-negative integers.\n.PP\nThe defined function \\fBfib\\fR follows this definition by \nreturning zero if the number requested is zero and one if the argument is one.\nIf the number is neither of these, then the function calls itself to\ncalculate the previous two numbers of the series and adds them together.\n.Sh \"The auto Statement\"\n.PP\nMany functions that call other functions, including themselves, may require\nvariables that are not changeable by the rest of the program.\nThis is signalled to \\fBbc\\fR by the \\fBauto\\fR statement:\n.DM\n\tauto var1, var2\n.DE\nThis declares \\fBvar1\\fR and \\fBvar2\\fR as local to\nthe function that contains them.\n.PP\nTo illustrate the use of \\fBauto\\fR, the following \\fBbc\\fR\nprogram calculates the factorial of a number:\n.DM\n\tdefine factorial (number) {\n\t\tauto value, i\n\t\tvalue = 1\n\t\tfor (i = 1; i <= number; ++i) value *= i\n\t\treturn (value)\n\t}\n\tvalue = 3\n\tfactorial (value)\n\ti = 99\n\tfactorial (20)\n\tvalue\n\ti\n.DE\nThe result is:\n.DM\n\t6\n\t2432902008176640000\n\t3\n\t99\n.DE\nThe first number, 6, results from:\n.DM\n\tfactorial (value)\n.DE\nThe second number is from:\n.DM\n\tfactorial (20)\n.DE\nThe last two numbers are from \\fBvalue\\fR and \\fBi\\fR,\nand are included to demonstrate that the variables in the function\n\\fBfactorial\\fR appearing in this statement:\n.DM\n\t auto value, i\n.DE\nare separate from the variables of the same name in the rest of the program.\n.PP\nIf the function calls itself, as the \\fBfib\\fR example does\nabove, any variable names noted in the \\fBauto\\fR statement are\nhandled separately for each call of the function.\n.SH \"Programs in a File\"\n.PP\nBecause its programs can be quite complex, \n\\fBbc\\fR lets you keep them in files.\nThis lets you build a library of \\fBbc\\fR programs and \nfunctions that can be called up easily.\n.Sh \"Using a Program From a File\"\n.PP\nTo illustrate the use of programs stored in a file,\ntype the following example into file \\fBfib.bc\\fR using the\neditor of your choice.\nThe program defines the function \\fBfib\\fR:\n.DM\n\tdefine fib (f) {\n\t\tif (f == 0) return (0)\n\t\tif (f == 1) return (1)\n\t\tif (f > 1) return (fib (f - 1) + fib (f - 2))\n\t}\n.DE\nTo use a \\fBbc\\fR program that has been stored in a file, enter\nthe file name on the \\fBbc\\fR command line, like this:\n.DM\n\tbc fib.bc\n.DE\nThe function definition will be read in by \\fBbc\\fR and ready for your use.\nTo use the function, simply type the function name with parameters.\n.PP\nSo, if you type:\n.DM\n\tbc fib.bc\n\tfib (6)\n.DE\n\\fBbc\\fR will reply:\n.DM\n\t8\n.DE\n.Sh \"Using Libraries\"\n.PP\nYou can enter several useful programs in their own files and call them\ninto \\fBbc\\fR at the same time.\nThe following example creates another function\nthat calculates the sum of the squares of integers up to a given number.\nUse an editor to type the following into a file named \\fBsumsq.bc\\fR:\n.DM\n\tdefine sumsq (number) {\n\t\tauto i, sum\n\t\tsum = 0\n\t\tfor (i = number; i > 0; --i) sum += i ^ 2\n\t\treturn (sum)\n\t}\n.DE\nNow, you can use the \\fBsumsq\\fR function to print the sum of\nthe squares for each number from one to ten:\n.DM\n\tbc sumsq.bc\n\tfor (i = 1; i <= 10; ++i) sumsq (i)\n.DE\nThe result is:\n.DM\n\t1\n\t5\n\t14\n\t30\n\t55\n\t91\n\t140\n\t204\n\t285\n\t385\n\tquit\n.DE\nYou can use the two functions stored in a file to print the difference\nbetween the sum of the squares of numbers, and the\nFibonacci number:\n.DM\n\tbc fib.bc sumsq.bc\n\tfor (i = 1; i <= 10; ++i) sumsq (i) - fib (i)\n\tquit\n.DE\nThe result of this questionable computation is:\n.DM\n\t0\n\t4\n\t12\n\t27\n\t50\n\t83\n\t127\n\t183\n\t251\n\t330\n.DE\n.Sh \"The bc Library\"\n.II bc^library\n.PP\n\\*(OS provides\nan extended library to go with \\fBbc\\fR.\nIt includes the following functions:\n.DS\n\t\\fBatan\\fP(\\fIz\\fP)\tarctangent of \\fIz\\fP\n\t\\fBcos\\fP(\\fIz\\fP)\tcosine of \\fIz\\fP\n\t\\fBexp\\fP(\\fIz\\fP)\texponential function of \\fIz\\fP\n\t\\fBj\\fP(\\fIn,z\\fP)\t\\fIn\\fPth order Bessel function of \\fIz\\fP\n\t\\fBln\\fP(\\fIz\\fP)\tnatural logarithm of \\fIz\\fP\n\t\\fBpi\\fP\tthe value of pi to 100 digits\n\t\\fBsin\\fP(\\fIz\\fP)\tsine of \\fIz\\fP\n.DE\nThe library is stored in file\n.if \\nX=0 \\fB/usr/lib/lib.b\\fR.\n.if \\nX=1 \\fB\\eBIN\\eLIB.B\\fR.\nTo use the library, invoke the \\fBbc\\fR\ncommand with the \\fB-l\\fR option.\n.PP\nTo show how the library can be used in your work\nthe following example computes the sine of an angle of\none-third radian with scale set to 20:\n.DM\n\tbc -l\n\tscale = 20\n\tsin (1/3)\n\tquit\n.DE\nThe result is:\n.DM\n\t.32719469679615224418\n.DE\n.SH Summary\n.PP\nThe Lexicon entry for\n.B bc\nsummarizes its commands, features, and libraries.\nIt will also refer you to related commands and functions.\n", "meta": {"hexsha": "d1fab5a3693ae352e74ac4f06c41d154e6a21376", "size": 26409, "ext": "r", "lang": "R", "max_stars_repo_path": "doc/mwc/doc/coherent/text/bc.r", "max_stars_repo_name": "gspu/Coherent", "max_stars_repo_head_hexsha": "299bea1bb52a4dcc42a06eabd5b476fce77013ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-10-10T14:14:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:54:38.000Z", "max_issues_repo_path": "doc/mwc/doc/coherent/text/bc.r", "max_issues_repo_name": "gspu/Coherent", "max_issues_repo_head_hexsha": "299bea1bb52a4dcc42a06eabd5b476fce77013ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/mwc/doc/coherent/text/bc.r", "max_forks_repo_name": "gspu/Coherent", "max_forks_repo_head_hexsha": "299bea1bb52a4dcc42a06eabd5b476fce77013ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-25T18:38:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T18:38:37.000Z", "avg_line_length": 23.1454864154, "max_line_length": 80, "alphanum_fraction": 0.7233897535, "num_tokens": 8399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.48356338620322875}} {"text": "# auprc.r\n# usage: Rscript auprc.r\n# calculate the Area under Precision Recall curve\n\nlibrary(zoo)\n\n# order x in increasing fashion\nx <- c(0.755239138372, 0.761591821833, 0.766995253742, 0.772033588901, 0.778386272362, 0.783935742972, 0.789558232932, 0.795618838992, 0.801533406353)\ny <- c(1, 1, 1, 1, 1, 0.999255398362, 0.995305596465, 0.987493202828, 0.9801768015)\nid <- order(x)\n\nauc <- sum(diff(x[id]) * rollmean(y[id], 2))\nprint(paste0(\"auPRC = \", auc))\n", "meta": {"hexsha": "a2eb28690a4f6845718fa294058f59cd5b3b7f0e", "size": 459, "ext": "r", "lang": "R", "max_stars_repo_path": "auprc.r", "max_stars_repo_name": "aniketk21/tfbs-prediction", "max_stars_repo_head_hexsha": "dbb98450182f5be7a7f1ff71b8c382fcbba8666b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-07T07:22:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-11T15:56:08.000Z", "max_issues_repo_path": "auprc.r", "max_issues_repo_name": "aniketk21/tfbs-prediction", "max_issues_repo_head_hexsha": "dbb98450182f5be7a7f1ff71b8c382fcbba8666b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auprc.r", "max_forks_repo_name": "aniketk21/tfbs-prediction", "max_forks_repo_head_hexsha": "dbb98450182f5be7a7f1ff71b8c382fcbba8666b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7857142857, "max_line_length": 150, "alphanum_fraction": 0.7145969499, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4834921231875923}} {"text": "# Script to fit an SEIRS-SEI dengue transmission model to weekly trap counts\n# and reports of \"dengue-like illness\" using Stan.\n\nlibrary(rstan)\nlibrary(plyr)\nlibrary(magrittr)\nlibrary(lubridate)\n\n# Setting Stan options\nrstan_options(auto_write = TRUE)\noptions(mc.cores = parallel::detectCores())\n\n#===============================================================================\n# Loading data and setting up model\n\ntseries <- read.csv(\"Data/Vitoria.data.csv\")\n\ndata <- ddply(tseries, .(tot.week), summarise,\n obs = sum(Cases, na.rm = T),\n q = sum(Mosquitoes, na.rm = T),\n tau = sum(Trap, na.rm = T),\n year = unique(Year),\n week = unique(Week)\n )\n\n# Population size\npop <- 327801\n\n# Wrangling weather data and computing EIP\nweather <- read.csv(\"Data/Vitoria.weather.csv\") %>% \n mutate(date = ymd(BRST), year = year(date), week = week(date))\n\nweather <- subset(weather, date < date[1] + weeks(243))\nweather$tot.week <- rep(c(1:243), each = 7)\n\n# Weekly mean temperature\ncovars <- ddply(weather, .(tot.week), summarise, \n temp = mean(Mean.TemperatureC, na.rm = T),\n humid = mean(Mean.Humidity, na.rm = T))\n\n# Computing inverse of extrinsic incubation period\nrov <- 7 * exp(0.21 * covars$temp - 7.9)\n\n#===============================================================================\n# Running stan\n\n# Setting imports (if any)\nfirsts <- daply(data, .(year), function(df) min(df$tot.week))[2:5]\nimport <- rep(0, 243)\n# import[firsts - 8] <- 10 / pop\n\n# Wrapping up all the data\ndat.stan <- list(T = 243,\n steps = 7,\n y =data$obs,\n q = data$q,\n tau = data$tau,\n rov = rov,\n control = matrix(1.0, nrow = 243, ncol = 3),\n import = import,\n pop = pop)\n\n# Specifying initial conditions for 3 chains\ninits = list(list(S0 = 0.4,\n E0 = 80,\n I0 = 40,\n log_phi_q = -13,\n phi_y = 1/12,\n eta_inv_y = 0.1,\n eta_inv_q = 0.1,\n ro_c = 0.8,\n gamma_c = 1,\n delta_c = 0.8,\n dvmu_c = 1, \n logNv = 1.5,\n dv0 = 0,\n rv0 = 0,\n sigmadv = 0.2,\n sigmarv = 0.2,\n eps_dv = rep(0, 243),\n eps_rv = rep(0, 243)),\n list(S0 = 0.3,\n E0 = 100,\n I0 = 80,\n log_phi_q = -13.5,\n phi_y = 1/6,\n eta_inv_y = 1,\n eta_inv_q = 1,\n ro_c = 1,\n gamma_c = 1.2,\n delta_c = 1,\n dvmu_c = 0.6,\n logNv = 0.7,\n dv0 = 0,\n rv0 = 0,\n sigmadv = 0.5,\n sigmarv = 0.5,\n eps_dv = rep(0, 243),\n eps_rv = rep(0, 243)),\n list(S0 = 0.5,\n E0 = 40,\n I0 = 20,\n log_phi_q = -12.5,\n phi_y = 1/24,\n eta_inv_y = 5,\n eta_inv_q = 5,\n ro_c = 0.9,\n gamma_c = 0.5,\n delta_c = 0.6,\n dvmu_c = 1,\n logNv = 1,\n dv0 = 0,\n rv0 = 0,\n sigmadv = 0.01,\n sigmarv = 0.01,\n eps_dv = rep(0, 243),\n eps_rv = rep(0, 243)))\n\n# Running HMC\n# Note non-default options for adapt_delta and max_treedepth, which \n# help ensure good mixing and avoid divergent transitions\n# Also note that this will take on the order of 1 week to run\n\nfit <- stan(file = \"Code/gammaeip.stan\", \n data = dat.stan, \n init = inits, \n iter = 2000,\n chains = 3,\n control = list(adapt_delta = 0.99,\n max_treedepth = 15))\n\nsaveRDS(fit, \"Results/chain.rds\")\n", "meta": {"hexsha": "48d0d09a6450684aed3913c0a5311d05b6318e4f", "size": 4131, "ext": "r", "lang": "R", "max_stars_repo_path": "Analysis/citystan.r", "max_stars_repo_name": "clint-leach/mosquito-recon", "max_stars_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-30T08:56:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T09:40:12.000Z", "max_issues_repo_path": "Analysis/citystan.r", "max_issues_repo_name": "clint-leach/mosquito-recon", "max_issues_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis/citystan.r", "max_forks_repo_name": "clint-leach/mosquito-recon", "max_forks_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-03T08:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-03T08:36:04.000Z", "avg_line_length": 31.0601503759, "max_line_length": 80, "alphanum_fraction": 0.4274993948, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4833304498195835}} {"text": "\n#===================================\n#\n# Detection probability - survival analysis\n# -----\nlibrary(tidyverse)\nlibrary(lubridate)\nlibrary(sf)\nlibrary(purrr)\nlibrary(nimble)\nlibrary(posterior)\nsource(\"R/judas functions.r\")\n\ngoat_dyads<- read_csv(\"data/Santiago_judas_dyads.csv\")\ngoat_dyads<- goat_dyads %>% mutate(id1 = factor(as.character(id1)), id2 = factor(as.character(id2)))\ngoat_ids<- goat_dyads %>% select(ID=id1,Sex=Sex1,Trans=Trans1) %>% distinct() %>% arrange(ID)\n\nid1<- as.vector(unclass(goat_dyads$id1))\nid2<- as.vector(unclass(goat_dyads$id2))\n\ndyad<- as.vector(unclass(factor(goat_dyads$Dyad)))\nndyads<- max(dyad)\nN<- nrow(goat_dyads)\nM<- nrow(goat_ids)\nX<- model.matrix(~ distance + Sex1 + Trans1, data=goat_dyads)[,-1]\nK<- ncol(X)\nsex<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\n# Calculate home range scale (sigma) from Judas locations \n\ngoat_locs<- read_csv(\"data/santiago_judas_locs.csv\")\ngoat_locs<- goat_locs %>% mutate(ID = factor(as.character(ID)))\ngoat_locs<- goat_locs %>% group_by(ID) %>% nest() %>% arrange(ID)\n\n\ngoat_chr<- goat_locs %>% mutate(CNorm=map(data, calc_hr))\ngoat_chr<- goat_chr %>% unnest(CNorm) %>% select(-data)\n\nmaxD<- goat_chr$sigma * 2.45\n\n#------------------------------------------------------\n# Discrete survival analysis\n\n# Nimble function to undertake estimation of Marginal detection probability (Eqn. 2)\n\nintegrateP<- function(b0, b1, beta, XX, maxD) {\n integrand<- function(x, b0, b1, beta, XX, maxD) {\n e<- 2*x/maxD^2 \n sex.effects<- as.vector(beta %*% XX)\n int<- e * (1-exp(-exp(b0 + b1*x + sex.effects)))\n return(int)\n }\n return(integrate(integrand,lower=0,upper=maxD, b0=b0, b1=b1, beta=beta, XX=XX, maxD=maxD,\n rel.tol = .Machine$double.eps^0.5)[[1]])\n}\n\nRintegrateP <- nimbleRcall(function(b0=double(0), b1=double(0), beta=double(1),\n XX=double(1), maxD=double(0)){}, Rfun='integrateP',\n returnType = double(0))\n\n# Nimble code - Note: since no time varying parameters/covariates we can group intervals\n# and use a binomial distribution rather than bernoulli.\n\ncode<- nimbleCode({\n \n for (i in 1:N) {\n ev[i] ~ dbin(q[i], time[i])\n cloglog(q[i])<- b1 + inprod(X[i,1:K],beta[1:K]) + eps_id1[id1[i]] + eps_id2[id2[i]]\n }\n \n for(k in 1:M) {\n eps_id1[k] ~ dnorm(0, sd=sigma_id1)\n eps_id2[k] ~ dnorm(0, sd=sigma_id2)\n beta0[k] <- b1 + eps_id1[k]\n Pave[k]<- RintegrateP(beta0[k], beta[1], beta[2:K], sex[k,1:(K-1)], maxD[k])\n }\n \n for(j in 1:K) {\n beta[j] ~ dnorm(0, sd=5)\n }\n b1 ~ dnorm(0, sd=5)\n \n sigma_id1 ~ T(dt(0, 1, 4),0,)\n sigma_id2 ~ T(dt(0, 1, 4),0,)\n \n}) \t\n#----------------------\n\nconstants<- list(N=N, M=M, K=K, id1=id1, id2=id2)\ndata<- list(time=goat_dyads$time,ev=goat_dyads$event, X=X, sex=sex, maxD=maxD)\n\n\ninits1<- list(b1=-4, beta= c(-1,1,1,1), sigma_id1=runif(1),sigma_id2=runif(1),\n q=rep(0.01,N),eps_id1=runif(M,-2,0),eps_id2=runif(M, -2,0))\n\n## create the model object\nRmodel <- nimbleModel(code=code, constants=constants, data=data, inits=inits1)\nRmcmc<- compileNimble(Rmodel)\n\nModSpec <- configureMCMC(Rmodel)\n#ModSpec$removeSamplers(c(\"eps_id1\"), print = FALSE)\n#ModSpec$removeSamplers(c(\"eps_id2\"), print = FALSE)\n#ModSpec$addSampler(target =c(\"eps_id1\"), type = 'AF_slice', print=FALSE)\n#ModSpec$addSampler(target =c(\"eps_id2\"), type = 'AF_slice', print=FALSE)\nModSpec$resetMonitors()\nModSpec$addMonitors(c(\"b1\",\"beta\",\"sigma_id1\",\"sigma_id2\",\"beta0\",\"Pave\"))\n \n\nCmcmc <- buildMCMC(ModSpec)\nCmodel <- compileNimble(Cmcmc, project = Rmodel, resetFunctions = T)\n\nn.iter<- 2000\nn.burnin<- 1000\nn.thin<- 1\nn.chains<- 3\n\ninits<- function(){inits1}\n\nsamp<- runMCMC(Cmodel, niter=n.iter, nburnin=n.burnin, thin=n.thin, nchains=n.chains,inits=inits,\n samplesAsCodaMCMC = TRUE)\n\n\ntmp<- subset_draws(as_draws(samp), variable=c(\"b1\",\"beta\",\"sigma_id1\",\"sigma_id2\"))\nsummarise_draws(tmp)\n\ntmp<- subset_draws(as_draws(samp), variable=c(\"Pave\"))\nsummarise_draws(tmp)\n#--------------------------------------------------------------------\n# Plots\n#-------------------------------------------------------------------- \n\n# Predicted probability of detection at activity centres (i.e. distance = 0)\n\nfit<- as_draws_rvars(samp)\n\nbeta0<- draws_of(fit$beta0)\nbeta<- draws_of(fit$beta)\nbeta1<- beta[,1]\nbeta2<- beta[,-1]\n\nn<- nrow(goat_ids)\nXX<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\nplam<- matrix(NA,nrow=dim(beta)[1],ncol=n)\nfor(i in 1:n){\n plam[,i]<- 1-exp(-exp(beta0[,i] + beta2 %*% XX[i,]))\n}\n\nplam<- as.data.frame(plam)\nnames(plam)<- goat_ids$ID\nplam$samp<- 1:nrow(plam)\n\nplam<- plam %>% pivot_longer(-samp, names_to = \"ID\", values_to = \"p\")\nplam<- left_join(plam, goat_ids)\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\nwin.graph(10,5)\nplam %>% ggplot(aes(ID, p, color=interaction(Sex,Trans))) +\n geom_boxplot(fill=\"grey90\",outlier.color = NA) +\n labs(x=\"Judas ID\", y=\"Detection probability at HR centre\") + \n theme_bw() +\n theme(axis.text.x = element_blank(),\n legend.position = \"bottom\",\n legend.title = element_blank())\n\n\n\n#--------------------------------------------------------\n# Predicted detection curves with distance from HR centre\n#--------------------------------------------------------\nfit<- as_draws_rvars(samp)\n\nbeta0<- E(fit$beta0)\nbeta<- E(fit$beta)\nbeta1<- beta[1]\nbeta2<- beta[-1]\n\nn<- nrow(goat_ids)\ndistance<- seq(0,20,0.1)\nXX<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\nplam<- matrix(NA,nrow=length(distance), ncol=n)\n\nfor(i in 1:n){\n plam[,i]<- 1-exp(-exp(beta0[i] + beta1*distance + as.vector(XX[i,] %*% beta2)))\n}\nplam<- as.data.frame(plam)\nnames(plam)<- goat_ids$ID\nplam<- plam %>% mutate(Distance=distance)\n\nplam<- plam %>% pivot_longer(-Distance, names_to = \"ID\", values_to = \"p\")\nplam<- left_join(plam, goat_ids)\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\n\nwin.graph(8,7)\nplam %>% ggplot(aes(Distance, p, group=ID)) +\n geom_line(color=\"grey50\") +\n facet_grid(rows=vars(Sex), cols=vars(Trans)) +\n labs(x=\"Distance (km)\",y=\"Probability of association\") +\n theme_bw() +\n theme(legend.position = \"none\",\n strip.text = element_text(face=\"bold\"))\n\n#--------------------------------------------------------------------\n# Unconditional detection probability (Eqn. 2)\n#-------------------------------------------------------------------- \n\nfit<- subset_draws(as_draws_rvars(samp), variable=\"Pave\")\n\nplam<- goat_ids %>% mutate(pave= E(fit$Pave), lcl = quantile2(fit$Pave)[1,], ucl=quantile2(fit$Pave)[2,])\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\nwin.graph(10,5)\nplam<- plam %>% arrange(pave)\nplam %>% mutate(ID = fct_reorder(ID, pave), Sex) %>%\n ggplot(aes(x=Trans, y=pave, color=Sex)) +\n geom_pointrange(aes(ymin=lcl,ymax=ucl), position=position_dodge2(width=0.5)) +\n facet_wrap(~Sex) +\n labs(x=\"\",y=\"Probability of association\",color=\"Status\") +\n theme_bw() +\n theme(legend.position = \"none\",\n strip.text = element_text(face=\"bold\"),\n axis.title = element_text(face=\"bold\", size=12),\n axis.text.x = element_text(size=11))\n", "meta": {"hexsha": "26af558da3dd1df71abf7b21311d61a9764898e6", "size": 7435, "ext": "r", "lang": "R", "max_stars_repo_path": "R/discrete_survival_nimble.r", "max_stars_repo_name": "dslramsey/judas_detection", "max_stars_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/discrete_survival_nimble.r", "max_issues_repo_name": "dslramsey/judas_detection", "max_issues_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/discrete_survival_nimble.r", "max_forks_repo_name": "dslramsey/judas_detection", "max_forks_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4672489083, "max_line_length": 105, "alphanum_fraction": 0.6068594486, "num_tokens": 2342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4832698750335064}} {"text": "#' Conversion between adjacency matrix and edgelist\n#'\n#' Generates adjacency matrix from an edgelist and vice versa.\n#'\n#' @param edgelist Two column matrix/data.frame in the form of ego -source- and\n#' alter -target- (see details).\n#' @templateVar undirected TRUE\n#' @templateVar self TRUE\n#' @templateVar multiple TRUE\n#' @template graph_template\n#' @param w Numeric vector. Strength of ties (optional).\n#' @param t0 Integer vector. Starting time of the ties (optional).\n#' @param t1 Integer vector. Finishing time of the ties (optional).\n#' @param t Integer scalar. Repeat the network \\code{t} times (if no \\code{t0,t1} are provided).\n#' @param simplify Logical scalar. When TRUE and \\code{times=NULL} it will return an adjacency\n#' matrix, otherwise an array of adjacency matrices.\n#' (see details).\n#' @param keep.isolates Logical scalar. When FALSE, rows with \\code{NA/NULL} values\n#' (isolated vertices unless have autolink) will be droped (see details).\n#' @param recode.ids Logical scalar. When TRUE ids are recoded using \\code{\\link{as.factor}}\n#' (see details).\n#' @details\n#'\n#' When converting from edglist to adjmat the function will \\code{\\link{recode}} the\n#' edgelist before starting. The user can keep track after the recording by checking\n#' the resulting adjacency matrices' \\code{\\link{row.names}}. In the case that the\n#' user decides skipping the recoding (because wants to keep vertices index numbers,\n#' implying that the resulting graph will have isolated vertices), he can override\n#' this by setting \\code{recode.ids=FALSE} (see example).\n#'\n#' When multiple edges are included, \\code{multiple=TRUE},each vertex between \\eqn{\\{i,j\\}}{{i,j}} will be counted\n#' as many times it appears in the edgelist. So if a vertex \\eqn{\\{i,j\\}}{{i,j}} appears 2\n#' times, the adjacency matrix element \\code{(i,j)} will be 2.\n#'\n#' Edges with incomplete information (missing data on \\code{w} or \\code{times}) are\n#' not included on the graph. Incomplete cases are tagged using \\code{\\link{complete.cases}}\n#' and can be retrieved by the user by accessing the attribute \\code{incomplete}.\n#'\n#' Were the case that either ego or alter are missing (i.e. \\code{NA} values), the\n#' function will either way include the non-missing vertex. See below for an example\n#' of this.\n#'\n#' The function performs several checks before starting to create the adjacency\n#' matrix. These are:\n#' \\itemize{\n#' \\item{Dimensions of the inputs, such as number of columns and length of vectors}\n#' \\item{Having complete cases. If anly edge has a non-numeric value such as NAs or\n#' NULL in either \\code{times} or \\code{w}, it will be\n#' removed. A full list of such edges can be retrieved from the attribute\n#' \\code{incomplete}}\n#' \\item{Nodes and times ids coding}\n#' }\n#'\n#' \\code{recode.ids=FALSE} is useful when the vertices ids have already been\n#' coded. For example, after having use \\code{adjmat_to_edgelist}, ids are\n#' correctly encoded, so when going back (using \\code{edgelist_to_adjmat})\n#' \\code{recode.ids} should be FALSE.\n#'\n#'\n#'\n#' @return In the case of \\code{edgelist_to_adjmat} either an adjacency matrix\n#' (if times is NULL) or an array of these (if times is not null). For\n#' \\code{adjmat_to_edgelist} the output is an edgelist with the following columns:\n#' \\item{ego}{Origin of the tie.}\n#' \\item{alter}{Target of the tie.}\n#' \\item{value}{Value in the adjacency matrix.}\n#' \\item{time}{Either a 1 (if the network is static) or the time stamp of the tie.}\n#' @export\n#' @examples\n#' # Base data\n#' set.seed(123)\n#' n <- 5\n#' edgelist <- rgraph_er(n, as.edgelist=TRUE, p=.2)[,c(\"ego\",\"alter\")]\n#' times <- sample.int(3, nrow(edgelist), replace=TRUE)\n#' w <- abs(rnorm(nrow(edgelist)))\n#'\n#' # Simple example\n#' edgelist_to_adjmat(edgelist)\n#' edgelist_to_adjmat(edgelist, undirected = TRUE)\n#'\n#' # Using w\n#' edgelist_to_adjmat(edgelist, w)\n#' edgelist_to_adjmat(edgelist, w, undirected = TRUE)\n#'\n#' # Using times\n#' edgelist_to_adjmat(edgelist, t0 = times)\n#' edgelist_to_adjmat(edgelist, t0 = times, undirected = TRUE)\n#'\n#' # Using times and w\n#' edgelist_to_adjmat(edgelist, t0 = times, w = w)\n#' edgelist_to_adjmat(edgelist, t0 = times, undirected = TRUE, w = w)\n#'\n#' # Not recoding ----------------------------------------------------\n#' # Notice that vertices 3, 4 and 5 are not present in this graph.\n#' graph <- matrix(c(\n#' 1,2,6,\n#' 6,6,7\n#' ), ncol=2)\n#'\n#' # Generates an adjmat of size 4 x 4\n#' edgelist_to_adjmat(graph)\n#'\n#' # Generates an adjmat of size 7 x 7\n#' edgelist_to_adjmat(graph, recode.ids=FALSE)\n#'\n#' # Dynamic with spells -------------------------------------------------------\n#' edgelist <- rbind(\n#' c(1,2,NA,1990),\n#' c(2,3,NA,1991),\n#' c(3,4,1991,1992),\n#' c(4,1,1992,1993),\n#' c(1,2,1993,1993)\n#' )\n#'\n#' graph <- edgelist_to_adjmat(edgelist[,1:2], t0=edgelist[,3], t1=edgelist[,4])\n#'\n#' # Creating a diffnet object with it so we can apply the plot_diffnet function\n#' diffnet <- as_diffnet(graph, toa=1:4)\n#' plot_diffnet(diffnet, label=rownames(diffnet))\n#'\n#' # Missing alter in the edgelist ---------------------------------------------\n#' data(fakeEdgelist)\n#'\n#' # Notice that edge 202 is isolated\n#' fakeEdgelist\n#'\n#' # The function still includes vertex 202\n#' edgelist_to_adjmat(fakeEdgelist[,1:2])\n#'\n#' edgelist\n#'\n#' @keywords manip\n#' @family data management functions\n#' @include graph_data.r\n#' @author George G. Vega Yon & Thomas W. Valente\nedgelist_to_adjmat <- function(\n edgelist, w=NULL,\n t0=NULL, t1=NULL, t=NULL, simplify=TRUE,\n undirected=getOption(\"diffnet.undirected\"), self=getOption(\"diffnet.self\"), multiple=getOption(\"diffnet.multiple\"),\n keep.isolates=TRUE, recode.ids=TRUE) {\n\n cls <- class(edgelist)\n if (\"data.frame\" %in% cls)\n edgelist_to_adjmat.data.frame(\n edgelist, w, t0, t1, t, simplify, undirected, self, multiple,\n keep.isolates, recode.ids\n )\n else if (\"matrix\" %in% cls)\n edgelist_to_adjmat.matrix(\n edgelist, w, t0, t1, t, simplify, undirected, self, multiple,\n keep.isolates, recode.ids)\n else stop(\"-edgelist- should be either a data.frame, or a matrix.\")\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nedgelist_to_adjmat.data.frame <- function(\n edgelist, w,\n t0,t1, t, simplify,\n undirected, self, multiple,\n keep.isolates, recode.ids) {\n\n edgelist_to_adjmat.matrix(as.matrix(edgelist), w, t0,t1, t, simplify,\n undirected, self, multiple, keep.isolates,\n recode.ids)\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nedgelist_to_adjmat.matrix <- function(\n edgelist, w,\n t0, t1,\n t, simplify,\n undirected, self, multiple,\n keep.isolates, recode.ids) {\n\n # Step 0: Checking dimensions\n if (ncol(edgelist) !=2) stop(\"Edgelist must have 2 columns\")\n if (length(t0) && nrow(edgelist) != length(t0))\n stop(\"-t0- should have the same length as number of rows in -edgelist-.\",\n \" Currently they are \",length(t0), \" and \", nrow(edgelist),\n \" respectively.\")\n if (length(t1) && nrow(edgelist) != length(t1))\n stop(\"-t1- should have the same length as number of rows in -edgelist-.\",\n \" Currently they are \",length(t1), \" and \", nrow(edgelist),\n \" respectively.\")\n if (length(w) && nrow(edgelist) != length(w))\n stop(\"-w- should have the same length as number of rows in -edgelist-.\",\n \" Currently they are \",length(w), \" and \", nrow(edgelist),\n \" respectively.\")\n\n ##############################################################################\n # Step 1: Incomplete cases.\n # Finding incomplete cases. This is always done since we need to provide a\n # complete list of variables to the C++ function, otherwise it will throw\n # an error.\n if (length(w)) complete <- complete.cases( w)\n else complete <- rep(TRUE, nrow(edgelist))\n edgelist <- edgelist[complete,]\n\n incomplete <- which(!complete)\n\n # Getting the list of isolated vertices\n not.isolated <- which(!is.na(edgelist[,1]) & !is.na(edgelist[,2]))\n\n # If the user chooses to drop incomplete, then what changes is the selection\n # of ids in the graph.\n # Times and w MUST be removed since wont be used in the C++ function\n if (length(incomplete))\n warning(\"Some edges a had NA/NULL value on either -times- or -w-:\\n\\t\",\n paste0(head(incomplete,20), collapse = \", \"),\n ifelse(length(incomplete)>20,\", ...\", \"\"),\n \"\\nThese won't be included in the adjacency matrix. The complete list will be stored as an attribute of the resulting\",\n \" adjacency matrix, namely, -incomplete-.\")\n\n\n # If no.incomplete is activated, then the vectors should be fixed\n if (!keep.isolates) edgelist <- edgelist[not.isolated,,drop=FALSE]\n\n ##############################################################################\n # Step 2: Recoding nodes ids\n # Recoding nodes ids\n if (recode.ids) {\n # Recoding\n dat <- recode(edgelist)\n n <- max(dat, na.rm = TRUE)\n\n # Retrieving codes + labels. If use.incomplete == FALSE, then the edgelist\n # has already been filtered\n recodedids <- attr(dat, \"recode\")\n if (keep.isolates) dat <- dat[not.isolated,]\n attr(dat, \"recode\") <- recodedids\n rm(recodedids)\n }\n else {\n dat <- edgelist\n n <- max(dat, na.rm = TRUE)\n }\n\n ##############################################################################\n # Step 3: Preparing -times- and -w- considering complete cases.\n # Times + recoding\n m <- nrow(dat)\n if (length(t0)) t0 <- t0[complete][not.isolated]\n else t0 <- rep(NA, m)\n\n if (length(t1)) t1 <- t1[complete][not.isolated]\n else t1 <- rep(NA, m)\n\n suppressWarnings(oldtimes <- range(c(t0,t1), na.rm=TRUE))\n if (all(!is.finite(oldtimes))) oldtimes <- rep(1,2)\n oldtimes <- oldtimes[1]:oldtimes[2]\n\n t0 <- t0 - oldtimes[1] + 1L\n t1 <- t1 - oldtimes[1] + 1L\n\n # Replacing NAs\n t0[is.na(t0)] <- 1\n if (!length(t)) t <- max(c(t0,t1), na.rm=TRUE)\n t1[is.na(t1)] <- t\n\n # Weights\n if (length(w)) w <- w[complete][not.isolated]\n else w <- rep(1, m)\n\n ##############################################################################\n # Computing the graph\n graph <- vector(\"list\", t)\n\n if (recode.ids) labs <- attr(dat, \"recode\")[[\"label\"]]\n else labs <- 1:n\n\n for(i in 1:t) {\n index <- which((t0 <= i) & (i <= t1))\n graph[[i]] <- edgelist_to_adjmat_cpp(\n dat[index,,drop=FALSE], w[index], n, undirected, self, multiple)\n\n # Naming\n dimnames(graph[[i]]) <- list(labs, labs)\n }\n\n # Times naming\n if (t>1 && (length(oldtimes) == 1))\n oldtimes <- 1:t\n\n names(graph) <- oldtimes\n\n if (t==1 & simplify) graph <- graph[[1]]\n\n attr(graph, \"incomplete\") <- incomplete\n\n return(graph)\n}\n\n#' @rdname edgelist_to_adjmat\n#' @export\nadjmat_to_edgelist <- function(\n graph,\n undirected=getOption(\"diffnet.undirected\", FALSE),\n keep.isolates = getOption(\"diffnet.keep.isolates\", TRUE)\n ) {\n\n cls <- class(graph)\n out <- if (\"list\" %in% cls) {\n adjmat_to_edgelist.list(graph, undirected, keep.isolates)\n } else if (\"matrix\" %in% cls) {\n cbind(adjmat_to_edgelist.matrix(graph, undirected, keep.isolates),1)\n } else if (\"array\" %in% cls) {\n adjmat_to_edgelist.array(graph, undirected, keep.isolates)\n } else if (\"dgCMatrix\" %in% cls) {\n cbind(adjmat_to_edgelist.dgCMatrix(graph, undirected, keep.isolates), 1)\n } else\n stopifnot_graph(graph)\n\n colnames(out) <- c(\"ego\", \"alter\", \"value\", \"time\")\n out\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nadjmat_to_edgelist.matrix <- function(graph, undirected, keep.isolates) {\n # as.integer(factor(diffnet$meta$ids[fakeDynEdgelist[,1]], diffnet$meta$ids))\n out <- adjmat_to_edgelist_cpp(methods::as(graph, \"dgCMatrix\"), undirected)\n\n # If keep isolates\n if (keep.isolates) {\n N <- 1:nvertices(graph)\n test <- which(!(N %in% unlist(out[,1:2])))\n\n # If there are isolates\n if (length(test)) out <- rbind(out, cbind(test, NA, NA))\n }\n\n return(out)\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nadjmat_to_edgelist.dgCMatrix <- function(graph, undirected, keep.isolates) {\n out <- adjmat_to_edgelist_cpp(graph, undirected)\n\n # If keep isolates\n if (keep.isolates) {\n N <- 1:nvertices(graph)\n test <- which(!(N %in% unlist(out[,1:2])))\n\n # If there are isolates\n if (length(test)) out <- rbind(out, cbind(test, NA, NA))\n }\n\n return(out)\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nadjmat_to_edgelist.array <- function(graph, undirected, keep.isolates) {\n edgelist <- matrix(ncol=3,nrow=0)\n times <- vector('integer',0L)\n\n # Getting the names\n tnames <- as.integer(dimnames(graph)[[3]])\n if (!length(tnames)) tnames <- 1:dim(graph)[3]\n\n for (i in 1:dim(graph)[3]) {\n x <- adjmat_to_edgelist.matrix(graph[,,i], undirected, keep.isolates)\n edgelist <- rbind(edgelist, x)\n times <- c(times, rep(tnames[i],nrow(x)))\n }\n\n return(cbind(edgelist, times=times))\n}\n\n# @rdname edgelist_to_adjmat\n# @export\nadjmat_to_edgelist.list <- function(graph, undirected, keep.isolates) {\n edgelist <- matrix(ncol=3,nrow=0)\n times <- vector('integer',0L)\n\n # Getting the names\n tnames <- as.integer(names(graph))\n if (!length(tnames)) tnames <- 1:dim(graph)[3]\n\n for (i in 1:length(graph)) {\n x <- adjmat_to_edgelist.dgCMatrix(graph[[i]], undirected, keep.isolates)\n edgelist <- rbind(edgelist, x)\n times <- c(times, rep(tnames[i],nrow(x)))\n }\n\n # # Adjusting the length\n # ids <- apply(edgelist, 1, paste0, collapse=\"\")\n # times <- as.integer(unname(tapply(times, ids, min)))\n #\n # edgelist <- unique(edgelist)\n # edgelist <- edgelist[order(edgelist[,1],edgelist[,2]),]\n\n return(cbind(edgelist, times=times))\n}\n\n# # Benchmark with the previous version\n# library(microbenchmark)\n# library(netdiffuseR)\n#\n# dat <- as.data.frame(cbind(edgelist, w))\n# colnames(dat) <- c('ego','alter','tie')\n# microbenchmark(\n# adjmatbuild(dat,n,1:n),\n# edgelist_to_adjmat(edgelist, w), times=100)\n#\n# old <- adjmatbuild(dat[,-3],n,1:n)\n# new <- (edgelist_to_adjmat(unique(edgelist), undirected = FALSE))[,,1]\n# arrayInd(which(old!=new), dim(old), dimnames(old))\n#\n# ## Dynamic\n# microbenchmark(\n# adjByTime(cbind(year=times,dat),n,max(times)),\n# edgelist_to_adjmat(edgelist, w, times), times=100)\n\n#' Time of adoption matrix\n#'\n#' Creates two matrices recording times of adoption of the innovation. One matrix\n#' records the time period of adoption for each node with zeros elsewhere. The\n#' second records the cumulative time of adoption such that there are ones for\n#' the time of adoption and every time period thereafter.\n#'\n#' @param obj Either an integer vector of size \\eqn{n} containing time of adoption of the innovation,\n#' or a \\code{\\link{diffnet}} object.\n#' @param labels Character vector of size \\eqn{n}. Labels (ids) of the vertices.\n#' @param t0 Integer scalar. Sets the lower bound of the time window (e.g. 1955).\n#' @param t1 Integer scalar. Sets the upper bound of the time window (e.g. 2000).\n#' @details\n#'\n#' In order to be able to work with time ranges other than \\eqn{1,\\dots, T}{1,..., T}\n#' the function receives as input the boundary labels of the time windows through\n#' the variables \\code{t0} and \\code{t}. While by default the function assumes that\n#' the the boundaries are given by the range of the \\code{times} vector, the user\n#' can set a personalized time range exceeding the one given by the \\code{times}\n#' vector. For instance, times of adoption may range between 2001 and 2005 but the\n#' actual data, the network, is observed between 2000 and 2005 (so there is not\n#' left censoring in the data), hence, the user could write:\n#'\n#' \\preformatted{\n#' adopmats <- toa_mat(times, t0=2000, t1=2005)\n#' }\n#'\n#' That way the resulting \\code{cumadopt} and \\code{adopt} matrices would have\n#' 2005 - 2000 + 1 = 6 columns instead of 2005 - 2001 + 1 = 5 columns, with the\n#' first column of the two matrices containing only zeros (as the first adoption\n#' happend after the year 2000).\n#' @examples\n#' # Random set of times of adoptions\n#' times <- sample(c(NA, 2001:2005), 10, TRUE)\n#'\n#' toa_mat(times)\n#'\n#' # Now, suppose that we observe the graph from 2000 to 2006\n#' toa_mat(times, t0=2000, t1=2006)\n#'\n#' @export\n#' @return A list of two \\eqn{n \\times T}{n x T}\n#' \\item{\\code{cumadopt}}{has 1's for all years in which a node indicates having the innovation.}\n#' \\item{\\code{adopt}}{has 1's only for the year of adoption and 0 for the rest.}\n#' @keywords manip\n#' @include graph_data.r\n#' @author George G. Vega Yon & Thomas W. Valente\ntoa_mat <- function(obj, labels=NULL, t0=NULL, t1=NULL) {\n\n if (!inherits(obj, \"diffnet\")) {\n if (!length(t0)) t0 <- min(obj, na.rm = TRUE)\n if (!length(t1)) t1 <- max(obj, na.rm = TRUE)\n }\n\n cls <- class(obj)\n ans <- if (\"numeric\" %in% cls) {\n toa_mat.numeric(obj, labels, t0, t1)\n } else if (\"integer\" %in% cls) {\n toa_mat.integer(obj, labels, t0, t1)\n } else if (\"diffnet\" %in% cls) {\n with(obj, list(adopt=adopt,cumadopt=cumadopt))\n } else\n stopifnot_graph(obj)\n\n\n if (inherits(obj, \"diffnet\")) {\n dimnames(ans$adopt) <- with(obj$meta, list(ids,pers))\n dimnames(ans$cumadopt) <- with(obj$meta, list(ids,pers))\n }\n\n\n return(ans)\n}\n\ntoa_mat.default <- function(per, t0, t1) {\n ans <- matrix(0L, ncol=t1-t0+1L, nrow=length(per))\n ans[cbind(1L:nrow(ans), per - t0 + 1L)] <- 1L\n\n list(\n adopt = ans,\n cumadopt = t(apply(ans, 1, cumsum))\n )\n}\n\n# @rdname toa_mat\n# @export\ntoa_mat.numeric <- function(times, labels=NULL,\n t0 = min(times, na.rm = TRUE),\n t1 = max(times, na.rm=TRUE)) {\n if (inherits(times, 'numeric')) warning('-x- numeric. will be coersed to integer.')\n\n # Coercing into integer\n times <- as.integer(times)\n t0 <- as.integer(t0)\n t1 <- as.integer(t1)\n\n toa_mat.integer(times, labels, t0, t1)\n}\n\n# @rdname toa_mat\n# @export\ntoa_mat.integer <- function(times, labels=NULL,\n t0 = min(times, na.rm = TRUE),\n t1 = max(times, na.rm=TRUE)) {\n # Rescaling\n output <- toa_mat.default(times, t0, t1)\n\n # Naming\n cn <- t0:t1\n if (length(labels)) rn <- labels\n else rn <- 1:length(times)\n\n dimnames(output[[1]]) <- list(rn, cn)\n dimnames(output[[2]]) <- list(rn, cn)\n\n output\n}\n\n# set.seed(123)\n# x <- sample(2000:2005, 10, TRUE)\n# y <- as.numeric(as.factor(x))\n#\n# new <- toa_mat(x)\n# old <- adoptMat(y)\n#\n# sum(new[[1]] - old[[1]])\n# sum(new[[2]] - old[[2]])\n#\n# microbenchmark(adoptMat(y), toa_mat_cpp(x), times=1000)\n# Unit: microseconds\n# expr min lq mean median uq max neval cld\n# adoptMat(y) 43.876 51.010 61.133262 53.002 55.9400 4070.201 10000 b\n# toa_mat_cpp(x) 4.620 6.226 7.921307 7.374 8.2605 114.874 10000 a\n\n#' Difference in Time of Adoption (TOA) between individuals\n#'\n#' Creates \\eqn{n \\times n}{n * n} matrix indicating the difference in times of adoption between\n#' each pair of nodes\n#' @inheritParams toa_mat\n#' @details Each cell ij of the resulting matrix is calculated as \\eqn{toa_j - toa_i}{%\n#' toa(j) - toa(i)}, so that whenever its positive it means that the j-th individual (alter)\n#' adopted the innovation sooner.\n#' @return An \\eqn{n \\times n}{n * n} symmetric matrix indicating the difference in times of\n#' adoption between each pair of nodes.\n#' @export\n#' @examples\n#' # Generating a random vector of time\n#' set.seed(123)\n#' times <- sample(2000:2005, 10, TRUE)\n#'\n#' # Computing the TOA differences\n#' toa_diff(times)\n#' @keywords manip\n#' @include graph_data.r\n#' @author George G. Vega Yon & Thomas W. Valente\ntoa_diff <- function(obj, t0=NULL, labels=NULL) {\n\n # Calculating t0 (if it was not provided)\n if (!inherits(obj, \"diffnet\") && !length(t0))\n t0 <- as.integer(min(obj, na.rm = TRUE))\n else\n t0 <- obj$meta$pers[1]\n\n # Computing the difference\n if (inherits(obj, \"integer\")) {\n out <- toa_diff_cpp(obj - t0 + 1L)\n } else if (inherits(obj, \"numeric\")) {\n warning(\"coercing -obj- to integer.\")\n out <- toa_diff_cpp(as.integer(obj) - t0 + 1L)\n } else if (inherits(obj, \"diffnet\")) {\n out <- toa_diff_cpp(obj$toa - t0 + 1L)\n } else stop(\"No method defined for class -\",class(obj),\"-\")\n\n out\n}\n\n# @rdname toa_diff\n# @export\ntoa_diff.integer <- function(times, t0, labels) {\n # Rescaling\n times <- times - t0 + 1L\n toa_diff_cpp(times)\n}\n\n\n\n# set.seed(123)\n# x <- sample(2000:2005, 10, TRUE)\n# toa_diff(x)\n#\n# microbenchmark(toaMat(x), toa_diff_cpp(x), times=1000)\n# Unit: microseconds\n# expr min lq mean median uq max neval cld\n# toaMat(x) 227.279 247.679 291.940566 272.4290 283.6845 3667.118 1000 b\n# toa_diff_cpp(x) 3.539 4.623 6.887954 6.3755 7.4645 54.817 1000 a\n# > 291.940566/6.887954\n# [1] 42.38422\n\n\n#' Find and remove isolated vertices\n#'\n#' Find and remove unconnected vertices from the graph.\n#' @templateVar undirected TRUE\n#' @template graph_template\n#' @templateVar undirected 1\n#' @templateVar self 1\n#' @export\n#' @return\n#' When \\code{graph} is an adjacency matrix:\n#' \\item{isolated}{an matrix of size \\eqn{n\\times 1}{n*1} with 1's where a node is isolated}\n#' \\item{drop_isolated}{a modified graph excluding isolated vertices.}\n#'\n#' Otherwise, when \\code{graph} is a list\n#' \\item{isolated}{an matrix of size \\eqn{n\\times T}{n*T} with 1's where a node is isolated}\n#' \\item{drop_isolated}{a modified graph excluding isolated vertices.}\n#' @examples\n#' # Generating random graph\n#' set.seed(123)\n#' adjmat <- rgraph_er()\n#'\n#' # Making nodes 1 and 4 isolated\n#' adjmat[c(1,4),] <- 0\n#' adjmat[,c(1,4)] <- 0\n#' adjmat\n#'\n#' # Finding isolated nodes\n#' iso <- isolated(adjmat)\n#' iso\n#'\n#' # Removing isolated nodes\n#' drop_isolated(adjmat)\n#'\n#'\n#' # Now with a dynamic graph\n#' graph <- rgraph_er(n=10, t=3)\n#'\n#' # Making 1 and 5 isolated\n#' graph <- lapply(graph, \"[<-\", i=c(1,5), j=1:10, value=0)\n#' graph <- lapply(graph, \"[<-\", i=1:10, j=c(1,5), value=0)\n#' graph\n#'\n#' isolated(graph)\n#' drop_isolated(graph)\n#' @keywords manip\n#' @family data management functions\n#' @author George G. Vega Yon\nisolated <- function(\n graph,\n undirected = getOption(\"diffnet.undirected\", FALSE),\n self = getOption(\"diffnet.self\", FALSE)\n) {\n cls <- class(graph)\n ans <- if (\"matrix\" %in% cls) {\n isolated.default(methods::as(graph, \"dgCMatrix\"), undirected, self)\n } else if (\"dgCMatrix\" %in% cls) {\n isolated.default(graph, undirected, self)\n } else if (\"array\" %in% cls) {\n lapply(apply(graph, 3, methods::as, Class=\"dgCMatrix\"), isolated.default,\n undirected=undirected, self=self)\n } else if (\"list\" %in% cls) {\n lapply(graph, isolated.default, undirected=undirected, self=self)\n } else if (\"diffnet\" %in% cls) {\n lapply(graph$graph, isolated.default, undirected=undirected, self=self)\n } else\n stopifnot_graph(graph)\n\n if (any(class(graph) %in% c(\"list\", \"diffnet\", \"array\")))\n apply(do.call(cbind, ans), 1, all)\n else ans\n # UseMethod(\"isolated\")\n}\n\n# @export\n# @rdname isolated\nisolated.default <- function(\n graph,\n undirected = getOption(\"diffnet.undirected\", FALSE),\n self = getOption(\"diffnet.self\", FALSE)\n) {\n\n graph@x <- rep(1.0, length(graph@x))\n d <- Matrix::rowSums(graph)\n if (undirected)\n d <- d + Matrix::colSums(graph)\n\n if (!self)\n d <- d - Matrix::diag(graph)\n\n unname(d == 0)\n}\n\nisolated.list <- function(\n graph,\n undirected = getOption(\"diffnet.undirected\", FALSE),\n self = getOption(\"diffnet.self\", FALSE)\n ) {\n\n ids <- lapply(graph, isolated.default, undirected=undirected, self=self)\n\n apply(do.call(cbind, ids), 1, all)\n\n}\n\n\n#' @export\n#' @rdname isolated\ndrop_isolated <- function(\n graph,\n undirected = getOption(\"diffnet.undirected\", FALSE),\n self = getOption(\"diffnet.self\", FALSE)\n) {\n\n # Find isolates\n ids <- which(!isolated(graph))\n\n if (inherits(graph, \"list\"))\n lapply(graph, \"[\", i=ids, j=ids, drop=FALSE)\n else if (inherits(graph, \"diffnet\"))\n graph[ids,]\n else if (inherits(graph, \"dgCMatrix\"))\n graph[ids,,drop=FALSE][,ids,drop=FALSE]\n else if (inherits(graph, \"array\"))\n graph[ids,,,drop=FALSE][,ids,,drop=FALSE]\n\n}\n\n\nsimmelian_mat <- function(graph, ...) {\n tmethod <- if(isS4(graph)) getMethod(\"t\", class(graph)) else t\n tmp <- graph & tmethod(graph)\n methods::as(tmp & (tmp %*% tmp), \"dgCMatrix\")\n}\n\n\n\n#' Approximate Geodesic Distances\n#'\n#' Computes approximate geodesic distance matrix using graph powers and keeping\n#' the amount of memory used low.\n#'\n#' @template graph_template\n#' @param n Integer scalar. Degree of approximation. Bigger values increase\n#' precision (see details).\n#' @param warn Logical scalar. When \\code{TRUE}, it warns if the algorithm\n#' performs less steps than required.\n#'\n#' @details\n#'\n#' While both \\pkg{igraph} and \\pkg{sna} offer very good and computationally\n#' efficient routines for computing geodesic distances, both functions return\n#' dense matrices, i.e. not sparse, which can be troublesome. Furthermore,\n#' from the perspective of social network analysis, path lengths of more than 6 steps,\n#' for example, may not be meaningful, or at least, relevant for the researcher.\n#' In such cases, \\code{approx_geodesic} serves as a solution to this problem,\n#' computing geodesics up to the number of steps, \\code{n}, desired, hence,\n#' if \\code{n = 6}, once the algorithm finds all paths of 6 or less steps it\n#' will stop, returning a sparse matrix with zeros for those pairs of\n#' vertices for which it was not able to find a path with less than \\code{n}\n#' steps.\n#'\n#' Depending on the graph size and density, \\code{approx_geodesic}'s performance\n#' can be compared to that of \\code{\\link[sna:geodist]{sna::geodist}}. Although,\n#' as \\code{n} increases, \\code{geodist} becomes a better alternative.\n#'\n#' The algorithm was implemented using power graphs. At each itereation i the\n#' power graph of order \\code{i} is computed, and its values are compared\n#' to the current values of the geodesic matrix (which is initialized in zero).\n#'\n#' \\enumerate{\n#' \\item Initialize the output \\code{ans(n, n)}\n#' \\item For \\code{i=1} to \\code{i < n} do\n#' \\enumerate{\n#' \\item Iterate through the edges of \\code{G^i}, if \\code{ans} has a zero\n#' value in the corresponding row+column, replace it with \\code{i}\n#' \\item next\n#' }\n#' \\item Replace all diagonal elements with a zero and return.\n#' }\n#'\n#' This implementation can be more memory efficient that the aforementioned ones,\n#' but at the same time it can be significant slower.\n#'\n#' \\code{approx_geodist} is just an allias for \\code{approx_geodesic}.\n#'\n#' @return A sparse matrix of class \\code{\\link[Matrix:dgCMatrix-class]{dgCMatrix}} of size\n#' \\code{nnodes(graph)^2} with geodesic distances up to \\code{n}.\n#'\n#' @examples\n#' # A very simple example -----------------------------------------------------\n#' g <- ring_lattice(10, 3)\n#' approx_geodesic(g, 6)\n#' sna::geodist(as.matrix(g))[[2]]\n#' igraph::distances(\n#' igraph::graph_from_adjacency_matrix(g, mode = \"directed\"),\n#' mode = \"out\"\n#' )\n#'\n#' @aliases Geodesic Shortest-Path\n#' @export\napprox_geodesic <- function(graph, n = 6L, warn=FALSE) {\n cls <- class(graph)\n\n if (\"dgCMatrix\" %in% cls) {\n approx_geodesicCpp(graph, n, warn)\n } else if (\"matrix\" %in% cls) {\n approx_geodesicCpp(methods::as(graph, \"dgCMatrix\"), n, warn)\n } else if (\"list\" %in% cls) {\n lapply(graph, approx_geodesicCpp, n = n, warn = warn)\n } else if (\"diffnet\" %in% cls) {\n lapply(graph$graph, approx_geodesicCpp, n = n, warn = warn)\n } else if (\"array\" %in% cls) {\n apply(graph, 3, approx_geodesicCpp, n = n, warn = warn)\n } else stopifnot_graph(graph)\n}\n\n#' @rdname approx_geodesic\n#' @export\napprox_geodist <- approx_geodesic\n", "meta": {"hexsha": "711433cbc6bcf2dedc54407438c437b184ef9cd6", "size": 27699, "ext": "r", "lang": "R", "max_stars_repo_path": "R/adjmat.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/adjmat.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/adjmat.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 33.1327751196, "max_line_length": 131, "alphanum_fraction": 0.6508899238, "num_tokens": 8373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.48313379369580556}} {"text": "library(scales)\n\n# set your folder\nsetwd(\"//Users//wayne//Documents//My research//0. Pop CSGLD//\")\n\n\n# total number of iterations\ntotal_iters = 1e6\n# learning rate for gradient Langevin dynamics\neta = 0.1 \n# temperature\nT = 1\n# hyperparameter\nzeta = 0.9\n# Total number of partitions\nparts = 100\n# Energy gap\ndiv = 1\n# Minimum energy for partition\nmin_energy = 0.15\n\n# build the energy function and the gradient\nenergy = function(x) return(-log(0.4 * dnorm(x, -6, 1) + 0.6 * dnorm(x, 4, 1)))\ngrad_f = function(x) return(numDeriv::grad(energy, x) + 0.03 * rnorm(1, 0, 1))\n\n# find the index for new samples\nfind_idx = function(sample) {\n stochastic_energy = energy(sample) + 0.03 * rnorm(1, 0, 1)\n return(min((as.integer((energy(sample) - min_energy) / div) + 1), parts-1))\n}\n\nrandom_field = function(theta, idx) {\n sub_random_field = -theta\n sub_random_field[idx] = sub_random_field[idx] + 1\n return(theta[idx] * sub_random_field)\n}\n\n# print process\nprint_progress = function(iter, total_iters) {\n if (iter %% (total_iters / 10) == 0) {\n print(paste('Iter ', scientific(iter, digits = 3), '/', total_iters,' completed'))\n }\n}\n\n\n# Since we are converging to a biased equilibrium that approximates the ground truth, we will not compare it and will only\n# focus on validate the reduction of variance\n############################################# Ground truth density of states #########################################\nparts_for_presentation = 11\n# simulate samples from the Gaussian mixture distribution\nreal_samples = c(rnorm(1e6 * 0.4, -6, 1), rnorm(1e6 * 0.6, 4, 1))\n# obtain the energy value for these samples\nenergy_each_sample = mapply(energy, real_samples)\n\n# establish energy partition\ngrids = seq(1, parts_for_presentation) * div + min_energy\n# compute density of states (ignore the first partition)\nreal_density_of_states = rep(0, (parts_for_presentation-1))\nfor (i in 1:(parts_for_presentation-1)) {\n real_density_of_states[i] = (sum(energy_each_sample <= grids[i+1]) - sum(energy_each_sample <= grids[i])) / 1e6\n}\n\n\n\nchains = 10\n######################################### ICSGLD (many short chains) ##############################################\ntheta_ICSGLD = c()\ncandidate_seeds = seq(1, 10)\nfor (seeds in candidate_seeds) {\n set.seed(seeds) \n print(paste(\"Run ICSGLD (many short chains) based on the random seed\", seeds))\n theta = rep(1, parts) / parts\n samples = rep(0, chains)\n indexs = rep(1, chains)\n for (iter in 1: total_iters) { \n decay = 1 / (iter^0.6 + 100)\n print_progress(iter, total_iters)\n # adaptive sampling part (parallelizable)\n for (cidx in 1: chains) {\n multiplier = 1 + zeta * T * (log(theta[indexs[cidx]+1]) - log(theta[indexs[cidx]])) / div \n samples[cidx] = samples[cidx] - eta * multiplier * grad_f(samples[cidx]) + sqrt(2 * eta * T) * rnorm(1, 0, 1)\n indexs[cidx] = find_idx(samples[cidx])\n }\n # interacting stochastic approximation\n interacting_random_field = 0\n for (cidx in 1: chains) {\n interacting_random_field = interacting_random_field + random_field(theta, indexs[cidx]) / chains\n }\n theta = theta + decay * interacting_random_field\n }\n # ignore the first empty partition where the minimum energy is around 1.42\n theta_ICSGLD = cbind(theta_ICSGLD, theta[2:parts_for_presentation])\n}\n\n######################################### CSGLD (a single long chain) ##############################################\ntheta_CSGLD = c()\nfor (seeds in candidate_seeds) {\n set.seed(seeds) \n print(paste(\"Run CSGLD (a single long chain) based on the random seed\", seeds))\n theta = rep(1, parts) / parts\n sample = 0\n idx = 1\n for (iter in 1: (total_iters*chains)) { \n decay = 1 / (iter^0.6 + 100)\n print_progress(iter, total_iters*chains)\n # adaptive sampling part\n multiplier = 1 + zeta * T * (log(theta[idx+1]) - log(theta[idx])) / div \n sample = sample - eta * multiplier * grad_f(sample) + sqrt(2 * eta * T) * rnorm(1, 0, 1)\n idx = find_idx(sample)\n theta = theta + decay * random_field(theta, idx)\n }\n # ignore the first empty partition where the minimum energy is around 1.42\n theta_CSGLD = cbind(theta_CSGLD, theta[2:parts_for_presentation])\n}\n\n\n\nlibrary(ggplot2)\n\nICSGLD_estimated_density_of_states = rowMeans(theta_ICSGLD)^zeta / sum(rowMeans(theta_ICSGLD)^zeta)\nCSGLD_estimated_density_of_states = rowMeans(theta_CSGLD)^zeta / sum(rowMeans(theta_CSGLD)^zeta)\n\n# we don't know the real equilibrium, we approximate it instead\nbiased_equilibrium = (ICSGLD_estimated_density_of_states + CSGLD_estimated_density_of_states) / 2\n\nwdata = cbind(CSGLD_estimated_density_of_states, ICSGLD_estimated_density_of_states, biased_equilibrium)\nddf = as.data.frame(wdata)\nddf$X = seq(1, length(ICSGLD_estimated_density_of_states))\nddf$ICSGLD_theta_upper = ddf$ICSGLD_estimated_density_of_states + 2 * apply(theta_ICSGLD, 1, sd) \nddf$ICSGLD_theta_lower = ddf$ICSGLD_estimated_density_of_states - 2 * apply(theta_ICSGLD, 1, sd)\nddf$CSGLD_theta_upper = ddf$CSGLD_estimated_density_of_states + 2 * apply(theta_CSGLD, 1, sd) \nddf$CSGLD_theta_lower = ddf$CSGLD_estimated_density_of_states - 2 * apply(theta_CSGLD, 1, sd) \n\n\nsub_p = ggplot(ddf, aes(X)) + \n geom_line(aes(y=ICSGLD_estimated_density_of_states, col=\"#7570B3\"), size=0.5) + \n geom_line(aes(y=CSGLD_estimated_density_of_states, col=\"#FF9999\"), size=0.5) + \n geom_line(aes(y=biased_equilibrium, col=\"black\"), size=1) + \n geom_ribbon(aes(ymin=ICSGLD_theta_lower,ymax=ICSGLD_theta_upper, x=X),alpha=0.3, fill=\"#7570B3\") + \n geom_ribbon(aes(ymin=CSGLD_theta_lower,ymax=CSGLD_theta_upper, x=X),alpha=0.3, fill=\"#FF9999\") + \n scale_x_continuous(name=\"Energy\") +\n scale_y_continuous(name=\"PDF in Energy (density of states)\") + \n scale_color_identity(name = \"Multipliers\",\n breaks = c(\"#7570B3\", \"#FF9999\", \"black\"),\n labels = c(\"ICSGLD xP10\", \"CSGLD xT10\", bquote(hat(theta)[\"*\"])),\n guide = \"legend\") +\n theme(legend.position=c(0.8, 0.2),\n legend.title = element_blank(),\n axis.title=element_text(size=20),\n legend.text = element_text(colour=\"grey15\", size=24),\n legend.key.size = unit(2,\"line\"),\n legend.key = element_blank(),\n legend.background = element_rect(fill=alpha('grey', 0.1)),\n axis.text.y = element_text(size=16),\n axis.text.x = element_text(size=16))\n\nprint(sub_p)\n\n\n", "meta": {"hexsha": "7fe332e24acd01a76c3258471dc406b164e2996e", "size": 6565, "ext": "r", "lang": "R", "max_stars_repo_path": "simulations/validation_of_reduced_variance.r", "max_stars_repo_name": "WayneDW/Interacting-Contour-Stochastic-Gradient-Langevin-Dynamics", "max_stars_repo_head_hexsha": "ecc073572d283895cf2629faf5522d83b23da1e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-21T20:22:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:21:52.000Z", "max_issues_repo_path": "simulations/validation_of_reduced_variance.r", "max_issues_repo_name": "WayneDW/Interacting-Contour-Stochastic-Gradient-Langevin-Dynamics", "max_issues_repo_head_hexsha": "ecc073572d283895cf2629faf5522d83b23da1e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/validation_of_reduced_variance.r", "max_forks_repo_name": "WayneDW/Interacting-Contour-Stochastic-Gradient-Langevin-Dynamics", "max_forks_repo_head_hexsha": "ecc073572d283895cf2629faf5522d83b23da1e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-23T14:45:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T17:14:57.000Z", "avg_line_length": 41.03125, "max_line_length": 123, "alphanum_fraction": 0.6528560548, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48303377093661654}} {"text": "LISP Interpreter Run\n\n[[[\n First steps with my new construction for\n a self-delimiting universal Turing machine.\n We show that\n H(x,y) <= H(x) + H(y) + c\n and determine c.\n Consider a bit string x of length |x|.\n We also show that\n H(x) <= 2|x| + c\n and that\n H(x) <= |x| + H(the binary string for |x|) + c\n and determine both these c's.\n]]]\n \n[\n Here is the self-delimiting universal Turing machine!\n]\ndefine (U p) cadr try no-time-limit 'eval read-exp p\n\ndefine U\nvalue (lambda (p) (car (cdr (try no-time-limit (' (eval \n (read-exp))) p))))\n\n(U bits 'cons x cons y cons z nil)\n\nexpression (U (bits (' (cons x (cons y (cons z nil))))))\nvalue (x y z)\n\n(U append bits 'cons a debug read-exp\n bits '(b c d)\n)\n\nexpression (U (append (bits (' (cons a (debug (read-exp))))) \n (bits (' (b c d)))))\ndebug (b c d)\nvalue (a b c d)\n\n[\n The length of alpha in bits is the\n constant c in H(x) <= 2|x| + 2 + c.\n]\ndefine alpha\nlet (loop) let x read-bit\n let y read-bit\n if = x y\n cons x (loop)\n nil\n(loop)\n\ndefine alpha\nvalue ((' (lambda (loop) (loop))) (' (lambda () ((' (lam\n bda (x) ((' (lambda (y) (if (= x y) (cons x (loop)\n ) nil))) (read-bit)))) (read-bit)))))\n\nlength bits alpha\n\nexpression (length (bits alpha))\nvalue 1104\n\n(U\n append\n bits alpha\n '(0 0 1 1 0 0 1 1 0 1)\n)\n\nexpression (U (append (bits alpha) (' (0 0 1 1 0 0 1 1 0 1)))\n )\nvalue (0 1 0 1)\n\n(U\n append\n bits alpha\n '(0 0 1 1 0 0 1 1 0 0)\n)\n\nexpression (U (append (bits alpha) (' (0 0 1 1 0 0 1 1 0 0)))\n )\nvalue out-of-data\n\n[\n The length of beta in bits is the\n constant c in H(x,y) <= H(x) + H(y) + c.\n]\ndefine beta\ncons eval read-exp\ncons eval read-exp\n nil\n\ndefine beta\nvalue (cons (eval (read-exp)) (cons (eval (read-exp)) ni\n l))\n\nlength bits beta\n\nexpression (length (bits beta))\nvalue 432\n\n(U\n append\n bits beta\n append\n bits 'cons a cons b cons c nil\n bits 'cons x cons y cons z nil\n)\n\nexpression (U (append (bits beta) (append (bits (' (cons a (c\n ons b (cons c nil))))) (bits (' (cons x (cons y (c\n ons z nil))))))))\nvalue ((a b c) (x y z))\n\n(U\n append\n bits beta\n append\n append bits alpha '(0 0 1 1 0 0 1 1 0 1)\n append bits alpha '(1 1 0 0 1 1 0 0 1 0)\n)\n\nexpression (U (append (bits beta) (append (append (bits alpha\n ) (' (0 0 1 1 0 0 1 1 0 1))) (append (bits alpha) \n (' (1 1 0 0 1 1 0 0 1 0))))))\nvalue ((0 1 0 1) (1 0 1 0))\n\n[\n The length of gamma in bits is the\n constant c in H(x) <= |x| + H(|x|) + c\n]\ndefine gamma\nlet (loop k)\n if = 0 k nil\n cons read-bit (loop - k 1)\n(loop base2-to-10 eval read-exp)\n\ndefine gamma\nvalue ((' (lambda (loop) (loop (base2-to-10 (eval (read-\n exp)))))) (' (lambda (k) (if (= 0 k) nil (cons (re\n ad-bit) (loop (- k 1)))))))\n\nlength bits gamma\n\nexpression (length (bits gamma))\nvalue 1024\n\n(U\n append\n bits gamma\n append\n [Arbitrary program for U to compute number of bits]\n bits' '(1 0 0 0)\n [That many bits of data]\n '(0 0 0 0 0 0 0 1)\n)\n\nexpression (U (append (bits gamma) (append (bits (' (' (1 0 0\n 0)))) (' (0 0 0 0 0 0 0 1)))))\nvalue (0 0 0 0 0 0 0 1)\n\nEnd of LISP Run\n\nElapsed time is 0 seconds.\n", "meta": {"hexsha": "8658c6892efc90015d256b4dbde1a4d0a3bb5214", "size": 3395, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/utm.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/utm.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/utm.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 20.8282208589, "max_line_length": 62, "alphanum_fraction": 0.5378497791, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.48275977898540406}} {"text": "#' @title calcKristWakeFrac\n#'\n#'@description Calculate wake fraction (\\code{wakeFraction}) (dimensionless)\n#'using the Kristensen method.\n#'\n#'@param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param lwl Waterline length (vector of numericals, m) (see\n#'\\code{\\link{calclwl}})\n#'@param Cbw Waterline block coefficient (vector of numericals, dimensionless)\n#'(see \\code{\\link{calcCbw}})\n#'@param propDiam Propeller diameter (vector of numericals, m) (see\n#'\\code{\\link{calcPropDia}})\n#'@param M Fineness/slenderness coefficient (vector of numericals,\n#'dimensionless) (see \\code{\\link{calcShipM}})\n#'@param nProp Number of propellers (vector of numericals, see\n#'\\code{\\link{calcPropNum}})\n#'@param tankerBulkCarrierShipTypes Ship types specified in input\n#'\\code{shipTypes} to be modeled as tankers and bulk carriers vessels (vector of\n#' strings)\n#'\n#' @return \\code{wakeFraction} (vector of numericals, dimensionless)\n#'\n#' @details\n#' \"The speed of advance of the propeller relative to the water in which it is working is\n#' lower than the observed speed of the vessel. This difference in speed,\n#' expressed as a percentage of the ship speed, is known as the wake fraction coefficient\".\n#' \\url{https://www.wartsila.com/encyclopedia/term/wake-fraction-coefficient}\n#'\n#'Wake fraction is a component of hull efficiency as well as a component of\n#'propeller efficiency.\n#'\n#' This method this requires ship types to be grouped. Use the\n#' \\code{tankerBulkCarrierShipTypes} grouping parameters to provide these ship\n#' type groupings. Any ship types not included in this grouping will be considered as\n#' miscellaneous vessels.\n#'\n#' @references\n#'Kristensen, H. O. and Lutzen, M. 2013. \"Prediction of Resistance and Propulsion\n#'Power of Ships.\"\n#'\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCbw}}\n#'\\item \\code{\\link{calcPropDia}}\n#'\\item \\code{\\link{calcShipM}}\n#'\\item \\code{\\link{calcPropNum}}\n#'\\item \\code{\\link{calcShipType}}}\n#'\n#' @family Kristensen Calculations\n#'\n#' @examples\n#' calcKristWakeFrac(\"bulk.carrier\",32.25,218.75, 0.8, 6.7,5.2, 1)\n#' calcKristWakeFrac(\"oil.tanker\",32.25,218.75, 0.8, 6.7,5.2, 1)\n#' calcKristWakeFrac(c(\"bulk.carrier\",\"container.ship\"),\n#' c(32.25,49),\n#' c(218.75,400),\n#' c(0.8,0.75),\n#' c(6.7,9.6),\n#' c(5.2,6.7),\n#' c(1,1))\n#'\n#' @export\n\ncalcKristWakeFrac <- function(shipType, breadth,lwl, Cbw, propDiam,M, nProp,\n tankerBulkCarrierShipTypes=c(\"tanker\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\")\n){\n\n wakeFraction<-ifelse(nProp==1,\n #a\n ((((0.1*breadth)/\n lwl)+0.149)+\n (\n #b\n (((0.05*breadth)/\n lwl)+0.449)/\n #c\n (\n (585-((5027*breadth)/\n lwl)+\n 11700*((breadth/\n lwl)^2)\n )*\n ((0.98-Cbw)^3)+1)))+\n # Assume w2 = 0 because we assume F_a = 0 where\n #F_a = [-2,0,2] and F_a=0 represents a N-shaped hull form\n #take this assumption for lack of better information\n #w3\n pmin(0.1,-0.18+(0.00756/((propDiam/lwl)+\n 0.002))),\n #nprop == 2 case\n 1.133*(Cbw^2)-0.797*Cbw+0.215\n )\n\n #apply adjustments from Kristensen, 2016 (to correct Harvald's algorithms toward data in more recent model tests)\n wakeFraction<-ifelse( (nProp==1) & ( shipType %in% tankerBulkCarrierShipTypes), #End of case definition\n (0.7*wakeFraction-0.45+0.08*M),#second case= container ships\n 0.7*wakeFraction\n )\n\n return(wakeFraction)\n\n}# end of function: calcWakeFrac\n", "meta": {"hexsha": "148ba7246dc9c5ba54381582dc816ac4f7e308d0", "size": 4200, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristWakeFrac.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcKristWakeFrac.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcKristWakeFrac.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 39.2523364486, "max_line_length": 152, "alphanum_fraction": 0.6076190476, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}} {"text": "#' Runs cross-validation of Random Forests classification\n#'\n#' @param x A matrix of numeric predictors\n#' @param y A factor or logical of responses\n#' @param nfolds number of cross-validation folds (nfolds==-1 means leave-one-out)\n#' @param folds optional, if not \\code{NULL} then uses these fold assignments (one fold index for each row in \\code{x})\n#' @param verbose Use verbose output\n#' @param ... additional parameters for randomForest\n#'\n#' @return\n#' \\item{y}{Observed values}\n#' \\item{predicted}{CV predicted values}\n#' \\item{probabilities}{CV predicted class probabilities (or NULL if unavailable)}\n#' \\item{confusion.matrix}{Confusion matrix (true-by-predicted)}\n#' \\item{nfolds}{Number of folds used (or -1 for leave-one-out)}\n#' \\item{params}{List of additional parameters, if any}\n#' \\item{importances}{Feature-by-fold matrix of importances of features (mean decrease in accuracy) across folds}\n#' \\item{final.model}{Final random forests model trained on whole data set}\n#' @examples\n#' # generate fake data: 50 samples, 20 variables\n#' x <- matrix(rnorm(2000),100)\n#' rownames(x) <- sprintf('Sample%02d',1:100)\n#' colnames(x) <- sprintf('Feature%02d',1:20)\n#' # generate fake response variable, function of columns 1-5 plus noise\n#' y <- rowSums(sweep(x[,1:5],2,runif(5),'*')) + rnorm(100,sd=.5)\n#' # y is now binary response variable\n#' y <- factor(y > median(y))\n#' names(y) <- rownames(x)\n#'\n#' # 10-fold cross validation, returning predictions\n#' res.rf <- rf.cross.validation(x,y2)\n#'\n#' # plot importance of top ten variables\n#' sorted.importances <- sort(rowMeans(res.rf$importances), decreasing=TRUE)\n#' barplot(rev(sorted.importances[1:10]),horiz=TRUE, xlab='Mean Decrease in Accuracy')\n#'\n#' # Plot classification ROC curve\n#' roc <- probabilities.to.ROC(res.rf$probabilities[,2], y2,plot=TRUE)\n#'\n#' # Report ROC AUC\n#' cat('ROC AUC was:',roc$auc,'\\n')\n#'\n\n\"rf.cross.validation\" <- function(x, y, nfolds=10, folds=NULL, verbose=FALSE, ...){\n require('randomForest')\n if(nfolds==-1) nfolds <- length(y)\n if(is.null(folds)) folds <- balanced.folds(y,nfolds=nfolds)\n result <- list()\n result$y <- as.factor(y)\n result$predicted <- result$y\n result$probabilities <- matrix(0, nrow=length(result$y), ncol=length(levels(result$y)))\n rownames(result$probabilities) <- rownames(x)\n colnames(result$probabilities) <- levels(result$y)\n result$importances <- matrix(0,nrow=ncol(x),ncol=nfolds)\n result$errs <- numeric(length(unique(folds)))\n\n # K-fold cross-validation\n for(fold in sort(unique(folds))){\n if(verbose) cat(sprintf('Fold %d...\\n',fold))\n foldix <- which(folds==fold)\n model <- randomForest(x[-foldix,], factor(result$y[-foldix]), importance=TRUE, do.trace=verbose, ...)\n newx <- x[foldix,,drop=F]\n if(length(foldix)==1) newx <- matrix(newx,nrow=1)\n result$predicted[foldix] <- predict(model, newx)\n probs <- predict(model, newx, type='prob')\n result$probabilities[foldix,colnames(probs)] <- probs\n result$errs[fold] <- mean(result$predicted[foldix] != result$y[foldix])\n result$importances[,fold] <- model$importance[,'MeanDecreaseAccuracy']\n }\n rownames(result$importances) <- colnames(x)\n result$err <- mean(result$predicted != result$y)\n result$nfolds <- nfolds\n result$params <- list(...)\n result$confusion.matrix <- t(sapply(levels(y), function(level) table(result$predicted[y==level])))\n\n # train one final model on the whole data set\n result$final.model <- randomForest(x,result$y)\n\n return(result)\n}\n\n#' Runs cross-validation of LARS regression\n#'\n#' @param x A matrix of numeric predictors\n#' @param y A factor or logical of responses\n#' @param nfolds number of cross-validation folds (nfolds==-1 means leave-one-out)\n#' @param folds optional, if not \\code{NULL} then uses these fold assignments (one fold index for each row in \\code{x})\n#' @param verbose Use verbose output\n#' @param ... additional parameters for lars\n#'\n#' @return:\n#' \\item{y}{Observed values}\n#' \\item{predicted}{CV predicted values}\n#' \\item{fractions}{Vector of LASSO fractions used across folds}\n#' \\item{best.fraction}{Best LASSO fraction used}\n#' \\item{MSE}{Mean squared error}\n#' \\item{RMSE}{Root mean squared error}\n#' \\item{nfolds}{Number of folds used (or -1 for leave-one-out)}\n#' \\item{params}{List of additional parameters, if any}\n#' \\item{coefficients}{Feature-by-fold matrix of coefficients of features across folds}\n#' \\item{final.model}{Final lars model trained on whole data set}\n#' @examples\n#' # generate fake data: 50 samples, 20 variables\n#' x <- matrix(rnorm(2000),100)\n#' rownames(x) <- sprintf('Sample%02d',1:100)\n#' colnames(x) <- sprintf('Feature%02d',1:20)\n#' # generate fake response variable, function of columns 1-5 plus noise\n#' y <- rowSums(sweep(x[,1:5],2,runif(5),'*')) + rnorm(100,sd=.5)\n#' names(y) <- rownames(x)\n#'\n#' # 10-fold cross validation with predictions\n#' res.lars <- lars.cross.validation(x,y)\n#' # plot predictions\n#' plot(res.lars$y, res.lars$predicted, xlab=\"Observed\", ylab=\"Predicted (hold-out)\")\n#'\n#' # correlation\n#' cat('Pearson correlation of predictions with truth?\\n')\n#' print(cor.test(res.lars$y, res.lars$predicted))\n#'\n#' # plot fraction of times each variable was included in a fold\n#' sorted.importances <- sort(rowMeans(res.lars$coefficients > 0), decreasing=TRUE)\n#' # bar plot of top ten variables\n#' par(mar=c(4.5,6,2,1),las=2) # larger margin on left, perpendicular axis labels\n#' barplot(rev(sorted.importances[1:10]),horiz=TRUE, xlab='Frequency of selection')\n#'\n\n\"lars.cross.validation\" <- function(x, y, nfolds=10, folds=NULL, verbose=FALSE, ...){\n require('lars')\n if(nfolds==-1) {\n nfolds <- length(y)\n folds <- 1:length(y)\n } else{\n folds <- sample(rep(1:nfolds,times=ceiling(length(y)/nfolds))[1:length(y)])\n }\n result <- list()\n result$y <- as.numeric(y)\n result$predicted <- result$y\n result$coefficients <- matrix(0,nrow=ncol(x),ncol=nfolds)\n result$fractions <- numeric(length(y))\n\n # K-fold cross-validation\n for(fold in sort(unique(folds))){\n if(verbose) cat(sprintf('Fold %d...\\n',fold))\n foldix <- which(folds==fold)\n\n # do cv.lars on the training set to choose the best penalty\n cv.res <- cv.lars(x[-foldix,], result$y[-foldix], plot.it=FALSE, ...)\n threshold <- cv.res$index[which.min(cv.res$cv)]\n res <- lars(x[-foldix,], result$y[-foldix])\n\n # predict on test set\n newx <- x[foldix,,drop=F]\n yhat <- predict(res, newx, mode='fraction',type='fit',s=threshold)$fit\n\n # extract results\n result$predicted[foldix] <- yhat\n result$coefficients[,fold] <- coef(res,mode='fraction',s=threshold)\n result$fractions[fold] <- threshold\n }\n rownames(result$coefficients) <- colnames(x)\n result$MSE <- mean((result$predicted - result$y)^2)\n result$RMSE <- sqrt(result$MSE)\n result$nfolds <- nfolds\n result$params <- list(...)\n result$best.fraction <- mean(result$fractions)\n\n # train one final model on the whole data set\n result$final.model <- lars(x,result$y)\n return(result)\n}\n\n\n#' Get balanced folds where each fold has close to overall class ratio. This only works for non-numeric inputs.\n#'\n#' @param y Vector of classes; should be a factor, logical, or character\n#' @param nfolds Number of folds. -1 means leave-one-out\n#' @return Numeric vector of fold indices, one for each element of \\code{y}\n\"balanced.folds\" <- function(y, nfolds=10){\n if(is.numeric(y)) stop(\"MWAS balanced.folds function only accepts non-numeric inputs.\")\n folds = rep(0, length(y))\n y <- as.factor(y)\n classes = levels(y)\n # size of each class\n Nk = table(y)\n # -1 or nfolds = len(y) means leave-one-out\n if (nfolds == -1 || nfolds == length(y)){\n invisible(1:length(y))\n }\n else{\n # Can't have more folds than there are items per class\n nfolds = min(nfolds, max(Nk))\n # Assign folds evenly within each class, then shuffle within each class\n for (k in 1:length(classes)){\n ixs <- which(y==classes[k])\n folds_k <- rep(1:nfolds, ceiling(length(ixs) / nfolds))\n folds_k <- folds_k[1:length(ixs)]\n folds_k <- sample(folds_k)\n folds[ixs] = folds_k\n }\n invisible(folds)\n }\n}\n\n\n\n\n#' Performs ROC analysis (and plot) on probability vector\n#'\n#' @param p Vector or probabilities of TRUE\n#' @param y Logical, factor, or character of TRUE/FALSE\n#' @param step.size Increments at which to calculate false and true positive rates\n#' @param plot If \\code{TRUE} then make a simple ROC curve plot.\n#' @param ... Additional parameters to pass to \\code{plot} function\n#' @return\n#' \\item{fprs}{Vector of false positive rates}\n#' \\item{tprs}{Vector of true positive rates}\n#' \\item{auc}{Area under the curve}\n\"probabilities.to.ROC\" <- function(p,y,step.size=0.01, plot=TRUE,...){\n require('flux')\n y <- as.logical(y)\n fprs <- sapply(seq(1,0,-abs(step.size)), function(xx) mean(p[!y] >= xx))\n tprs <- sapply(seq(1,0,-abs(step.size)), function(xx) mean(p[y] >= xx))\n tprs[fprs > tprs] <- fprs[fprs > tprs]\n auc.res <- auc(fprs, tprs)\n plot(fprs,tprs,type='l', xlab='False Positive Rate',ylab='True Positive Rate',...)\n\n return(list(fprs=fprs, tprs=tprs, auc=auc.res))\n}\n", "meta": {"hexsha": "b91d69cf998e469d174bdfd1e6327cb9f21a712d", "size": 9397, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cross-validation.r", "max_stars_repo_name": "knights-lab/MWAS", "max_stars_repo_head_hexsha": "92bb832507cc4894f2ca2bc7d096ec9cd2ab979a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-06T09:23:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T09:23:08.000Z", "max_issues_repo_path": "R/cross-validation.r", "max_issues_repo_name": "knights-lab/MWAS", "max_issues_repo_head_hexsha": "92bb832507cc4894f2ca2bc7d096ec9cd2ab979a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/cross-validation.r", "max_forks_repo_name": "knights-lab/MWAS", "max_forks_repo_head_hexsha": "92bb832507cc4894f2ca2bc7d096ec9cd2ab979a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-06T10:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-18T21:50:35.000Z", "avg_line_length": 41.0349344978, "max_line_length": 119, "alphanum_fraction": 0.6622326274, "num_tokens": 2633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4821466552673674}} {"text": "x <- c(-8, -3, 9)\r\npr_1 <- 4\r\npr_2 <- 2\r\npr_3 <- pr_1 + pr_2\r\n\r\n\r\n# Svolgimento\r\nlibrary(MASS)\r\nprint(0)\r\nprint(fractions(1/pr_3))\r\na <- x[3]/-(x[1]*pr_1 + x[2]*pr_2 + x[3]*(-pr_3))\r\nprint(fractions(a))\r\nprint(x[1]^2*(a*pr_1) + x[2]^2*(a*pr_2) + x[3]^2*(1-(a*pr_3)))", "meta": {"hexsha": "6b05708c86bea4e9ebfb91598c62d1c16d0f39de", "size": 266, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 36.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 36.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 36.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4615384615, "max_line_length": 62, "alphanum_fraction": 0.5263157895, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48214664878930397}} {"text": "# écriture de stochastic_model sans array\n# avec output true\n\n# endogènes -----------------\n## qpib pib en volume\n## vpib pib en valeur (mds euro)\n## og écart de production\n## ppib prix du pib\n## inf inflation\n## imp_dep, imp_po, imp_int décompositon de l'impulsion budgétaire en trois composantes\n## dépenses, recettes, et intérêt\n## dette dette publique, en valeur (mds euro)\n## tppdette dette publique en point de pib potentiel\n## dettep dette publique en point de pib\n## cha_int charge d'intérêt en valeur (mds euro)\n## tchaint charge d'intérêt en point de pib potentiel\n## r_app taux d'intérêt souverain national apparent (1% = 0.01)\n## r_inst taux d'intérêt souverain instantané (moyen année) (1% = 0.01)\n## gpot croissance potentielle en volume\n## aide de odin https://mrc-ide.github.io/odin/\n## tcho est le taux de chômage au sens du BIT \n## tvnairu est le NAIRU de AMECO tandis que Nairu est le chômage d'équilibre \n\n# exogènes --------------\n## dep_prim dépenses primaires en valeur\n## rec_po recettes fiscales (et non fiscales) en valeur (mds euro)\n## pibpot pib potentiel en volume\n\n# écart de production -------------------\nog <- lagog + dog\ndog <- og_lag * (lagog - lag2og) +\n - og_mce * (lagog - 0) + \n og_dep * ib_dep + \n og_po * ib_po + \n og_cin * ib_cin + \n og_noise + \n - og_ddpot * ((pibpot/lagpibpot-1)-(lagpibpot/lag2pibpot-1)) +\n - pot_r*(r_inst-lagr_inst)\n# on retarde de cette façon, cela permet de passer une condition initiale\nupdate(lagog) <- og\nupdate(lag2og) <- lagog\nupdate(og_noise) <- ogn_ar * og_noise + rnorm(0, ogn_sigma)\n\n# Taux de chômage -------------------\ntcho <- lagtcho - tcho_okun * dog - tcho_mce * (lagtcho+lagog-lagtvnairu)\nupdate(lagtcho) <- tcho\nupdate(lag2tcho) <- lagtcho\n\n# Dynamique du NAIRU -------------------\ntvnairu <- lagtvnairu - tvnairu_mce * (lagtvnairu - nairu)\nupdate(lagtvnairu) <- tvnairu\n\n# prix du pib -------------------\ntxppib <- lagtxppib + inf_lag * (lagtxppib - lag2txppib) - inf_mce * (lagtxppib - infstar + inf_tcho * (lagtcho - lagtvnairu))\nppib <- (1 + txppib)*lagppib\nupdate(lagppib) <- ppib\nupdate(lag2ppib) <- lagppib\nupdate(lag3ppib) <- lag2ppib\nlagtxppib <- lagppib/lag2ppib-1 \nlag2txppib <- lag2ppib/lag3ppib-1 \n\n# pib volume&valeur&potentiel -----------\npibpot <- lagpibpot*(1+(gpot[step]-1*((tvnairu-lagtvnairu)/(1-(tvnairu-i_lagtvnairu)))))\nupdate(lagpibpot) <- pibpot\nupdate(lag2pibpot) <- lagpibpot\nqpib <- (1 + og) * pibpot\nvpib <- qpib * ppib\nlagvpib <- lagqpib * lagppib\nlag2vpib <- lag2qpib * lag2ppib\nupdate(lagqpib) <- qpib\nupdate(lag2qpib) <- lagqpib\ngpib <- qpib/lagqpib-1\nupdate(laggpib) <- gpib\ngpot_v <- pibpot/lagpibpot-1\n\n# dette ------------\n# dette au 31 décembre\ndette <- lagdette + ddette + dette_oneoff[step]\nupdate(lagdette) <- dette\nupdate(lag2dette) <- lagdette\nlagdettep <- lagdette/lagvpib\nlag2dettep <- lag2dette/lag2vpib\nddette <- - rec_po + dep_prim + cin - taut[step] * vpib\n\n# taux d'intérêt ---------------\n#r_inst <- gpot[step] + lagtxppib + ecart_c + r_dette * (lagdettep - dstarr)\nr_inst <- gpot_v + infstar + ecart_c + r_dette * (lagdettep - dstarr)\nr_app <- (1-1/r_mat) * lagr_app + 1/r_mat * r_inst\nupdate(lagr_app) <- r_app\necart_c <- lagecart_c + decart_c\ndecart_c <- -ec_mce * (lagecart_c - ecstar)\nupdate(lagecart_c) <- ecart_c \nupdate(lagr_inst) <- r_inst \n\n# impulsion --------------\n# l'impulsion sur les dépenses est définie comme la variation du taux des dépenses par rapport au potentiel\ndep_prim <- tdeppp * ppib_dep * pibpot_dep\n\nppib_dep <- lagppib_dep*(1+ infdep_star*txppib + (1-infdep_star)*lagtxppib_dep - infdep_mce*(lagppib_dep/lagppib-1))\npibpot_dep <- lagpibpot_dep*(1+ potdep_star*gpot_v + (1-potdep_star)*lagtxpibpot_dep - potdep_mce*(lagpibpot_dep/lagpibpot-1))\n\n#pibpot_dep <- lagpibpot_dep*(1+(-((lag2pibpot_dep-lagpibpot_dep)/lag2pibpot_dep)-potdep_mce*(lagpibpot_dep/lagpibpot-1)))\nlagtxppib_dep <- (lagppib_dep-lag2ppib_dep)/lag2ppib_dep\nlagtxpibpot_dep <- (lagpibpot_dep-lag2pibpot_dep)/lag2pibpot_dep\n\nupdate(lagppib_dep) <- ppib_dep\nupdate(lag2ppib_dep) <- lagppib_dep\nupdate(lagpibpot_dep) <- pibpot_dep\nupdate(lag2pibpot_dep) <- lagpibpot_dep\nupdate(lagtdeppp) <- tdeppp\nupdate(lag2tdeppp) <- lagtdeppp\n\ntdepp_e <- dep_prim/pibpot/ppib\nupdate(lagtdepp_e) <- tdepp_e \n\n# l'impulsion sur les recettes est définie comme la variation du tpo\nrec_po <- tpo * vpib\nupdate(lagtpo) <- tpo\n\n# l'impulsion sur les intérêts (le multiplicateur est suceptible d'être nul (og_int))\n# charge d'intérêts nette de la part BC\ncin <- r_app * lagdette - dettebc * lagdette * r_bc\ncinp <- cin / vpib\nupdate(lagcinp) <- cinp\nupdate(lag2cinp) <- lagcinp\n\nib_cin <- lagcinp - lag2cinp\n\n# règle budgétaire --------------\nspp <- (rec_po - dep_prim)/vpib + taut[step]\nupdate(lagspp) <- spp\nupdate(lag2spp) <- lagspp\nspstar <- (ecart_c+r_dette*(dstar-dstarr))/(1+gpot_v+infstar) * dstar\n\nib_fr <- tpo_sstar * (lagspp - spstar) + tpo_1sstar * (lagspp - lag2spp) + tpo_sstar2 * (lagspp - spstar)^2 +\n tpo_dstar * (lagdettep - dstar) + tpo_1dstar * (lagdettep - lag2dettep) + tpo_dstar2 * (lagdettep - dstar)^2 +\n tpo_og*(lagog) + tpo_og2*(lagog)^2 + tpo_1og*(lagog - lag2og) +\n tpo_ec*(ecart_c - ecstar) +\n tpo_inf*(lagtxppib- infstar) +\n phi[step]\n\nib_sup <- max(min(ib_fr, ibcap), -ibcap)\n\nib_spont_dep <- tx_deriv_dep[step] * lagtdeppp +\n lagtdeppp * (lagppib_dep*lagpibpot_dep / lagpibpot / lagppib - lag2ppib_dep * lag2pibpot_dep/ lag2pibpot / lag2ppib)\nib_dep <- ib_spont_dep + (1-pcpo) * ib_sup \ntdeppp <- lagtdeppp + ib_dep\n\nib_spont_po <- - tx_deriv_po[step] * lagtpo\nib_po <- ib_spont_po + pcpo * ib_sup\ntpo <- lagtpo - ib_po\n\n# fonction de perte ----------------------\n# utilisée pour la partie optimisation\nupdate(loss_d_only) <- loss_d_only + loss_d * (step >= loss_t)*(lagdettep - dstar)^2\ninitial(loss_d_only) <- 0\nupdate(loss_no_d) <- loss_no_d + og^2/(1+loss_df)^(step-1) + loss_dog * (og-lagog)^2 + loss_ib * (ib_sup)^2\ninitial(loss_no_d) <- 0\n\n# sorties ------\n# dans dust c'est un peu capilotracté\n# sans output, on est obligé de faire un update()\n# et de définir une CI nulle\n# on pense ensuite à décaler les variables pour les utilisations\n# \nupdate(dettep_o) <- dette / vpib\nupdate(og_o) <- og\nupdate(txppib_o) <- ppib/lagppib-1\nupdate(gpib_o) <- qpib/lagqpib-1\nupdate(gpot_o) <- gpot_v\nupdate(spp_o) <- spp\nupdate(ci_o) <- cinp\nupdate(tpo_o) <- tpo\nupdate(tdep_o) <- tdepp_e * pibpot/qpib\nupdate(tdeppp_o) <- tdepp_e \nupdate(ib_dep_o) <- ib_dep\nupdate(ib_po_o) <- ib_po\nupdate(ib_o) <- ib_po + ib_dep\nupdate(qpib_o) <- qpib\nupdate(ppib_o) <- ppib\nupdate(tcho_o) <- tcho\nupdate(tvnairu_o) <- tvnairu\nupdate(spstar_o) <- spstar\nupdate(r_app_o) <- r_app\nupdate(loss_o) <- loss_no_d + loss_d_only\nupdate(loss_nd_o) <- loss_no_d\n\ninitial(txppib_o) <- 0\ninitial(gpib_o) <- 0\ninitial(gpot_o) <- 0\ninitial(spp_o) <- 0\ninitial(og_o) <- 0\ninitial(dettep_o) <- 0\ninitial(ci_o) <- 0\ninitial(tpo_o) <- 0\ninitial(tdep_o) <- 0\ninitial(ib_dep_o) <- 0\ninitial(ib_o) <- 0\ninitial(ib_po_o) <- 0\ninitial(qpib_o) <- 0\ninitial(ppib_o) <- 0\ninitial(tcho_o) <- 0\ninitial(tvnairu_o) <- 0\ninitial(tdeppp_o) <- 0\ninitial(spstar_o) <- 0\ninitial(r_app_o) <- 0\ninitial(loss_o) <- 0\ninitial(loss_nd_o) <- 0\n\n# init ----------------\ni_lagog <- user(0)\ni_lagtcho <- user(0)\ni_lag2tcho <- user(0)\ni_lagtvnairu <- user(0)\ni_lag2og <- user(0)\ni_lagqpib <- user(1)\ni_lag2qpib <- user(1)\ni_lag3qpib <- user(1)\ni_lagppib <- user(1)\ni_lag2ppib <- user(1)\ni_lag3ppib <- user(1)\ni_lagpibpot <- user(1)\ni_lag2pibpot <- user(1)\ni_lagtpo <- user(0.5)\ni_lagtdeppp <- user(0.5)\ni_lagr_app <- user(0.04)\ni_lagr_inst <- user(0.04)\ni_lagdette <- user(1)\ni_lagspp <- user(0.0)\ni_lag2spp <- user(0.0)\ni_lagecart_c <- user(0.0)\ni_ogn <- user(0) # rnorm(0, ogn_sigma)+ogn*(rnorm(0, ogn_sigma) + ogn*(rnorm(0, ogn_sigma)+ogn*rnorm(0, ogn_sigma)))\ni_lagcip <- user(0.02)\ni_lag2cip <- user(0.02)\ni_lag2dette <- user(1)\ni_lag2tdeppp <- user(0.5)\n\n## Initial conditions\n# initial(og) <- init_og\ninitial(lagog) <- i_lagog\ninitial(lag2og) <- i_lag2og\ninitial(lagtcho) <- i_lagtcho\ninitial(lag2tcho) <- i_lag2tcho\ninitial(lagtvnairu) <- i_lagtvnairu\ninitial(og_noise) <- i_ogn\ninitial(lagppib) <- i_lagppib\ninitial(lag2ppib) <- i_lag2ppib\ninitial(lag3ppib) <- i_lag3ppib\ninitial(lagppib_dep) <- i_lagppib\ninitial(lag2ppib_dep) <- i_lag2ppib\ninitial(lagqpib) <- i_lagqpib\ninitial(lag2qpib) <- i_lag2qpib\ninitial(laggpib) <- i_lag2qpib/i_lag3qpib - 1\ninitial(lagpibpot) <- i_lagpibpot\ninitial(lagpibpot_dep) <- i_lagpibpot\ninitial(lag2pibpot_dep) <- i_lag2pibpot\ninitial(lag2pibpot) <- i_lag2pibpot\ninitial(lagtpo) <- i_lagtpo\ninitial(lagtdepp_e) <- i_lagtdeppp\ninitial(lagtdeppp) <- i_lagtdeppp\ninitial(lag2tdeppp) <- i_lag2tdeppp\ninitial(lagr_app) <- i_lagr_app\ninitial(lagr_inst) <- i_lagr_inst\ninitial(lagdette) <- i_lagdette\ninitial(lag2dette) <- i_lag2dette\ninitial(lagspp) <- i_lagspp\ninitial(lag2spp) <- i_lag2spp\ninitial(lagcinp) <- i_lagcip\ninitial(lag2cinp) <- i_lag2cip\ninitial(lagecart_c) <- i_lagecart_c\n\n# params -------------\nperiods <- user(50)\n\n## parameters\nog_lag <- user(0)\nog_mce <- user(0.29)\nog_ddpot <- user(0.29)\ntvnairu_mce <- user(0.13)\ntcho_okun <- user(0.33)\ntcho_mce <- user(0.27)\ninf_tcho <- user(0.1)\ninf_lag <- user(0.0)\ninf_mce <- user(0.68)\ninfdep_mce <- user(0.5)\ninfdep_star <- user(0.5)\npotdep_star <- user(0.5)\npotdep_mce <- user(0.5)\npot_r <- user(0.15)\nog_dep <- user(0.7)\nog_po <- user(0.7)\nog_cin <- user(0)\ninfstar <- user(0.0175)\nr_mat <- user(8)\ndstar <- user(0.6)\ndstarr <- user(0.6)\nnairu <- user(0.07)\ntpo_sstar <- user(0.4)\ntpo_dstar <- user(0.1)\ntpo_sstar2 <- user(0)\ntpo_1sstar <- user(0)\ntpo_dstar2 <- user(0)\ntpo_1dstar <- user(0)\ntpo_1og <- user(0)\ntpo_og <- user(0)\ntpo_og2 <- user(0)\ntpo_ec <- user(0)\ntpo_inf <- user(0)\npcpo <- user(1)\nloss_df <- user(0.02)\nloss_ib <- user(0)\nogn_ar <- user(0)\nogn_sigma <- user(0.005)\nr_dette <- user(0.01)\nibcap <- user(0.01)\necstar <- user(-0.015)\nec_mce <- user(0.1)\ndettebc <- user(0)\nr_bc <- user(0)\n\n# loss\nloss_dog <- user(0)\nloss_d <- user(0.5)\nloss_t <- user(20)\n\n# controls&exogenes -----------\ndette_oneoff[] <- user(0)\nphi[] <- user(0)\ntaut[] <- user(0)\ngpot[] <- user(0)\ntx_deriv_dep[] <- user(0)\ntx_deriv_po[] <- user(0)\n\ndim(dette_oneoff) <- periods\ndim(phi) <- periods\ndim(gpot) <- periods\ndim(taut) <- periods\ndim(tx_deriv_dep) <- periods\ndim(tx_deriv_po) <- periods", "meta": {"hexsha": "39da5a9b0f8128004f6af99ca7ede8560463f519", "size": 10369, "ext": "r", "lang": "R", "max_stars_repo_path": "odin/dwrstochasticmodel.r", "max_stars_repo_name": "OFCE/debtwatchR", "max_stars_repo_head_hexsha": "53c71e386c923dae0d98c90c79d65e3605b018d2", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-10-19T21:52:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T19:33:06.000Z", "max_issues_repo_path": "odin/dwrstochasticmodel.r", "max_issues_repo_name": "OFCE/dwr", "max_issues_repo_head_hexsha": "53c71e386c923dae0d98c90c79d65e3605b018d2", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "odin/dwrstochasticmodel.r", "max_forks_repo_name": "OFCE/dwr", "max_forks_repo_head_hexsha": "53c71e386c923dae0d98c90c79d65e3605b018d2", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.587020649, "max_line_length": 126, "alphanum_fraction": 0.6888803163, "num_tokens": 4092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4820548366433472}} {"text": "#==============================================\n# functions\n#----------------------------------------------\n# reworked function to speed up the bootstrap analysis\n\n\n#----------------------------------------------------\n# Make Tables with specified categoriges\n# Enables fixed format output and zero entries\n#----------------------------------------------------\n\nTable <- function(x,Labels){\n #=c(\"D614\",\"G614\") ){\n xx <- rep(0, length(Labels) )\n names(xx) <- Labels\n xx.t <- table( x )\n xx[ names(xx.t) ] <- xx.t\n return(xx)\n}\n\n#=================================================================\n# Compute isotonic logistic regression, using the pava rountine\n# from Iso \n# Input: yy matrix of successes, failures, ordered in time\n# decreasing = F\n# theta initial value, default is zero\n# err L1 error on estimated probs. Recommended 10e-5\n# eps numerical stability for prob going to 0 or 1\nIsoLog <- function(Y,decreasing=F,theta=0,err=1e-5,min.w=1e-6){\n G <- 1\n theta0 <- theta\n pp <- exp(theta0)/(1+exp(theta0))\n \n yy <- Y[,1]\n nn <- apply(Y,1,sum)\n \n while ( G > err ){\n ww <- nn*pmax( pp*(1-pp), min.w ) # ensure the weights are always larger than eps\n zz <- theta0 + (yy-nn*pp)/ww\n theta1 <- pava(zz,ww,decreasing=decreasing)\n p1 <- exp(theta1)/(1+exp(theta1))\n G <- sum( abs(p1-pp) )\n #\n theta0 <- theta1\n pp <- p1\n }\n return(theta1)\n}\n\n\n#===================================================================================\n# fit a Ashaped \nAshape <- function(Y,lmode,theta=0,err=1e-5,min.w=1e-6){\n G <- 1\n theta0 <- theta\n pp <- exp( theta0)/( 1+exp(theta0) )\n \n yy <- Y[,1]\n nn <- apply(Y,1,sum)\n iidx <- (1:length(yy)) < (lmode+1)\n\n while ( G > err ){\n ww <- nn*pmax( pp*(1-pp), min.w ) # ensure the weights are always larger than eps\n zz <- theta0 + (yy-nn*pp)/ww\n theta1 <- pava(zz[iidx],ww[iidx],decreasing=F)\n theta2 <- pava(zz[!iidx],ww[!iidx],decreasing=T)\n ttheta <- c(theta1,theta2)\n p1 <- exp(ttheta)/(1+exp(ttheta))\n G <- sum( abs(p1-pp) )\n #\n theta0 <- ttheta\n pp <- p1\n }\n loglik <- sum(yy*log(pp) + (nn-yy)*log(1-pp))\n return( list( theta=theta0,p=pp,loglik=loglik ) )\n}\n\nAshape2 <- function(Y,Lmode=c(1,dim(Y)[1]),theta=0,err=1e-6,min.w=1e-6){\n lmode <- Lmode[1]:Lmode[2]\n Ffit <- vector(\"list\",length = length(lmode)) \n Ffit[[1]] <- Ashape(Y,lmode[1],theta)\n for ( k in 2:length(lmode) ){\n Ffit[[k]] <- Ashape(Y,lmode=lmode[k],Ffit[[k-1]]$theta)\n }\n iidx <- which.max(sapply(Ffit, FUN=function(x) x$loglik))\n return( list( theta=Ffit[[iidx]]$theta, \n p=Ffit[[iidx]]$p,\n loglik=Ffit[[iidx]]$loglik,\n mode = lmode[iidx] ) )\n}\n\n#===================================================================\n# Function to compute from one bootstrap sample\n# To be used in parallel\n# input: empty vector, needed to get it to run in parallel\n# y vector of 0-1\n# ddate: vector of dates\n# p0: probability under the null distribution\n# Decreasing: test decresing? T=yes, F=no\n# Labels: vector of labels to be used in Table\n#===================================================================\nBoot.Pval <- function(zz,yy,ddates,p0,Decreasing=F,Labels=c(\"M\",\"W\")){\n \n y.b <- sample(yy, replace = F) # permutation of strain labels\n ddt.b <- split(y.b,ddates) # split by date\n BB.b <- t( sapply( ddt.b , Table, Labels=Labels ) ) \n \n ffit.b <- IsoLog( as.matrix( BB.b ), decreasing=Decreasing)\n p.b <- exp(ffit.b)/(1+exp(ffit.b))\n \n # calculate relative loglikelihood\n LL <- sum( BB.b[,1]*log(p.b/p0) + BB.b[,2]*log((1-p.b)/(1-p0)) )\n \n return(LL)\n \n }\n", "meta": {"hexsha": "e448d1b0f8f74038f66232043a8f5a5a87bfc2fb", "size": 3735, "ext": "r", "lang": "R", "max_stars_repo_path": "isotonic/myfunctions_v3.r", "max_stars_repo_name": "eeg-lanl/sarscov2-selection", "max_stars_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isotonic/myfunctions_v3.r", "max_issues_repo_name": "eeg-lanl/sarscov2-selection", "max_issues_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isotonic/myfunctions_v3.r", "max_forks_repo_name": "eeg-lanl/sarscov2-selection", "max_forks_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9230769231, "max_line_length": 86, "alphanum_fraction": 0.5078982597, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48205040433610324}} {"text": "# Start point bias plots\n # Set overlap values\n overlaps <- seq(0,1.5,0.025)\n # Run RRW based on overlaps and bias\n # Unbiased start point\n unbiased <- getMomentsOfRRWoverlap(overlaps,boundary=10, startValue=0, loops = 500,noiseSD = 2)\n #Positive start point bias\n posbias1 <- getMomentsOfRRWoverlap(overlaps,boundary=10, startValue=0.25, loops = 500,noiseSD = 2)\n posbias2 <- getMomentsOfRRWoverlap(overlaps,boundary=10, startValue=0.50, loops = 500,noiseSD = 2)\n # Negative start point bias\n negbias1 <- getMomentsOfRRWoverlap(overlaps,boundary=10, startValue= -0.25, loops = 500,noiseSD = 2)\n negbias2 <- getMomentsOfRRWoverlap(overlaps,boundary=10, startValue= -0.50, loops = 500,noiseSD = 2)\n\n # Generate plot found in paper\n with(unbiased[unbiased$correct==T,],plot(pCross ~ overlap, pch=16, col=\"black\",frame.plot=F,xlab=\"Overlap\",ylab=\"pHO\",ylim=c(0,1),las=1,cex=0.75,xaxt='n'))\n abline(0.5,0,lty=2)\n abline(v=1,lty=2)\n axis(1, at = seq(0, 1.5, by = .1), las=2)\n with(posbias1[posbias1$correct==T,],points(pCross ~ overlap, pch=16, col=\"sky blue\",cex=0.75))\n with(posbias2[posbias2$correct==T,],points(pCross ~ overlap, pch=16, col=\"blue\",cex=0.75))\n with(negbias1[negbias1$correct==T,],points(pCross ~ overlap, pch=16, col=\"light pink\",cex=0.75))\n with(negbias2[negbias2$correct==T,],points(pCross ~ overlap, pch=16, col=\"red\",cex=0.75))\n legend(0.2,0.4, legend=c(\"0.50\",\"0.25\",\"0 (unbiased)\",\"-0.25\",\"-0.50\"),title=\"Start Point\",col=c(\"blue\", \"skyblue\",\"black\",\"light pink\",\"red\"),pch=16,cex=0.75)\n # Write to a pdf\n dev.copy(pdf,\"pHVOxOverlapVal.pdf\")\n dev.off()\n", "meta": {"hexsha": "26cfa07970ae291b84899f6719af54e4e6b8a3c1", "size": 1680, "ext": "r", "lang": "R", "max_stars_repo_path": "StartPointBiasSimulation.r", "max_stars_repo_name": "ccpluncw/ccpl_data_DDsim_2022", "max_stars_repo_head_hexsha": "22b949d85d4458663063b5ed53259e9747887bfd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StartPointBiasSimulation.r", "max_issues_repo_name": "ccpluncw/ccpl_data_DDsim_2022", "max_issues_repo_head_hexsha": "22b949d85d4458663063b5ed53259e9747887bfd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StartPointBiasSimulation.r", "max_forks_repo_name": "ccpluncw/ccpl_data_DDsim_2022", "max_forks_repo_head_hexsha": "22b949d85d4458663063b5ed53259e9747887bfd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.2222222222, "max_line_length": 166, "alphanum_fraction": 0.6613095238, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.48200001324405856}} {"text": "#########################################################\n#install.packages(\"argparse\")\nlibrary(argparse)\nlibrary(mdatools)\nparser <- ArgumentParser()\n\nparser$add_argument(\"--file\", type=\"character\", default= \"no_input_return_error\",\n help=\"file containing variant frequencies\")\nparser$add_argument(\"--plot_bool\", type=\"logical\", default= FALSE,\n help=\"determines whether pdf plot approx_plot.pdf is produced or not\")\nparser$add_argument(\"--var_calling_threshold\", type=\"double\", default= 0.03,\n help=\"variant calling threshold\")\nparser$add_argument(\"--Nb_min\", type=\"integer\", default= 1,\n help=\"Minimum bottleneck value considered\")\nparser$add_argument(\"--Nb_max\", type=\"integer\", default= 200,\n help=\"Maximum bottleneck value considered\")\nparser$add_argument(\"--confidence_level\", type=\"double\", default= .95,\n help=\"Confidence level (determines bounds of confidence interval)\")\nargs <- parser$parse_args()\nif (args$file == \"no_input_return_error\" ) { stop(\"file with lists of donor and recipient frequencies is a required argument.\", call.=FALSE)}\n \nplot_bool <- args$plot_bool\nvar_calling_threshold <- args$var_calling_threshold\nNb_min <- args$Nb_min # Minimum bottleneck size we consider. \nNb_max <- args$Nb_max\nconfidence_level <- args$confidence_level\ndonor_and_recip_freqs_observed <- read.table(args$file) #donor_freqs_observed <- read.table(args[1])\ndonor_freqs_observed <- as.data.frame(donor_and_recip_freqs_observed[, 1]) # We read in and save the list of donor frequencies\nrecipient_freqs_observed <- as.data.frame(donor_and_recip_freqs_observed[, 2]) # We read in and save the list of recipient frequencies\nn_variants <- nrow(donor_and_recip_freqs_observed)#nrow(donor_freqs_observed) # number of variants \n\n#######################################################\n#######################################################\ngenerate_log_likelihood_function_approx <- function(donor_freqs_observed, recipient_freqs_observed, Nb_min, Nb_max, var_calling_threshold, confidence_level)\n{\n\n num_NB_values <- Nb_max -Nb_min + 1\nlikelihood_matrix <- matrix( 0, n_variants, num_NB_values)#This matrix stores the likelihood values for each variant frequency and bottleneck size. \nlog_likelihood_matrix <- matrix( 0, n_variants, num_NB_values)#This matrix stores the log likelihood values for each variant frequency and bottleneck size. We can sum the log likelihoods of all the variant alleles to get the total log likelihood. \nlog_likelihood_function <- matrix( 0, Nb_max )\n\n\nfor (i in 1:n_variants) {for (j in 1:num_NB_values) {\n Nb_val <- (j - 1 + Nb_min)\n nu_donor <- donor_freqs_observed[i, 1]\n nu_recipient <- recipient_freqs_observed[i, 1]\n if (recipient_freqs_observed[i, 1] >= var_calling_threshold)\n { # implement variant calling threshold\n\nfor (k in 0:Nb_val){ \n likelihood_matrix[i, j] <- likelihood_matrix[i, j] + \n (dbeta(nu_recipient, k, (Nb_val - k))*dbinom(k, size=Nb_val, prob= nu_donor)) \n }\n log_likelihood_matrix[i,j] = log(likelihood_matrix[i, j]) \n }\n if (recipient_freqs_observed[i, 1] < var_calling_threshold)\n { # implement variant calling threshold\n \n likelihood_matrix[i, j] = 0\n log_likelihood_matrix[i,j] = 0\n for (k in 0:Nb_val){ likelihood_matrix[i, j] <- likelihood_matrix[i, j] + \n (pbeta(var_calling_threshold, k, (Nb_val - k))*dbinom(k, size=Nb_val, prob= nu_donor)) \n } \nlog_likelihood_matrix[i,j] = log(likelihood_matrix[i, j])\n }\n# Now we sum over log likelihoods of the variants at different loci to get the total log likelihood for each value of Nb\nlog_likelihood_function[ Nb_val] <- log_likelihood_function[ Nb_val] + log_likelihood_matrix[i,j]\n# Shifting entries of log_likelihood function to ensure plot begins at proper point on x axis\n}}\n\n\nreturn(log_likelihood_function)\n\n}\n#################################################################\n#################################################################\nrestrict_log_likelihood <- function(log_likelihood_function, Nb_min, Nb_max) # restricts log likelihood to the interval of interst\n{\nfor (h in 1:(Nb_min )){ \n if(h< Nb_min)\n {log_likelihood_function[h] = - 999999999} # kludge for ensuring that these values less than Nb_min don't interfere with our search for the max of log likelihood in the interval of Nb_min to Nb_max\n }\n\nreturn(log_likelihood_function)\n#print(erfinv(percent_confidence_interval)*sqrt(2))\n}\n\n\nreturn_bottleneck_size <- function(log_likelihood_function, Nb_min, Nb_max)\n{ max_log_likelihood = which(log_likelihood_function == max(log_likelihood_function))\n\n return(max_log_likelihood)\n}\n\n\nreturn_CI_lower <- function(log_likelihood_function, Nb_min, Nb_max) ## returns lower bound of confidence interval\n { max_log_likelihood = which(log_likelihood_function == max(log_likelihood_function)) ## This is the point on the x-axis (bottleneck size) at which log likelihood is maximized\nmax_val = max(log_likelihood_function) ## This is the maximum value of the log likelihood function, found when the index is our bottleneck estimate\nCI_height = max_val - erfinv(confidence_level)*sqrt(2) # This value ( height on y axis) determines the confidence intervals using the likelihood ratio test\n\n\n CI_index_lower = Nb_min\n CI_index_upper = max_log_likelihood\nfor (h in 1:Nb_min){ \n if(h< Nb_min)\n {log_likelihood_function[h] = NA} # Removing parameter values less than Nb_min from plot\n }\n## above loop just enforces our minimum bottleneck cutoff\nfor (h in Nb_min:max_log_likelihood){ \n test1 = (log_likelihood_function[CI_index_lower] - CI_height) * (log_likelihood_function[CI_index_lower] - CI_height)\n test2 = (log_likelihood_function[h] - CI_height) * (log_likelihood_function[h] - CI_height)\n if( test2 < test1){ CI_index_lower = h } \n}\nif( (log_likelihood_function[CI_index_lower] - CI_height) > 0 ){CI_index_lower = CI_index_lower - 1 } \n# above loops use likelihood ratio test to find lower confidence interval\nfor (h in max_log_likelihood:Nb_max)\n{ test1 = (log_likelihood_function[CI_index_upper] - CI_height) * (log_likelihood_function[CI_index_upper] - CI_height)\n test2 = (log_likelihood_function[h] - CI_height) * (log_likelihood_function[h] - CI_height)\n if( test2 < test1 ){CI_index_upper = h } \n}\nif( (log_likelihood_function[CI_index_upper] - CI_height) > 0 ){CI_index_upper = CI_index_upper + 1 } \n \n return(CI_index_lower)\n\n }\n\n\nreturn_CI_upper <- function(log_likelihood_function, Nb_min, Nb_max) ## returns upper bound of confidence interval\n { max_log_likelihood = which(log_likelihood_function == max(log_likelihood_function)) ## This is the point on the x-axis (bottleneck size) at which log likelihood is maximized\n max_val = max(log_likelihood_function) ## This is the maximum value of the log likelihood function, found when the index is our bottleneck estimate\n CI_height = max_val - erfinv(confidence_level)*sqrt(2) # This value ( height on y axis) determines the confidence intervals using the likelihood ratio test\n\n CI_index_lower = Nb_min\n CI_index_upper = max_log_likelihood\nfor (h in 1:Nb_min){ \n if(h< Nb_min)\n {log_likelihood_function[h] = NA} # Removing parameter values less than Nb_min from plot\n }\n## above loop just enforces our minimum bottleneck cutoff\nfor (h in Nb_min:max_log_likelihood){ \n test1 = (log_likelihood_function[CI_index_lower] - CI_height) * (log_likelihood_function[CI_index_lower] - CI_height)\n test2 = (log_likelihood_function[h] - CI_height) * (log_likelihood_function[h] - CI_height)\n if( test2 < test1){ CI_index_lower = h } \n}\nif( (log_likelihood_function[CI_index_lower] - CI_height) > 0 ){CI_index_lower = CI_index_lower - 1 } \n# above loops use likelihood ratio test to find lower confidence interval\nfor (h in max_log_likelihood:Nb_max)\n{ test1 = (log_likelihood_function[CI_index_upper] - CI_height) * (log_likelihood_function[CI_index_upper] - CI_height)\n test2 = (log_likelihood_function[h] - CI_height) * (log_likelihood_function[h] - CI_height)\n if( test2 < test1 ){CI_index_upper = h } \n}\nif( (log_likelihood_function[CI_index_upper] - CI_height) > 0 ){CI_index_upper = CI_index_upper + 1 } \n \n return(CI_index_upper)\n\n }\n\n\nlog_likelihood_function <- generate_log_likelihood_function_approx(donor_freqs_observed, recipient_freqs_observed, Nb_min, Nb_max, var_calling_threshold, confidence_level)\nlog_likelihood_function <- restrict_log_likelihood(log_likelihood_function, Nb_min, Nb_max)\nbottleneck_size <- return_bottleneck_size(log_likelihood_function, Nb_min, Nb_max)\nCI_index_lower <- return_CI_lower(log_likelihood_function, Nb_min, Nb_max)\nCI_index_upper <- return_CI_upper(log_likelihood_function, Nb_min, Nb_max)\n \n ##########################\n############################################################################################## ABOVE THIS LINE DETERMINES PEAK LOG LIKELIHOOD AND CONFIDENCE INTERVALS\n # Npw we plot the result\nif(plot_bool == TRUE)\n{pdf(file=\"approx_plot.pdf\")\nplot(log_likelihood_function)\nabline(v = bottleneck_size, col=\"black\" ) # Draws a verticle line at Nb value for which log likelihood is maximized\nabline(v = CI_index_lower, col=\"green\" ) # confidence intervals\nabline(v = CI_index_upper, col=\"green\" )\ndev.off()\n}\n\nprint(\"Bottleneck size\")\nprint(bottleneck_size)\nprint(\"confidence interval left bound\")\nprint(CI_index_lower)\nprint(\"confidence interval right bound\")\nprint(CI_index_upper)", "meta": {"hexsha": "44d892861818326d6b11f5261253ccf3ce8e8bbd", "size": 9567, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/secondary_analysis/betaBinomial/Bottleneck_size_estimation_approx.r", "max_stars_repo_name": "JosephLalli/ORCHARDS", "max_stars_repo_head_hexsha": "1fc4d27121683e77edd02303e9ecd3d8d4caeb1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/secondary_analysis/betaBinomial/Bottleneck_size_estimation_approx.r", "max_issues_repo_name": "JosephLalli/ORCHARDS", "max_issues_repo_head_hexsha": "1fc4d27121683e77edd02303e9ecd3d8d4caeb1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/secondary_analysis/betaBinomial/Bottleneck_size_estimation_approx.r", "max_forks_repo_name": "JosephLalli/ORCHARDS", "max_forks_repo_head_hexsha": "1fc4d27121683e77edd02303e9ecd3d8d4caeb1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5659340659, "max_line_length": 248, "alphanum_fraction": 0.719138706, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4819580705725635}} {"text": "#' @title\n#' Reduced-rank ridge regression with rank and tuning parameter selected by cross validation\n#'\n#' @description\n#' This function performs reduced-rank ridge regression with the rank and the\n#' tuning parameter selected by cross validation.\n#'\n#' @usage\n#' RRS.cv(Y, X, nfold = 10, rankmax = min(dim(Y), dim(X)), nlam = 100,\n#' lambda = seq(0, 100, length = nlam), norder = NULL,\n#' nest.tune = FALSE, fold.drop = 0)\n#'\n#' @param Y response matrix.\n#' @param X design matrix.\n#' @param nfold the number of folds used in cross validation. Default is 10.\n#' @param rankmax the maximum rank allowed.\n#' @param nlam the number of tuning parameter candidates. Default is 100.\n#' @param lambda the tuning sequence of length \\code{nlam}.\n#' @param norder a vector of length n that assigns samples to multiple folds\n#' for cross validation. Default is NULL and then \\code{norder} will be\n#' generated randomly.\n#' @param nest.tune a logical value to specify whether to tune the rank and lambda\n#' in a nested way. Default is FALSE.\n#' @param fold.drop the number of folds to drop. Default is 0.\n#'\n#'\n#' @return The function returns a list:\n#' \\item{cr_path}{a matrix displays the path of model selection.}\n#' \\item{C}{the estimated low-rank coefficient matrix.}\n#' \\item{rank}{the selected rank.}\n#' \\item{lam}{the selected tuning parameter for ridge penalty.}\n#'\n#' @references Mukherjee, A., & Zhu, J. (2011).\n#' Reduced Rank Ridge Regression and Its Kernel Extensions.\n#' Statistical analysis and data mining,\n#' 4(6), 612–622.\n#'\n# @importFrom rrpack rrs.fit\n#' @export\nRRS.cv<-function(Y, X, nfold = 10, rankmax = min(dim(Y), dim(X)), nlam = 100,\n lambda = seq(0, 100, length = nlam), norder = NULL, nest.tune = FALSE,\n fold.drop = 0)\n{\n p <- ncol(X)\n q <- ncol(Y)\n n <- nrow(Y)\n ndel <- round(n/nfold)\n if (is.null(norder)) {\n norder <- sample(1:n, n)\n }\n cr_path <- array(dim = c(nlam, rankmax + 1, nfold), NA)\n for (f in 1:nfold) {\n if (f != nfold) {\n iddel <- norder[(1 + ndel * (f - 1)):(ndel * f)]\n }\n else {\n iddel <- norder[(1 + ndel * (f - 1)):n]\n }\n ndel <- length(iddel)\n nf <- n - ndel\n Xf <- X[-iddel, ]\n Xfdel <- X[iddel, ]\n Yf <- Y[-iddel, ]\n Yfdel <- Y[iddel, ]\n for (ll in 1:nlam) {\n ini <- rrs.fit(Yf, Xf, lambda = lambda[ll], nrank = rankmax)\n C_ls <- ini$coef.ls\n A <- ini$A\n tempFit <- Xfdel %*% C_ls\n tempC <- matrix(nrow = nrow(A), ncol = nrow(A), 0)\n for (i in 1:rankmax) {\n tempC <- tempC + A[, i] %*% t(A[, i])\n cr_path[ll, i + 1, f] <- sum((Yfdel - tempFit %*%\n tempC)^2)\n }\n cr_path[ll, 1, f] <- sum(Yfdel^2)\n }\n }\n index <- order(apply(cr_path, 3, sum))[1:ifelse(nfold > 5,\n nfold - fold.drop, nfold)]\n crerr <- apply(cr_path[, , index], c(1, 2), sum)/length(index) *\n nfold\n minid <- which.min(crerr)\n minid2 <- ceiling(minid/nlam)\n rankest <- minid2 - 1\n minid1 <- minid - nlam * (minid2 - 1)\n if (nest.tune == TRUE) {\n lambda <- exp(seq(log(lambda[max(minid1 - 1, 1)] + 1e-04),\n log(lambda[min(minid1 + 1, nlam)]), length = nlam))\n cr_path <- array(dim = c(nlam, rankmax + 1, nfold), NA)\n ndel <- round(n/nfold)\n for (f in 1:nfold) {\n if (f != nfold) {\n iddel <- norder[(1 + ndel * (f - 1)):(ndel *\n f)]\n }\n else {\n iddel <- norder[(1 + ndel * (f - 1)):n]\n ndel <- length(iddel)\n }\n nf <- n - ndel\n Xf <- X[-iddel, ]\n Xfdel <- X[iddel, ]\n Yf <- Y[-iddel, ]\n Yfdel <- Y[iddel, ]\n for (ll in 1:nlam) {\n ini <- rrs.fit(Yf, Xf, lambda = lambda[ll], nrank = rankmax)\n C_ls <- ini$coef.ls\n A <- ini$A\n tempFit <- Xfdel %*% C_ls\n tempC <- matrix(nrow = nrow(A), ncol = nrow(A),\n 0)\n for (i in 1:rankmax) {\n tempC <- tempC + A[, i] %*% t(A[, i])\n cr_path[ll, i + 1, f] <- sum((Yfdel - tempFit %*%\n tempC)^2)\n }\n cr_path[ll, 1, f] <- sum(Yfdel^2)\n }\n }\n index <- order(apply(cr_path, 3, sum))[1:ifelse(nfold >\n 5, nfold - fold.drop, nfold)]\n crerr <- apply(cr_path[, , index], c(1, 2), sum)/length(index) *\n nfold\n minid <- which.min(crerr)\n minid2 <- ceiling(minid/nlam)\n rankest <- minid2 - 1\n minid1 <- minid - nlam * (minid2 - 1)\n }\n if (rankest == 0) {\n list(cr_path = cr_path, CRE = crerr, norder = norder,\n C = matrix(nrow = p, ncol = q, 0), rank = 0)\n }\n else {\n fit <- rrs.fit(Y, X, lambda = lambda[minid1], nrank = rankmax)\n C_lslam <- fit$coef.ls\n A <- fit$A\n list(cr_path = cr_path, CRE = crerr, ID = c(minid1, minid2),\n norder = norder, C = C_lslam %*% A[, 1:rankest] %*%\n t(A[, 1:rankest]), rank = rankest, lam = lambda[minid1])\n }\n}\n", "meta": {"hexsha": "d6be385352b546fec205723f11a2579c7f3b9faf", "size": 5116, "ext": "r", "lang": "R", "max_stars_repo_path": "R/RRRRcv_NRRR.r", "max_stars_repo_name": "xliu-stat/NRRR", "max_stars_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/RRRRcv_NRRR.r", "max_issues_repo_name": "xliu-stat/NRRR", "max_issues_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/RRRRcv_NRRR.r", "max_forks_repo_name": "xliu-stat/NRRR", "max_forks_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7762237762, "max_line_length": 92, "alphanum_fraction": 0.5277560594, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.48190009694242886}} {"text": "# <-- encoding UTF-8 -->\n# Empirical study on NHSS dataset (county level)\n# -------------------------------------\n## DOC STRING\n# \n# \n# Tianhao Zhao (GitHub: Clpr)\n# Dec 2018\n# -------------------------------------\n\n# -------------------------------------\n## SECTION 0: ENVIRONMENT\nlibrary(sqldf) # sql enquiry\nlibrary(openxlsx) # easy xlsx IO\nsource(\"./src/mathtools.r\") # math tools, e.g. Lorenz, Theil, descriptive stats\nsource(\"./src/mapplots.r\") # tools of map plots, using ggplot2\n# environment par dict\nenvNHSS$Output <- \"./output/proc_2_NHSS/\" # alter output directory\n\n\n\n# -------------------------------------\n## SECTION 1: GENERAL DESCRIPTIVE STATISTICS\ncat(\"\\nGeneral descriptive statistics of NHSS dataset:\\n\")\ncat(\"(please note: the income now is the residuals of income ~ edu)\\n\")\ncat(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\ncat(\"PLEASE NOTE: because we have normalized PCA components, we only do descriptive statistics for income & edu!!!!!!\")\ncat(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n# --------------\nli_Descript_NHSS <- list() # a list of descriptive statistics\nfor(tmpYname in envNHSS$Ynames){\n # 1.1 get a namelist of all numeric variables, both Y and Xcore\n tmp <- c( tmpYname, envNHSS$Xcore )\n li_Descript_NHSS[[tmpYname]] <- func_DescrStat( li_Dat_NHSS[[tmpYname]][,tmp] )\n # 1.2 print\n print(li_Descript_NHSS[[tmpYname]]); cat(\"-----------------------------------------\\n\")\n}\n# output to xlsx\nopenxlsx::write.xlsx(li_Descript_NHSS, paste(sep=\"\",envNHSS$Output,\"Descript_NHSS.xlsx\") )\n\n\n\n\n\n\n# -------------------------------------\n## SECTION 2: COUNTY-LEVEL LORENZ CURVE & GINI COEF\n# NOTE: in this section, we use counties as units/individuals to plot Lorenz curves in every year (98,03,08),\n# meanwhile, Gini coefficients in the three years are calculated;\n# later, in following sections, we will add other inequlity indices\n\n# 2.0 prepare a df for Gini coefs\ndf_Gini_NHSS <- data.frame(\n year = c(1998, 2003, 2008), # years\n counties = c( sum(df_NHSS$year == 1998),sum(df_NHSS$year == 2003),sum(df_NHSS$year == 2008) ), # number of counties in every year's data\n illnessratio = NA, # prevalence\n illnessday = NA,\n chronicratio = NA\n)\n\n# 2.1 use functions in mathtools.r to compute Lorenz Curve & Gini coefficients\n# NOTE: please refer to mathtools.r for how we calculated the both\n# and, if you want to see the plotting of Lorenz Curve, you may DIY (using tmp$LorenzX and tmp$LorenzY)\nfor(tmpYear in df_Gini_NHSS$year){\n for(tmpYname in envNHSS$Ynames){\n # 2.1.1 compute Lorenz Curve & Gini in specific year\n # eval(parse(text=paste(sep=\"\",\n # \"tmp <- LorenzCurve( df_NHSS$\",tmpYname,\"[df_NHSS$\",envNHSS$flagT,\" == \",tmpYear,\"] )\"\n # ))) \n tmp <- li_Dat_NHSS[[tmpYname]]\n tmp <- LorenzCurve( tmp[ tmp[,envNHSS$flagT] == tmpYear ,tmpYname] )\n # 2.1.2 save Gini coef\n df_Gini_NHSS[,tmpYname][df_Gini_NHSS$year == tmpYear] <- tmp$GiniIdx\n }\n}\n# print & output to xlsx\nprint(df_Gini_NHSS)\n\n\n# NOTE: the results will be output to a csv file with other kinds of indices, later\n\n\n\n# -------------------------------------\n## SECTION 3: COUNTY-LEVEL THEIL I & II INDEXES\n# NOTE: in this section, we use counties as units/individuals to calculate Theil-I & Theil-II indexes.\n# meanwhile, indices in the three years are calculated;\n# later, in following sections, we will add other inequlity indices\n\n# 3.0 prepare two df\ndf_Theil1_NHSS <- data.frame(\n year = c(1998, 2003, 2008), # years\n counties = c( sum(df_NHSS$year == 1998),sum(df_NHSS$year == 2003),sum(df_NHSS$year == 2008) ), # number of counties in every year's data\n illnessratio = NA, # prevalence\n illnessday = NA,\n chronicratio = NA\n)\ndf_Theil2_NHSS <- df_Theil1_NHSS\n\n# 3.1 use functions in mathtools.r to do computing\nfor(tmpYear in df_Gini_NHSS$year){ # loop on years\n for(tmpYname in envNHSS$Ynames){ # loop on health outcomes\n # slice a temp dataset\n tmpdf <- li_Dat_NHSS[[tmpYname]]\n # 3.1.1 compute Theil-I & Theil-II in a specific year\n tmp <- Theil( tmpdf[,tmpYname][tmpdf[,envNHSS$flagT] == tmpYear], Type = \"T\" )\n df_Theil1_NHSS[,tmpYname][ df_Theil1_NHSS$year == tmpYear ] <- tmp\n tmp <- Theil( tmpdf[,tmpYname][tmpdf[,envNHSS$flagT] == tmpYear], Type = \"L\" )\n df_Theil2_NHSS[,tmpYname][ df_Theil2_NHSS$year == tmpYear ] <- tmp\n }\n}\n\n# 3.2 print info\ncat(\"\\nThe county-level Theil-I type index in every year of NHSS dataset are:\\n\")\nprint(df_Theil1_NHSS)\ncat(\"\\nThe county-level Theil-II type index in every year of NHSS dataset are:\\n\")\nprint(df_Theil2_NHSS)\n\n# NOTE: the results will be output to a csv file with other kinds of indices, later\n\n\n\n\n\n# -------------------------------------\n## SECTION 4: COUNTY-LEVEL COEF OF VARIANCE (C.V.) & VARIANCE\n# NOTE: in this section, we use counties as units/individuals to calculate C.V. & variances\n# meanwhile, indices in the three years are calculated;\n\n# 4.0 prepare two df\ndf_CoefVar_NHSS <- data.frame(\n year = c(1998, 2003, 2008), # years\n counties = c( sum(df_NHSS$year == 1998),sum(df_NHSS$year == 2003),sum(df_NHSS$year == 2008) ), # number of counties in every year's data\n illnessratio = NA, # prevalence\n illnessday = NA,\n chronicratio = NA\n)\ndf_Variance_NHSS <- df_CoefVar_NHSS\n\n# 4.1 calculation\nfor(tmpYear in df_Gini_NHSS$year){ # loop on years\n for(tmpYname in envNHSS$Ynames){ # loop on health outcomes\n # slice a temp dataset\n tmpdf <- li_Dat_NHSS[[tmpYname]]\n # 4.1.1 get data vector\n tmp <- tmpdf[,tmpYname][ tmpdf[,envNHSS$flagT] == tmpYear ]\n df_Variance_NHSS[,tmpYname][df_Variance_NHSS$year == tmpYear] <- var(tmp)\n df_CoefVar_NHSS[,tmpYname][df_CoefVar_NHSS$year == tmpYear] <- sd(tmp) / mean(tmp)\n }\n}\n\n# 4.2 print info\ncat(\"\\nThe county-level coef of variance in every year of NHSS dataset are:\\n\")\nprint(df_CoefVar_NHSS)\ncat(\"\\nThe county-level variances in every year of NHSS dataset are:\\n\")\nprint(df_Variance_NHSS)\n\n\n\n\n\n# -------------------------------------\n## SECTION 5: COLLECT INEQUALITY INDICES & OUTPUT TO CSV\n# NOTE: in this section, we firstly bind all kinds of inequality indices to a single dframe,\n# then, output the large dframe to a csv file\n\n# 5.1 table joining\ndf_InequalIdx_NHSS <- data.frame( Index = rep(c(\"Gini\",\"Theil-I\",\"Theil-II\",\"Variance\",\"Coef of Variance\"), each = 3) )\ndf_InequalIdx_NHSS <- cbind(\n df_InequalIdx_NHSS, rbind( df_Gini_NHSS, df_Theil1_NHSS, df_Theil2_NHSS, df_Variance_NHSS, df_CoefVar_NHSS )\n)\n# 5.2 garbage recycling\nrm( df_Gini_NHSS, df_Theil1_NHSS, df_Theil2_NHSS, df_Variance_NHSS, df_CoefVar_NHSS )\nrm( tmpYear, tmpYname, tmpdf )\n# 5.3 output to csv\nwrite.csv( df_InequalIdx_NHSS, file = paste(sep=\"\",envNHSS$Output,\"InequalityIdx_NHSS.csv\") )\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# -------------------------------------\n## INTERVAL: MATCH CITY GIS DATA WITH NHSS DATASET\n# NOTE: in this section, we merge the China city/County GIS data with df_NHSS;\n# the data have been preloaded by mapplots.r, and named as MapGIScity;\n# in the next section, the dataset will be used to plot\n# NOTE: we do not plot PCs -> health outcomes, therefore, just use df_NHSS!\ntmpdf <- plyr::join( df_NHSS, MapGIScity[,c(\"ID\",\"long\",\"lat\")], by = \"ID\" ) # we use GB (country standard) codes of city/county to match by\ntmpdf <- na.omit(tmpdf)\n\n\ncat(\"\\nPlotting ...\\n\")\n# -------------------------------------\n## SECTION 6: COLORED MAPS OF HEALTH OUTCOMES\n# NOTE: in this section, we plot colored maps for every health outcomes,\n# where every health outcome (in three years) are seen as a pool data,\n# to see the (geographic) distribution (descriptively, intuitively) of the outcomes;\n# using ggplot2, and tools in mapplots.r\n# finally, we output these maps/figures to PDF figures\n# NOTE: please refer to mapplots.r for more information & technical details\n# NOTE: in final plots, the size of circle indicates the values of independents, where the color indicates the values of health outcomes\n# the plots work to display the relationship between X & Y\n# --------\n# 6.1 colored maps\n# 1998,2003,2008 data are now seen as a pool dataset\nfor(tmpYname in envNHSS$Ynames){\n # 6.1.1 temp slice: pooled health outcome & province tags\n tmp <- tmpdf[,c(tmpYname,envNHSS$flagProv, \"ID\", \"long\", \"lat\" )]\n # # 6.1.2 averaging by procinve tags (weighted by sample size/population of each county)\n # tmp <- sqldf::sqldf(paste(sep=\"\",\n # \"SELECT DISTINCT SUM(\",envNHSS$flagSampleSize,\" * \",tmpYname,\") / SUM(\",envNHSS$flagSampleSize,\") AS \",tmpYname,\n # \", \",envNHSS$flagProv,\" FROM tmp GROUP BY \",envNHSS$flagProv\n # ))\n # 6.1.3 using mapplots.r to get an instance of current map figure\n # eval(parse(text=paste(sep=\"\",\n # \"tmpfig <- func_MapProv( tmp$\",tmpYname,\", tmp$\",envNHSS$flagProv,\", vecName = \\\"\",tmpYname,\"\\\" )\"\n # )))\n # income -> health outcome\n tmpfig1 <- func_MapCityXY( tmpdf$income, tmpdf[,tmpYname], tmpdf$lat, tmpdf$long, \n Xname = \"income\", Yname = tmpYname , FontSize = 5,\n ColorScale = c(\"skyblue\",\"red\"), CircleScale = c(2,15) )\n # edu -> health outcome\n tmpfig2 <- func_MapCityXY( tmpdf$edu, tmpdf[,tmpYname], tmpdf$lat, tmpdf$long, \n Xname = \"edu\", Yname = tmpYname , FontSize = 5,\n ColorScale = c(\"skyblue\",\"red\"), CircleScale = c(2,15) )\n # output figures\n eval(parse(text=paste(sep=\"\",\n \"func_SaveMap2PDF( tmpfig1, \\\"\",envNHSS$Output,\"Map_income_2_\",tmpYname,\".pdf\\\" ) \"\n )))\n eval(parse(text=paste(sep=\"\",\n \"func_SaveMap2PDF( tmpfig2, \\\"\",envNHSS$Output,\"Map_edu_2_\",tmpYname,\".pdf\\\" ) \"\n )))\n}\n\n# 6.2 print info\ncat(\"\\n We have created colored maps for health outcomes and output them to the assigned output directory as PDF figures\\n\")\n\n\n\n\n\n\n\n\n# --------------------------------------\n# GARBAGE COLLECTION\nrm( tmp, tmpfig1, tmpfig2, tmpYname, tmpdf )\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# \n# # -------------------------------------\n# ## SECTION 7: COLORED MAPS OF CORE INDEPENDENTS (INCOME & EDU)\n# # NOTE: please refer to mapplots.r for more information & technical details\n# \n# # 7.1 colored maps\n# # 1998,2003,2008 data are now seen as a pool dataset\n# for(tmpXname in envNHSS$Xcore){\n# # 7.1.1 temp slice: pooled health outcome & province tags\n# tmp <- df_NHSS[,c(tmpXname,envNHSS$flagProv,envNHSS$flagSampleSize)]\n# # 7.1.2 averaging by procinve tags\n# tmp <- sqldf::sqldf(paste(sep=\"\",\n# \"SELECT DISTINCT SUM(\",envNHSS$flagSampleSize,\" * \",tmpXname,\") / SUM(\",envNHSS$flagSampleSize,\") AS \",tmpXname,\n# \", \",envNHSS$flagProv,\" FROM tmp GROUP BY \",envNHSS$flagProv\n# ))\n# # 7.1.3 using mapplots.r to get an instance of current map figure\n# eval(parse(text=paste(sep=\"\",\n# \"tmpfig <- func_MapProv( tmp$\",tmpXname,\", tmp$\",envNHSS$flagProv,\", vecName = \\\"\",tmpXname,\"\\\" )\"\n# )))\n# # 7.1.4 output figures\n# eval(parse(text=paste(sep=\"\",\n# \"func_SaveMap2PDF( tmpfig, \\\"\",envNHSS$Output,\"Map_\",tmpXname,\".pdf\\\" ) \"\n# )))\n# }\n# \n# # 7.2 print info\n# cat(\"\\nWe have created colored maps for core independents (income & edu) and output them to the assigned output directory as PDF figures\\n\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f162fecfad0b687fe89fcefb814882a5f9bee349", "size": 11558, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/proc_2_NHSS.r", "max_stars_repo_name": "Clpr/HealthInequality2018Dec", "max_stars_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/proc_2_NHSS.r", "max_issues_repo_name": "Clpr/HealthInequality2018Dec", "max_issues_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/proc_2_NHSS.r", "max_forks_repo_name": "Clpr/HealthInequality2018Dec", "max_forks_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1952662722, "max_line_length": 144, "alphanum_fraction": 0.6252811905, "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4818636026880351}} {"text": "#' @title calcShipCategory\n#'\n#' @description\n#' Assigns EPA regulatory ship category from engine displacement\n#'\n#' @param mainEngineBore Diameter of the main engine cylinder (mm) (vector of\n#' numericals)\n#' @param mainEngineStroke Main engine stroke length, the distance travelled by\n#' the piston in each cycle (mm) (vector of numericals)\n#'\n#'@details\n#'For more information, see Section 3.3.2.1 of the Port Emissions Inventory\n#'Guidance.\n#'\n#' @return \\code{shipCategory} (vector of ints). Valid values are: \\itemize{\n#' \\item 1\n#' \\item 2\n#' \\item 3\n#' }\n#'\n#' @references\n#'\\href{https://nepis.epa.gov/Exe/ZyPURL.cgi?Dockey=P1005ZGH.TXT}{EPA. 2009.\n#'\"Regulatory impact analysis: Control of emissions air pollution from category\n#'3 marine diesel engines.\" Ann Arbor, MI: Office of Transportation and Air\n#'Quality. US Environmental Protection Agency.}\n#'\n#'\\href{https://nepis.epa.gov/Exe/ZyPDF.cgi/?Dockey=P10024CN.PDF}{EPA. 2008.\n#'\"Regulatory impact analysis: Control of emissions of air pollution from\n#'locomotive engines and marine compression ignition engines less than 30 liters\n#'per cylinder.\" Ann Arbor, MI: Office of Transportation and Air\n#'Quality. US Environmental Protection Agency.}\n#'\n#' \\href{https://nepis.epa.gov/Exe/ZyPDF.cgi?Dockey=P10102U0.pdf}{EPA. 2020.\n#' \"Port Emissions Inventory Guidance: Methodologies for Estimating\n#' Port-Related and Goods Movement Mobile Source Emissions.\" Ann Arbor, MI:\n#' Office of Transportation and Air Quality. US Environmental Protection Agency.}\n#'\n#' @examples\n#' calcShipCategory(400, 240)\n#'\n#' @export\n\n\ncalcShipCategory<- function(mainEngineBore, mainEngineStroke){\n\n# Calculate displacement in L/cyl\n main.engine.displacement <- ((pi / 4) * (mainEngineBore/10) ^ 2 *\n (mainEngineStroke / 10)) / 1000\n\n# Categorize Ships (C1/C2/C3)\nshipCategory <- ifelse(main.engine.displacement>= 30, 3,\n ifelse(main.engine.displacement >= 7, 2,\n ifelse(main.engine.displacement > 0 , 1,\n NA)))\nreturn(shipCategory)\n}\n", "meta": {"hexsha": "777279cf288de73a2a8b4c65956199d3faf25598", "size": 2134, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipEF/R/calcShipCategory.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipEF/R/calcShipCategory.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipEF/R/calcShipCategory.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 37.4385964912, "max_line_length": 81, "alphanum_fraction": 0.6855670103, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48173878659085523}} {"text": "require(expm)\nrequire(survival)\n\ndyn.load(\"lk_rec.so\")\ndyn.load(\"lk_rec_surv.so\")\ndyn.load(\"lk_comp_joint.so\")\ndyn.load(\"lk_comp_joint_surv.so\")\ndyn.load(\"dlk_comp_joint.so\")\ndyn.load(\"dlk_comp_joint_surv.so\")\n\nest_incomp_joint_HMcontinuous = function(Y,TT,X,W,tv,dev,k,type=c(\"norm\",\"bino\"),btv=NULL,reltol=1e-6,inits=NULL,\n verbose=FALSE,LC=FALSE,surv=TRUE,maxit=5000,stderr=FALSE){\n\n# Estimate the joint model with continuous HM chain described in\n# \"A shared-parameter continuous-time hidden Markov and survival model for longitudinal data\n# with informative drop-out\"\n# by F.Bartolucci and A.Farcomeni (2018)\n#\n# INCOMPLETE DATA CASE\n#\n# INPUT:\n#\n# Y = matrix of responses of dimensino n x Tmax (Tmax = maximum number of individual observations)\n# TT = corresponding matrix of observation times\n# X = array of covariates for longitudinal process of dimension n x TT x nX (nX = number of covariates X)\n# W = array of covariates (including itercept) for survival process of dimension n x nW (nW = number of covariates V)\n# tv = vector of surivival times of lenght n\n# dev = vector of indicators of censoring of lenght n\n# k = number of latent states\n# type = type of response variables (norm or bino)\n# btv = list of equally spaced points defining time windows for the likelihood approximation\n# reltol = relative tollerance for checking log-likelihood convergence\n# inits = list of initial values of the parameters\n# verbose = to disply partial output\n# LC = to fit the latent class (instead of latent Markov) model\n# surv = if survival time is provided\n#\n# OUTPUT:\n#\n# lk = maximum log-likelihood at convergence\n# Q = estimated infinitesimal transition matrix\n# piv = estimated vector of initial probabilities\n# bev = estiamted vector of regression coefficients of the longitudinal responses\n# nu = estiamted parater in the baseline hazard function\n# xiv = estimated vector of support points for the latent distribution\n# phi = estimated association coeffiecint for the survivial process\n# psiv = estimated vector of \n# si2 = estimated variance parameter\n# pP = time-specific posterior probabilities of each state\n# Pi = discrete time transition matrix\n# it = final number of iterations\n# tim = computing time\n# bic = BIC\n# Ji = observed information matrix (optional)\n# sev = overall vector of standard errors (optional)\n# selav = standard errors for vector lambda (optional)\n# seLa = standard errors for matrix Lambda (optional)\n# sebev = standard errors for bev (optional)\n# seeta = standard error for eta (optional)\n# sexiv = standard errors for xiv (optional)\n# sephi = standard error for phi (optional)\n# sepsiv = standard errors for psi (optional)\n# sega = standard error for gamma (optional)\n\n# Preliminaries\n\ttype = match.arg(type)\n\tcensv = 1-dev\n\tt0 = proc.time()[3]\n\tnpX = dim(X)[3] # number of covariates on longitudinal process\n\tif(surv) npW = ncol(W) # number of covariates on survival process\n\tn = dim(Y)[1] # sample size\n\tjv = rowSums(!is.na(Y)) # number of longitudinal observations\n\tmjv = max(jv) # maximum number of longitudinal observations\n\tif(!surv) tv = apply(TT,1,max,na.rm=TRUE)\n\n# starting values\n\tQ = matrix(0,k,k)\n\tif(!is.null(inits)){\n\t\tif(LC) Q = matrix(0,k,k) else Q = inits$Q\n\t\tpiv = inits$piv\n\t\tbev = inits$bev\n\t\tif(surv){\n\t\t\tnu = inits$nu\n\t\t\tphi = inits$phi\n\t\t\tpsiv = inits$psiv\n\t\t}else{\n\t\t\tnu = phi = psiv = NULL\n\t\t}\n\t\txiv = inits$xiv\n\t\tif(type==\"bino\") si2 = NULL else si2 = inits$si2\n\t}\n\tif(is.null(inits)){\n\t\tif(!LC){\n\t\t\tQ = matrix(1/(k-1),k,k) \n\t\t\tdiag(Q) = -1\n\t\t}\n\t\tif(type==\"norm\"){\n\t\t\tjnk = lm(Y[,1]~.,data=data.frame(X[,1,]))\n\t\t\txiv = jnk$coef[1]+seq(-k,k,length=k)\n\t\t\tbev = jnk$coef[-1]\n\t\t\tres = jnk$residuals\n\t\t\tsi2 = var(res)\n\t\t}\n\t\tif(type==\"bino\"){\n\t\t\tyv = as.vector(Y)\n\t\t\tXX = matrix(X,n*mjv,npX)\n\t\t\tjnk = glm(yv~XX,family=binomial)\n\t\t\tpred = predict(jnk)\n\t\t\tppred0 = exp(-pred)/(1+exp(-pred))\n\t\t\tppred1 = exp(pred)/(1+exp(pred))\t\t\t\n\t\t\tres = yv[!is.na(yv)]*(-pred-log(1-ppred1)/ppred1)+(1-yv[!is.na(yv)])*(-pred+log(1-ppred0)/ppred0)\n\t\t\tsi2 = NULL\n\t\t}\n\t\tout = kmeans(res,centers=k,iter.max=100)\n\t\tbev = jnk$coef[-1]\n\t\tind = order(out$centers)\n\t\txiv = jnk$coef[1]+out$centers[ind]\n\t\tpiv = out$size[ind]/sum(out$size)\n\t\tif(surv){\n\t\t\tsu = survreg(Surv(tv,ifelse(censv,0,1))~.,data=data.frame(W[,-1]))\n\t\t\tnu = 1/su$scale\n\t\t\tphi = 0\n\t\t\tjnk = su$coef\n\t\t\tjnk[-1] = jnk[-1]*nu\n\t\t\tjnk[1] = exp(jnk[1])\n\t\t\tpsiv = -jnk\n\t\t}else{\n\t\t\tnu = phi = psiv = NULL\t\t\t\n\t\t}\n\t}\n\n# compute transition matrix\n\tif(is.null(btv)){\n\t\ta = min(c(0.1,tv))\n\t\tbtv = seq(0,max(tv),a)\n\t}else{\n\t\ta = btv[2]-btv[1]\n\t}\n\tM = length(btv)\n\tif(LC){\n\t\tPi = diag(k)\n\t}else{\n\t\tPi = diag(k)+a*Q\n\t\tTmp = a*Q\n\t\tit = 1\n\t\twhile(any(abs(Tmp)>0) & it<1000){\n\t\t\tit = it+1\n\t\t\tTmp = (a/it)*(Tmp%*%Q)\n\t\t\tPi = Pi+Tmp\n\t\t}\n\t}\n\n# expand matrix of responses and array of covariates\n\tYM = matrix(0,n,M)\n\tXM = array(0,c(n,M,npX))\n\tPM = matrix(0,n,M)\n\tfor(i in 1:n) for(j in 1:jv[i]){\n\t\tm = sum(TT[i,j]>=btv)\n\t\tYM[i,m] = Y[i,j]\n\t\tXM[i,m,] = X[i,j,]\n\t\tPM[i,m] = 1 \n\t}\n\t\n# compute log-likelihood\n\tif(is.null(si2)) si2f = as.double(0) else si2f = si2\n\tif(surv){\n\t\tout = .Fortran(\"lk_rec_surv\",k=as.integer(k),piv=piv,Pi=Pi,npX=as.integer(npX),bev=bev,\n\t\t nu=nu,xiv=xiv,phi=phi,npW=as.integer(npW),psiv=psiv,si2=si2f,\n\t\t typ=type,n=as.integer(n),XM=XM,W=W,YM=YM,M=as.integer(M),PM=as.integer(PM),\n\t\t btv=btv,dev=as.integer(1-censv),tv=as.double(tv),lk=0,Pp1=array(999,c(k,M,n)),Pp2=matrix(0,k,k))\n\t}else{\n\t\tout = .Fortran(\"lk_rec\",k=as.integer(k),piv=piv,Pi=Pi,npX=as.integer(npX),bev=bev,\n\t\t xiv=xiv,si2=si2f,typ=type,n=as.integer(n),XM=XM,YM=YM,M=as.integer(M),PM=as.integer(PM),\n\t\t btv=btv,tv=as.double(tv),lk=0,Pp1=array(999,c(k,M,n)),Pp2=matrix(0,k,k),ver=as.integer(rep(0,n)))\n\t}\n\tlk = out$lk\n\tit = 0; lko = lk\n\tif(verbose) print(c(0,lk,phi))\n\twhile(((lk-lko)/abs(lko)>reltol | it==0) & it1) for(m in 2:mi) l3 = l3-dbtvnu[m-1]*(etmp0%*%Pp1[,m-1,i])\n\t\t\tl3 = l3+(dev[i]*(lnu+(nu-1)*log(tv[i])+tmp0)-etmp0*(tv[i]^nu-btvnu[mi]))%*%Pp1[,mi,i]\n\t\t}\n\t}\n\tif(surv) lk = as.vector(l2+l3) else lk = l2\n\treturn(lk)\n\n}\n# ---------------------------------------------------------------------------------------------------\ndlk_comp_joint_HM2 <- function(par,piv,Pi,si2,type,XM,W,YM,PM,jv,btv,Pp1,dev,tv,surv=TRUE){\n\n# to compute the derivative of lk_comp_joint_HM\n# preliminaries\n\tk = length(piv)\n\tnpX = dim(XM)[3]\n\tif(surv) npW = ncol(W)\n\tbev = par[1:npX]\n\tif(surv){\n\t\tlnu = par[npX+1]; xiv = par[(npX+2):(k+npX+1)]; phi = par[k+npX+2]\n\t\tnu = exp(lnu); psiv = par[(k+npX+3):length(par)]\n\t}else{\n\t\txiv = par[(npX+1):(k+npX)]\n\t}\n\tn = nrow(YM)\n\tM = length(btv)\n\tif(surv){\n\t\tbtvnu = btv^nu\n\t\tdbtvnu = diff(btvnu)\n\t}\n# compute functions\n\tdl2bev = rep(0,2)\n\tif(surv) dl3nu = 0\n\tdl2xiv = dl3xiv = rep(0,k)\n\tif(surv){\n\t\tdl3phi = 0\n\t\tdl3psiv = rep(0,npW)\n\t}\n\tfor(i in 1:n){\n\t\tif(surv) tmp0 = exp(xiv*phi+as.vector(W[i,]%*%psiv))\n\t\tmi = sum(btv<=tv[i])\n\t\tfor(m in which(PM[i,1:mi]==1)){\n\t\t\tmuv = xiv+as.vector(XM[i,m,]%*%bev)\n\t\t\tif(type==\"norm\"){\n\t\t\t\tdl2bev = dl2bev+XM[i,m,]*as.vector(((YM[i,m]-muv)/si2)%*%Pp1[,m,i])\n\t\t\t\tdl2xiv = dl2xiv+(YM[i,m]-muv)/si2*Pp1[,m,i]\n\t\t\t}\n\t\t\tif(type==\"bino\"){\n\t\t\t\tmuv = exp(muv)/(1+exp(muv))\n\t\t\t\ttmp1 = (YM[i,m]-muv)*Pp1[,m,i]\n\t\t\t\tdl2bev = dl2bev+XM[i,m,]*sum(tmp1)\n\t\t\t\tdl2xiv = dl2xiv+tmp1\n\t\t\t}\n\t\t}\n\t\tif(surv){\n\t\t\tif(mi>1) for(m in 2:mi){\n\t\t\t\tif(btv[m-1]>0) tmp = log(btv[m-1]) else tmp = 0\n\t\t\t\tdl3nu = dl3nu-(tmp0*(log(btv[m])*btvnu[m]-tmp*btvnu[m-1]))%*%Pp1[,m-1,i]\n\t\t\t\tdl3xiv = dl3xiv-(tmp0*dbtvnu[m-1])*phi*Pp1[,m-1,i]\n\t\t\t\tdl3phi = dl3phi-(tmp0*dbtvnu[m-1]*xiv)%*%Pp1[,m-1,i]\n\t\t\t\tdl3psiv = dl3psiv-W[i,]*as.vector((tmp0*dbtvnu[m-1])%*%Pp1[,m-1,i])\n\t\t\t}\n\t\t\tif(btv[mi]>0) tmp = log(btv[mi]) else tmp = 0 \n\t\t\tdl3nu = dl3nu+(dev[i]*(1/nu+log(tv[i]))-tmp0*(log(tv[i])*tv[i]^nu-tmp*btvnu[mi]))%*%Pp1[,mi,i]\n\t\t\tdl3xiv = dl3xiv+(dev[i]*phi-tmp0*(tv[i]^nu-btvnu[mi])*phi)*Pp1[,mi,i]\n\t\t\tdl3phi = dl3phi+(dev[i]*xiv-tmp0*(tv[i]^nu-btvnu[mi])*xiv)%*%Pp1[,mi,i]\n\t\t\tdl3psiv = dl3psiv+W[i,]*as.vector((dev[i]-tmp0*(tv[i]^nu-btvnu[mi]))%*%Pp1[,mi,i])\n\t\t}\n\t}\n# output\n\tif(surv) dlk = c(dl2bev,dl3nu*nu,dl2xiv+dl3xiv,dl3phi,dl3psiv) else dlk = c(dl2bev,dl2xiv)\n\treturn(dlk)\n\n}\n# ---------------------------------------------------------------------------------------------------\nlk_rec_joint_HM2 <- function(piv,Pi,bev,nu,xiv,phi,psiv,si2,type,XM,W,YM,btv,dev,tv,surv=TRUE){\n\t\n# preliminaries\n\tn = nrow(YM)\n\tk = length(xiv)\n\tM = length(btv)\n\tif(type==\"norm\") si = sqrt(si2)\n\tif(surv){\n\t\tbtvnu = btv^nu\n\t\tdbtvnu = diff(btvnu)\n\t}\n# recursion for each individual\n\tlk = 0\n\tPp1 = array(NA,c(k,M,n))\n\tPp2 = matrix(0,k,k)\n\tfor(i in 1:n){\n\t\tmi = sum(btv<=tv[i])\n\t\tif(surv) tmp0 = exp(xiv*phi+as.vector(W[i,]%*%psiv))\n# FORWARD RECURSION\t\n\t\tFrec = matrix(0,k,mi)\n# first time\n\t\tmuv = xiv+as.vector(XM[i,1,]%*%bev)\n\t\tif(type==\"norm\") frec = piv*dnorm(YM[i,1],muv,si)\n\t\tif(type==\"bino\"){\n\t\t\tmuv = exp(muv)/(1+exp(muv)) \n\t\t\tfrec = piv*(YM[i,1]*muv+(1-YM[i,1])*(1-muv))\n\t\t}\n\t\tFrec[,1] = frec\n# following time occasions\n\t\tif(mi>1) for(m in 2:mi){\n\t\t\tif(surv){\n\t\t\t\ttmp = exp(-tmp0*dbtvnu[m-1])\n\t\t\t\tfrec = as.vector(t(Pi)%*%(frec*tmp))\n\t\t\t}else{\n\t\t\t\tfrec = as.vector(t(Pi)%*%frec)\t\t\t\t\n\t\t\t}\n\t\t\tif(!is.na(YM[i,m])){\n\t\t\t\tmuv = xiv+as.vector(XM[i,m,]%*%bev)\n\t\t\t\tif(type==\"norm\") frec = frec*dnorm(YM[i,m],muv,si)\n\t\t\t\tif(type==\"bino\"){\n\t\t\t\t\tmuv = exp(muv)/(1+exp(muv)) \n\t\t\t\t\tfrec = frec*(YM[i,m]*muv+(1-YM[i,m])*(1-muv))\n\t\t\t\t}\n\t\t\t}\n\t\t\tFrec[,m] = frec\t\n\t\t}\n\t\tif(surv){\n\t\t\ttmp = exp(-tmp0*(tv[i]^nu-btvnu[mi]))\n\t\t\tif(dev[i]==1) tmp = tmp*nu*tv[i]^(nu-1)*tmp0\t\n\t\t\tfrec = as.vector(frec*tmp)\n\t\t}\n\t\tfi = sum(frec)\n# accumulate log-likelihood\n\t\tlk = lk+log(fi)\n\n# BACKWARD RECURSION\n\t\tGrec = matrix(0,k,mi)\n# last time occasion\n\t\tif(surv){\n\t\t\tgrec = exp(-tmp0*(tv[i]^nu-btvnu[mi]))\n\t\t\tif(dev[i]==1) grec = grec*nu*tv[i]^(nu-1)*tmp0\n\t\t}else{\n\t\t\tgrec = rep(1,k)\n\t\t}\n\t\tGrec[,mi] = grec\n# previous time occasions\n\t\tif(mi>1) for(m in (mi-1):1){\n\t\t\tif(surv) tmp = exp(-tmp0*dbtvnu[m])\n\t\t\tif(!is.na(YM[i,m+1])){\n\t\t\t\tmuv = xiv+as.vector(XM[i,m+1,]%*%bev)\n\t\t\t\tif(type==\"norm\") grec = grec*dnorm(YM[i,m+1],muv,si)\n\t\t\t\tif(type==\"bino\"){\n\t\t\t\t\tmuv = exp(muv)/(1+exp(muv)) \n\t\t\t\t\tgrec = grec*(YM[i,m+1]*muv+(1-YM[i,m+1])*(1-muv))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(surv) grec = tmp*as.vector(Pi%*%grec) else grec = as.vector(Pi%*%grec)\n\t\t\tGrec[,m] = grec\t\n\t\t}\n# Posterior probabilities for the first time occasion\n\t\tPp1[,1:mi,i] = Frec*Grec/fi\n# Joint Posterior probabilities for two occasions\n\t\tif(mi>1) for(m in 1:(mi-1)){\n\t\t\tif(surv) tmp = exp(-tmp0*dbtvnu[m])\n\t\t\tif(!is.na(YM[i,m+1])){\n\t\t\t\tmuv = xiv+as.vector(XM[i,m+1,]%*%bev)\n\t\t\t\tif(type==\"norm\") tmp1 = dnorm(YM[i,m+1],muv,si)\n\t\t\t\tif(type==\"bino\"){\n\t\t\t\t\tmuv = exp(muv)/(1+exp(muv)) \n\t\t\t\t\ttmp1 = YM[i,m+1]*muv+(1-YM[i,m+1])*(1-muv)\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\ttmp1 = 1\n\t\t\t}\n\t\t\tif(surv){\n\t\t\t\tTmp = ((Frec[,m]*tmp)%o%(Grec[,m+1]*tmp1))*Pi/fi\n\t\t\t}else{\n\t\t\t\tTmp = (Frec[,m]%o%(Grec[,m+1]*tmp1))*Pi/fi\n\t\t\t}\n\t\t\tPp2 = Pp2+Tmp\n\t\t}\n\t}\n# output\n\tout = list(lk=lk,Pp1=Pp1,Pp2=Pp2)\n\n}\n# ---------------------------------------------------------------------------------------------------\nlk_obs <- function(par_tot,YM,XM,W,tv,dev,k,type,btv,M,PM,LC,surv,npX,npW,n)\n{\n\n# reconstruct parameters\n G = diag(k)[,-1]\n if(k==2) {G=matrix(G)}\n\tpiv = exp(G%*%par_tot[1:(k-1)]); piv = as.vector(piv/sum(piv))\n\tpar_tot = par_tot[-(1:(k-1))]\n\tif(!LC){\n\t\tPi = NULL\n\t\tfor(u in 1:k){\n G = diag(k)[,-u]\n if(k==2) {G=matrix(G)}\n\t\t\ttmp = exp(G%*%par_tot[1:(k-1)]); tmp = as.vector(tmp/sum(tmp))\n\t\t\tPi = rbind(Pi,tmp)\t\t\t\n\t\t\tpar_tot = par_tot[-(1:(k-1))]\n\t\t}\n\t}\n\tbev = par_tot[1:npX]; par_tot = par_tot[-(1:npX)]\n\tif(surv){\n\t\teta = par_tot[1]; nu = exp(eta); par_tot = par_tot[-1]\n\t}\n\txiv = par_tot[1:k]; par_tot = par_tot[-(1:k)]\n\tphi = par_tot[1]; par_tot = par_tot[-1]\n\tpsiv = par_tot[1:npW]; par_tot = par_tot[-(1:npW)]\n\tif(type==\"norm\"){\n\t\tga = par_tot; si2 = exp(ga)\t\n\t}else{\n\t\tsi2 = NULL\n\t}\n\n# compute log-likelihood\n\tif(is.null(si2)) si2f = as.double(0) else si2f = si2\n\tif(surv){\n\t\tout = .Fortran(\"lk_rec_surv\",k=as.integer(k),piv=piv,Pi=Pi,npX=as.integer(npX),bev=bev,\n\t\t nu=nu,xiv=xiv,phi=phi,npW=as.integer(npW),psiv=psiv,si2=si2f,\n\t\t typ=type,n=as.integer(n),XM=XM,W=W,YM=YM,M=as.integer(M),PM=as.integer(PM),\n\t\t btv=btv,dev=as.integer(dev),tv=as.double(tv),lk=0,Pp1=array(999,c(k,M,n)),Pp2=matrix(0,k,k))\n\t}else{\n\t\tout = .Fortran(\"lk_rec\",k=as.integer(k),piv=piv,Pi=Pi,npX=as.integer(npX),bev=bev,\n\t\t xiv=xiv,si2=si2f,typ=type,n=as.integer(n),XM=XM,YM=YM,M=as.integer(M),PM=as.integer(PM),\n\t\t btv=btv,tv=as.double(tv),lk=0,Pp1=array(999,c(k,M,n)),Pp2=matrix(0,k,k),ver=as.integer(rep(0,n)))\n\t}\n\tlk = out$lk\n# compute posterior probabilities\n\tPp1 = out$Pp1; Pp2 = out$Pp2\t\n\tPp1[Pp1==999] = NA\n# preliminaries\n\tif(surv){\n\t\tbtvnu = btv^nu\n\t\tdbtvnu = diff(btvnu)\n\t}\n# compute functions\n G = diag(k)[,-1]\n if(k==2) {G=matrix(G)}\n\tbnv = rowSums(Pp1[,1,])\n\tdl1lav = t(G)%*%(bnv-n*piv)\t\n\tdl1La = NULL\n\tfor(u in 1:k){\n G = diag(k)[,-u]\n if(k==2) {G=matrix(G)}\n\t\tdl1La = c(dl1La,t(G)%*%(Pp2[u,]-sum(Pp2[u,])*Pi[u,]))\t\n\t}\n\tdl2bev = rep(0,2)\n\tif(surv) dl3nu = 0\n\tif(type==\"norm\") dl2ga = 0\n\tdl2xiv = dl3xiv = rep(0,k)\n\tif(surv){\n\t\tdl3phi = 0\n\t\tdl3psiv = rep(0,npW)\n\t}\n\tfor(i in 1:n){\n\t\tif(surv) tmp0 = exp(xiv*phi+as.vector(W[i,]%*%psiv))\n\t\tmi = sum(btv<=tv[i])\n\t\tfor(m in which(PM[i,1:mi]==1)){\n\t\t\tmuv = xiv+as.vector(XM[i,m,]%*%bev)\n\t\t\tif(type==\"norm\"){\n\t\t\t\tdl2bev = dl2bev+XM[i,m,]*as.vector(((YM[i,m]-muv)/si2)%*%Pp1[,m,i])\n\t\t\t\tdl2xiv = dl2xiv+(YM[i,m]-muv)/si2*Pp1[,m,i]\n\t\t\t\tdl2ga = dl2ga-(1-(YM[i,m]-muv)^2/si2)%*%Pp1[,m,i]/2\n\t\t\t}\n\t\t\tif(type==\"bino\"){\n\t\t\t\tmuv = exp(muv)/(1+exp(muv))\n\t\t\t\ttmp1 = (YM[i,m]-muv)*Pp1[,m,i]\n\t\t\t\tdl2bev = dl2bev+XM[i,m,]*sum(tmp1)\n\t\t\t\tdl2xiv = dl2xiv+tmp1\n\t\t\t}\n\t\t}\n\t\tif(surv){\n\t\t\tif(mi>1) for(m in 2:mi){\n\t\t\t\tif(btv[m-1]>0) tmp = log(btv[m-1]) else tmp = 0\n\t\t\t\tdl3nu = dl3nu-(tmp0*(log(btv[m])*btvnu[m]-tmp*btvnu[m-1]))%*%Pp1[,m-1,i]\n\t\t\t\tdl3xiv = dl3xiv-(tmp0*dbtvnu[m-1])*phi*Pp1[,m-1,i]\n\t\t\t\tdl3phi = dl3phi-(tmp0*dbtvnu[m-1]*xiv)%*%Pp1[,m-1,i]\n\t\t\t\tdl3psiv = dl3psiv-W[i,]*as.vector((tmp0*dbtvnu[m-1])%*%Pp1[,m-1,i])\n\t\t\t}\n\t\t\tif(btv[mi]>0) tmp = log(btv[mi]) else tmp = 0 \n\t\t\tdl3nu = dl3nu+(dev[i]*(1/nu+log(tv[i]))-tmp0*(log(tv[i])*tv[i]^nu-tmp*btvnu[mi]))%*%Pp1[,mi,i]\n\t\t\tdl3xiv = dl3xiv+(dev[i]*phi-tmp0*(tv[i]^nu-btvnu[mi])*phi)*Pp1[,mi,i]\n\t\t\tdl3phi = dl3phi+(dev[i]*xiv-tmp0*(tv[i]^nu-btvnu[mi])*xiv)%*%Pp1[,mi,i]\n\t\t\tdl3psiv = dl3psiv+W[i,]*as.vector((dev[i]-tmp0*(tv[i]^nu-btvnu[mi]))%*%Pp1[,mi,i])\n\t\t}\n\t}\n\tif(surv) dlk = c(dl1lav,dl1La,dl2bev,dl3nu*nu,dl2xiv+dl3xiv,dl3phi,dl3psiv) else dlk = c(dl2bev,dl2xiv)\n\tif(type==\"norm\") dlk = c(dlk,dl2ga)\n# output\n\tout = list(lk=lk,dlk=dlk)\t\n\n}\n", "meta": {"hexsha": "0ccb4c366d6f6b55009e678c47dd0a2ad53b9c85", "size": 23305, "ext": "r", "lang": "R", "max_stars_repo_path": "est_incomp_joint_HMcontinuous.r", "max_stars_repo_name": "afarcome/lmjm", "max_stars_repo_head_hexsha": "5fd84ef9fa636e8d07d73207e6f385c92c535602", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "est_incomp_joint_HMcontinuous.r", "max_issues_repo_name": "afarcome/lmjm", "max_issues_repo_head_hexsha": "5fd84ef9fa636e8d07d73207e6f385c92c535602", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "est_incomp_joint_HMcontinuous.r", "max_forks_repo_name": "afarcome/lmjm", "max_forks_repo_head_hexsha": "5fd84ef9fa636e8d07d73207e6f385c92c535602", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8702397743, "max_line_length": 131, "alphanum_fraction": 0.5742973611, "num_tokens": 9474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48172692921217275}} {"text": "#' @title calcKristCr\n#'\n#' @description Calculate the residual resistance coefficient (\\code{Cr})\n#' (dimensionless) using the Kristensen method with Harvald regressions.\n#'\n#'@param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}})\n#'@param M Fineness/slenderness coefficient (vector of numericals,\n#'dimensionless) (see \\code{\\link{calcShipM}})\n#'@param froudeNum Froude number (vector of numericals, dimensionless) (see\n#'\\code{\\link{calcFroudeNum}})\n#'@param actualDraft Actual draft (vector of numericals, m)\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param Cp Prismatic coefficient (vector of numericals, dimensionless) (see\n#'\\code{\\link{calcCp}})\n#'@param tankerBulkCarrierGCargoShipTypes Ship types specified in input\n#'\\code{shipTypes} to be modeled as tankers, bulk carriers and general cargo\n#'vessels (vector of strings)\n#'\n#' @details\n#'Note: Uses Guldhammer Residual Resistance Calculation and adjusts for bulbous bow, and\n#'breadth/draft ratio.\n#'\n#' This method this requires ship types to be grouped. Use the\n#' \\code{tankerBulkCarrierGCargoShipTypes} grouping\n#' parameters to provide these ship type groupings. Any ship types not include\n#' this grouping will be considered as miscellaneous vessels.\n#'\n#' Actual draft is typically obtained from sources such as AIS messages or ship\n#' records.\n#'\n#' @return \\code{Cr} (vector of numericals, dimensionless)\n#'\n#' @references\n#'Kristensen, H. O. and Lutzen, M. 2013. \"Prediction of Resistance and Propulsion\n#'Power of Ships.\"\n#'\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcShipM}}\n#'\\item \\code{\\link{calcFroudeNum}}\n#'\\item \\code{\\link{calcCp}}\n#'\\item \\code{\\link{calcShipType}}\n#'}\n#'\n#' @family Kristensen Calculations\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcKristCr(\"bulk.carrier\", 5.2, 0.1199268, 12.48, 32.25, 0.81)\n#'\n#' @export\n\ncalcKristCr <- function(shipType, M, froudeNum, actualDraft, breadth, Cp,\n tankerBulkCarrierGCargoShipTypes=c(\"tanker\",\"general.cargo\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\")\n){\n\n\nE<- (\n (1.35-(0.23*M)+0.012*(M^2))+\n (1.5*(froudeNum^1.8))+\n ( 0.0011*(M^9.1)*(froudeNum^(2*M-3.7)))\n)*\n (0.98+(2.5/((M-2)^4)))+\n ((M-5)^4)*((froudeNum-0.1)^4)\n\nG<- ((7-0.09*((M)^2))*(((5*Cp)-2.5)^2))/\n ((600*((froudeNum-0.315)^2)+1)^1.5)\n\nH<-exp(\n 80*(froudeNum-(0.04+(0.59*Cp))-0.015*(M-5))\n)\n\n #Calculate Cr\n #Source: Kristensen(2016) using Guldhammer(1978) method\n Cr<-((\n (1.35-(0.23*M)+0.012*(M^2))+\n (1.5*(froudeNum^1.8))+\n ( 0.0011*(M^9.1)*(froudeNum^(2*M-3.7)))\n )*\n (0.98+(2.5/((M-2)^4)))+\n ((M-5)^4)*((froudeNum-0.1)^4)+\n (\n ((7-0.09*((M)^2))*(((5*Cp)-2.5)^2))/\n ((600*((froudeNum-0.315)^2)+1)^1.5)\n )+\n exp(\n 80*(froudeNum-(0.04+(0.59*Cp))-0.015*(M-5))\n )+\n ( 180*(froudeNum^3.7)*exp((20*Cp)-16))+\n #correction for vessels where B/T!=2.5\n (.16*((breadth/actualDraft)-2.5))\n )/1000\n\n #Apply Cr Correction for bulbous bow shape according to ship type.\n #Bulbous bows have become more common since these regressions were\n #made, they cut down on a lot of resistance\n Cr<- ifelse( shipType %in%tankerBulkCarrierGCargoShipTypes,\n\n Cr+ pmax(-0.4, -0.1-1.6*froudeNum)/1000,\n\n Cr+ pmax(-50,250*froudeNum-90)* (Cr/100)\n\n )#end ifelse\n\n return(Cr)\n\n}\n\n", "meta": {"hexsha": "a2a25aaedea0ad220859f2893a02b255d17d2288", "size": 3613, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristCr.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcKristCr.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcKristCr.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 32.5495495495, "max_line_length": 168, "alphanum_fraction": 0.6435095489, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48140618577205085}} {"text": "# lhl.r\n# Church two step breakpoint algorithm, from Church et al, 1994.\n# Author: Emmanuel Alcalá\n# Date: 5 may 2019\n# \n# ------------------------------------------------------------------------------\n# This is an improved version of lhl_old. It is just marginally faster, but\n# cleaner and more intuitive. It sets first all possible combinations of s1\n# and s2 (start and stop), then it computes the differences between the overall\n# rate r and the state rates r1, r2 and r3, weighted by their respective\n# durations t1, t2 and t3. Then it computes the index (i.e., an integer of the\n# position in the vector) at which the differences were maximized, with which\n# all other metrics can be solved. \n# inputs:\n# - r_times: every time at which there was a response\n# - trial_duration: the duration of peal trial\n# ------------------------------------------------------------------------------\n\nlhl = function(r_times, trial_duration) {\n # Number of responses\n nr = length(r_times)\n # overall response rate\n r = nr/trial_duration \n # Vector of putative starts (all time of responses except the last)\n s1 = r_times[1:(nr - 1)]\n # Vector of putative stops (except the first)\n s2 = r_times[2:nr]\n \n # Get all combinations of s1 and s2 with s1 less than s2.\n # For example, if s1 can be 1, 2, 3, and s2 = 2, 3, 4, \n # the combinations are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)\n grid = expand.grid.jc(s1,s2) # matrix of nx2; n = all possible combinations\n grid = grid[grid[ ,1] < grid[ ,2], ] # select n with s1 < s2\n # Vector of 0 to store results\n A = numeric(nrow(grid))\n # Computations of differences between the r and r(i), with i = 1, 2, 3\n # which are the rates at the low, high and low states. \n # Store the results of the differences in A[j]\n for (j in 1:nrow(grid)) { # loop trough all combinations of s1 & s2\n t1 = grid[j, 1]\n t2 = grid[j, 2] - t1\n t3 = trial_duration - grid[j, 2]\n # Previous versions looked if some t equals 0 and assigned 0 to rates\n # to avoid division by 0, but isn' necessary: there are 0 responses\n # with duration 0!\n r1 = sum(r_times <= t1)/t1\n r2 = sum(r_times > t1 & r_times <= grid[j, 2])/t2\n r3 = sum(r_times > grid[j, 2])/t3\n\n A[j] = sum(t1*(r - r1), t2*(r2 - r), t3*(r - r3), na.rm = T)\n \n } \n # Get the index which maximizes A\n argmaxA = which.max(A)\n # Vector of 2 at which A were maximum. column 1 is s1, 2 is s2\n s1s2 = grid[argmaxA, ]\n # High rate state duration: s2 - s1\n t2 = s1s2[2] - s1s2[1]\n # Low rate 1\n r1 = sum(r_times <= s1s2[1])/s1s2[1]\n # Low rate 2\n r3 = sum(r_times > s1s2[2])/(trial_duration - s1s2[2])\n # High rate\n hrate = sum(r_times > s1s2[1] & r_times <= s1s2[2])/t2\n # Middle time\n mid = sum(s1s2)/2\n # Return results\n data.frame(start = s1s2[1],\n stop = s1s2[2],\n spread = t2,\n hrate = hrate,\n mid = mid,\n r1 = r1,\n r3 = r3)\n}\n", "meta": {"hexsha": "cd2af2dd597f6f917a9a844985947da20e1f4de0", "size": 2959, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/r/lhl.r", "max_stars_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_stars_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/r/lhl.r", "max_issues_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_issues_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/r/lhl.r", "max_forks_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_forks_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9342105263, "max_line_length": 80, "alphanum_fraction": 0.594457587, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4806814620456157}} {"text": "#!/usr/bin/Rscript\n\n# R (http://www.r-project.org/) script\n# from https://en.wikipedia.org/wiki/R_(programming_language)#Basic_syntax\n\ninstall.packages(\"caTools\") # install external package\nlibrary(caTools) # external package providing write.gif function\njet.colors <- colorRampPalette(c(\"red\", \"blue\", \"#007FFF\", \"cyan\", \"#7FFF7F\",\n \"yellow\", \"#FF7F00\", \"red\", \"#7F0000\"))\ndx <- 1500 # define width\ndy <- 1400 # define height\nC <- complex(real = rep(seq(-2.2, 1.0, length.out = dx), each = dy),\n imag = rep(seq(-1.2, 1.2, length.out = dy), dx))\nC <- matrix(C, dy, dx) # reshape as square matrix of complex numbers\nZ <- 0 # initialize Z to zero\nX <- array(0, c(dy, dx, 20)) # initialize output 3D array\nfor (k in 1:20) { # loop with 20 iterations\n Z <- Z^2 + C # the central difference equation\n X[, , k] <- exp(-abs(Z)) # capture results\n}\nwrite.gif(X, \"out/mandelbrot.gif\", col = jet.colors, delay = 100)\n", "meta": {"hexsha": "c13983ebdb2e114255eb05f12eed006ce0dfeaaa", "size": 1061, "ext": "r", "lang": "R", "max_stars_repo_path": "programming/rscript/demos/mandelbrot.r", "max_stars_repo_name": "morten-andersen/tech-notes", "max_stars_repo_head_hexsha": "e6c3c83117bc43d2b37d7ff13f5179edbf1594ae", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T02:28:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T02:28:26.000Z", "max_issues_repo_path": "programming/rscript/demos/mandelbrot.r", "max_issues_repo_name": "morten-andersen/tech-notes", "max_issues_repo_head_hexsha": "e6c3c83117bc43d2b37d7ff13f5179edbf1594ae", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programming/rscript/demos/mandelbrot.r", "max_forks_repo_name": "morten-andersen/tech-notes", "max_forks_repo_head_hexsha": "e6c3c83117bc43d2b37d7ff13f5179edbf1594ae", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2272727273, "max_line_length": 77, "alphanum_fraction": 0.5673892554, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4805660133017677}} {"text": "rdirichlet = function(n, a) {\n l = length(a)\n x = matrix(rgamma(n * l, a), ncol = l, byrow = T)\n s = x %*% rep(1, l)\n x / as.vector(s)\n}\n", "meta": {"hexsha": "3641fc8ca458445e36d22b80530bdf164f511c0a", "size": 141, "ext": "r", "lang": "R", "max_stars_repo_path": "finite-gaussian-mixture/src/fmm_utils.r", "max_stars_repo_name": "jtobin/bnp", "max_stars_repo_head_hexsha": "ed73e15a2e5976993ff1f6a13fd7041f45b39a0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-01-27T10:07:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T13:13:25.000Z", "max_issues_repo_path": "finite-gaussian-mixture/src/fmm_utils.r", "max_issues_repo_name": "jtobin/bnp", "max_issues_repo_head_hexsha": "ed73e15a2e5976993ff1f6a13fd7041f45b39a0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finite-gaussian-mixture/src/fmm_utils.r", "max_forks_repo_name": "jtobin/bnp", "max_forks_repo_head_hexsha": "ed73e15a2e5976993ff1f6a13fd7041f45b39a0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1428571429, "max_line_length": 51, "alphanum_fraction": 0.5106382979, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.48015154527851633}} {"text": "#' RNAi\n#'\n#' RNAi Package to do stuff\n#'\n#' @name RNAi\n#'\n#'\n\nrequire(dplyr)\n\n\n\n# mapper for hypergeometric distribution\n# with lower.tail, return value is P[X > x], therefore x-1 as first argument\nrsa.phyper.map <- function(row) {\n phyper(row[1]-1, row[2], row[3], row[4],\n lower.tail=F, log.p=T)\n}\n\n# b<-590 to 591 reaches the 1E-2180 lowest p-value limit \n# a\n# phyper(b, a-b, 30203, 1090, lower.tail=FALSE, log.p = TRUE)\n\n# calculate p-values for each siRNA of a gene\n# by default, return only data for the siRNA with the smallest p-value\n# with full=T, all data is returned\nrsa.prob <- function(x, N, full) {\n nr <- nrow(x)\n x <- x[order(x$rank),]\n a <- seq_len(nr)\n b <- x$rank\n c <- N-b\n d <- nr\n counts <- cbind(a,b,c,d)\n p <- apply(counts, 1, rsa.phyper.map)/log(10)\n \n if (full) {\n idx <- seq_len(nr)\n } else {\n idx <- which.min(p)\n }\n \n return(cbind(x, counts, p)[idx,])\n}\n\n#' rsa\n#'\n#'\n#' @author Florian Nigsch, Gregory McAllister\n#' @name rsa\n#' @param rsadat data frame containing a minimum of gene id and value\n#' @param gene.column column name in rsadat specifying the gene identifier\n#' @param vale.column column name in rsadat specifying the value\n#' @param activator boolean specifying whether the screen is an activator or inhibitor. Activator will ranking such that numerically smaller values get lower ranks (ie are better)\n#' @param full boolean specifying whether to return all objects and their associated p-values. This will also return counts from the hypergeometric\n#' @param subset boolean (T = limit data frame returned to gene identifier and LogP)\n#' @return data frame\n#' @references A probability-based approach for the analysis of large-scale RNAi screens\n#' Nature Methods - 4, 847 - 849 (2007), doi:10.1038/nmeth1089\n#' Paper: \\url{http://www.nature.com/nmeth/journal/v4/n10/full/nmeth1089.html}\n#' SuppInfo: \\url{http://www.nature.com/nmeth/journal/v4/n10/extref/nmeth1089-S1.pdf}\n#'\n#' @seealso \\code{rsa.gnf}\n#' \n#' @export\n\n\n\nrsa <- function(rsadat, activator=F, full=F, gene.column=\"gene\", value.column=\"value\", subset=F, drugseq=F,drugseq.ties='average') {\n \n switch <- ifelse(activator, -1, 1)\n \n if(drugseq) {\n ties.met<-drugseq.ties #default = 'average' which performs well upon manual review.\n } else {\n ties.met<-\"min\"\n }\n \n rsadat$rank <- rank(rsadat[,value.column] * switch, ties.method=ties.met)\n \n res <- by(rsadat, rsadat[,gene.column], rsa.prob, nrow(rsadat), full)\n \n res <- do.call(\"rbind\", res)\n \n if(full)\n return(res)\n \n if (subset){\n tmp <- res[,c(gene.column,\"p\")]\n colnames(tmp)[2] <- \"LogP\"\n return(tmp)\n }else{\n tmp <- res[,!colnames(res) %in% c(\"rank\",\"a\",\"b\",\"c\",\"d\")]\n colnames(tmp)[which(colnames(tmp)==\"p\")] <- \"LogP\"\n return(tmp)\n }\n \n}\n\n\nq1q3 <- function(dat){\n result <- quantile(dat$my_value,probs=c(0.25,0.75),na.rm=T)\n return (c(result[1],result[2]))\n}\n\nq0q1q3q4 <-function(dat){\n result <- quantile(dat$my_value,probs=c(0,0.25,0.75,1),na.rm=T)\n return (c(result[1],result[2],result[3],result[4]))\n}\n\nlogq0q1q2q3q4<-function(dat){\n result <- quantile(dat$my_logvalue,probs=c(0,0.25,0.5,0.75,1),na.rm=T)\n return (c(result[1],result[2],result[3],result[4],result[5]))\n}\n\n\n#' score.screen.ZY.RQz\n#'\n#' Generate gene level scores for a single RNAi screen. Runs RSA in both directions and generates Q1/Q3 per gene.\n#'\n#' @name score.screen\n#' @param x data frame containing at least a gene column and score column\n#' @param gene.column column name in rsadat specifying the gene identifier\n#' @param vale.column column name in rsadat specifying the value\n#' @param both.directions boolean indicating whether to calculate \"RSA Up\" as well\n#'\n#' @export\n\nscore.screen.ZY.RQz <- function(data,gene.column=\"gene\",value.column=\"value\",log.column=\"Log2FoldChange\",drugseq=F,drugseq.ties='average') {\n if(drugseq){print('RSA setup for DRUG-seq: ties.methods is set to average in place of min in CRISPR/siRNA screens')}\n x.rsa.d <- rsa(data,gene.column=gene.column,value.column=value.column,subset=T,drugseq=drugseq,drugseq.ties=drugseq.ties)\n x.rsa.d <- unique(x.rsa.d[,c(gene.column,\"LogP\")])\n colnames(x.rsa.d)[2] <- \"logP_RSA_Down\"\n \n x.rsa.u <- rsa(data,gene.column=gene.column,value.column=value.column,subset=T,activator=T,drugseq=drugseq,drugseq.ties=drugseq.ties)\n x.rsa.u <- unique(x.rsa.u[,c(gene.column,\"LogP\")])\n colnames(x.rsa.u)[2] <- \"logP_RSA_Up\"\n \n #y <- ddply(data,gene.column,function(x) { quantile(x[,value.column],probs=c(0.25,0.75))})\n # remove plyr dependency - there are probably more elegant code for this thou...\n data$my_gene <- data[,gene.column]\n data$my_value <- data[,value.column]\n data$my_logvalue<- data[,log.column]\n data2<- select(data,my_gene,my_logvalue)\n data <- select(data,my_gene,my_value)\n #updated from q1q3 to q0q1q3q4 on 2017-11-20\n #y <- by(data,data$my_gene,q1q3)\n y <- by(data,data$my_gene,q0q1q3q4)\n y2<- by(data2,data2$my_gene,logq0q1q2q3q4)\n \n y <- as.data.frame(do.call(rbind,y))\n y$gene<-rownames(y)\n \n y2 <- as.data.frame(do.call(rbind,y2))\n y2$gene<-rownames(y2)\n \n #y <- y[c(5,1,2)]\n #colnames(y) <- c(gene.column,\"rz_score_Q1\",\"rz_score_Q3\")\n #updated from above on 2017-11-20\n y <- y[c(5,1,2,3,4)]\n colnames(y) <- c(gene.column,\"rz_score_min\",\"rz_score_Q1\",\"rz_score_Q3\",\"rz_score_max\")\n \n y2 <- y2[c(6,1,2,3,4,5)]\n colnames(y2) <- c(gene.column,\"Min log2FoldChange\",\"Q1 log2FoldChange\",\"Median log2FoldChange\",\"Q3 log2FoldChange\",\"Max log2FoldChange\")\n \n all <- merge(x.rsa.d,x.rsa.u,by=gene.column,all=T)\n \n \n zN<-by(data,data$my_gene,tally)\n zN <- as.data.frame(do.call(rbind,zN))\n zN$gene<-rownames(zN)\n zN <- zN[c(2,1)]\n colnames(zN)<-c(gene.column,\"N\")\n \n data_temp_D<-subset(data,data$my_value<=(-2.0))\n data_temp_D3<-subset(data,data$my_value<=(-3.0))\n data_temp_D4<-subset(data,data$my_value<=(-4.0))\n \n if(dim(data_temp_D)[1]==0) {\n } else {\n zD<-by(data_temp_D,data_temp_D$my_gene,tally)\n zD <- as.data.frame(do.call(rbind,zD))\n zD$gene<-rownames(zD)\n zD <- zD[c(2,1)]\n colnames(zD)<-c(gene.column,\"z2_count_Down\")\n }\n \n if(dim(data_temp_D3)[1]==0) {\n } else {\n zD3<-by(data_temp_D3,data_temp_D3$my_gene,tally)\n zD3 <- as.data.frame(do.call(rbind,zD3))\n zD3$gene<-rownames(zD3)\n zD3 <- zD3[c(2,1)]\n colnames(zD3)<-c(gene.column,\"z3_count_Down\")\n }\n \n if(dim(data_temp_D4)[1]==0) {\n } else {\n zD4<-by(data_temp_D4,data_temp_D4$my_gene,tally)\n zD4 <- as.data.frame(do.call(rbind,zD4))\n zD4$gene<-rownames(zD4)\n zD4 <- zD4[c(2,1)]\n colnames(zD4)<-c(gene.column,\"z4_count_Down\")\n }\n \n data_temp_U<-subset(data,data$my_value>=(2.0))\n data_temp_U3<-subset(data,data$my_value>=(3.0))\n data_temp_U4<-subset(data,data$my_value>=(4.0))\n \n if(dim(data_temp_U)[1]==0) {\n } else {\n zU<-by(data_temp_U,data_temp_U$my_gene,tally)\n zU <- as.data.frame(do.call(rbind,zU))\n zU$gene<-rownames(zU)\n zU <- zU[c(2,1)]\n colnames(zU)<-c(gene.column,\"z2_count_Up\")\n }\n \n if(dim(data_temp_U3)[1]==0) {\n } else {\n zU3<-by(data_temp_U3,data_temp_U3$my_gene,tally)\n zU3 <- as.data.frame(do.call(rbind,zU3))\n zU3$gene<-rownames(zU3)\n zU3 <- zU3[c(2,1)]\n colnames(zU3)<-c(gene.column,\"z3_count_Up\")\n }\n \n if(dim(data_temp_U4)[1]==0) {\n } else {\n zU4<-by(data_temp_U4,data_temp_U4$my_gene,tally)\n zU4 <- as.data.frame(do.call(rbind,zU4))\n zU4$gene<-rownames(zU4)\n zU4 <- zU4[c(2,1)]\n colnames(zU4)<-c(gene.column,\"z4_count_Up\")\n }\n \n all <- merge(all,y,by=gene.column,all=T)\n all <- merge(all,y2,by=gene.column,all=T)\n \n all <- merge(all,zN,by=gene.column,all=T)\n \n if(dim(data_temp_D)[1]==0) {\n all$z2_count_Down<-(0)\n } else {\n all <- merge(all,zD,by=gene.column,all=T)\n }\n \n if(dim(data_temp_U)[1]==0) {\n all$z2_count_Up<-(0)\n } else {\n all <- merge(all,zU,by=gene.column,all=T)\n }\n \n if(dim(data_temp_D3)[1]==0) {\n all$z3_count_Down<-(0)\n } else {\n all <- merge(all,zD3,by=gene.column,all=T)\n }\n \n if(dim(data_temp_U3)[1]==0) {\n all$z3_count_Up<-(0)\n } else {\n all <- merge(all,zU3,by=gene.column,all=T)\n }\n \n if(dim(data_temp_D4)[1]==0) {\n all$z4_count_Down<-(0)\n } else {\n all <- merge(all,zD4,by=gene.column,all=T)\n }\n \n if(dim(data_temp_U4)[1]==0) {\n all$z4_count_Up<-(0)\n } else {\n all <- merge(all,zU4,by=gene.column,all=T)\n }\n \n all[is.na(all$z2_count_Down),'z2_count_Down']<-0\n all[is.na(all$z2_count_Up),'z2_count_Up']<-0\n all[is.na(all$z3_count_Down),'z3_count_Down']<-0\n all[is.na(all$z3_count_Up),'z3_count_Up']<-0 \n all[is.na(all$z4_count_Down),'z4_count_Down']<-0\n all[is.na(all$z4_count_Up),'z4_count_Up']<-0\n \n invisible(all)\n}", "meta": {"hexsha": "654a38a25e689aaa935ab0b1794ad824960b9f0d", "size": 8680, "ext": "r", "lang": "R", "max_stars_repo_path": "RNAi-package.r", "max_stars_repo_name": "Novartis/DRUG-seq", "max_stars_repo_head_hexsha": "0939b57c834c8ba6837ac8b4165ce55ffb03e76c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-06-05T08:03:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:13:23.000Z", "max_issues_repo_path": "RNAi-package.r", "max_issues_repo_name": "Novartis/DRUG-seq", "max_issues_repo_head_hexsha": "0939b57c834c8ba6837ac8b4165ce55ffb03e76c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RNAi-package.r", "max_forks_repo_name": "Novartis/DRUG-seq", "max_forks_repo_head_hexsha": "0939b57c834c8ba6837ac8b4165ce55ffb03e76c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-10T09:16:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T16:07:24.000Z", "avg_line_length": 30.3496503497, "max_line_length": 180, "alphanum_fraction": 0.6551843318, "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4797949834760122}} {"text": "\n#' @name cMGL.multi\n#' @rdname cMGL.multi\n#' @title d-dimensional MGL and survival MGL copula\n#' @description\n#' Density, distribution function, and random generation for the MGL and survival MGL copula.\n#'\n#' @param u d-dimensional matrix\n#' @param d d-dimensional\n#' @param pars copula parameter, denoted by \\eqn{\\delta>0}.\n#' @param log logical; if TRUE, probabilities/densities p are returned as log(p).\n#' @param n number of observations. If length(n) > 1, the length is taken to be the number required.\n#' @importFrom stats qbeta\n#' @importFrom stats pbeta\n#' @importFrom stats runif\n#' @importFrom stats pgamma\n#' @md\n#' @return\n#' * \\code{dcMGL.multi}, \\code{pcMGL.multi} and \\code{rcMGL.multi} gives values of Density, distribution function, and random generation for the d-dimensional MGL copula with copula parameter \\eqn{\\delta>0}.\n#' * \\code{dcMGL180.multi}, \\code{pcMGL180.multi} and \\code{rcMGL180.multi} gives values of Density, distribution function, and random generation for the d-dimensional MGL copula with copula parameter \\eqn{\\delta>0}.\nNULL\n\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#'\n#'\n#' dcMGL.multi(u = cbind(c(0.6, 0.1, 0.5), c(0.3, 0.9, 0.2)), pars = 2, log = FALSE)\n#'\n#' dcMGL.multi(u = cbind(c(0.6, 0.1), c(0.3, 0.9), c(0.5, 0.6)), pars = 2, log = TRUE)\ndcMGL.multi <- function(u, pars, log = FALSE) {\n # coding as a matrix\n dim <- ncol(u)\n a <- 1 / pars[1]\n q <- (qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a)))\n logdc <- 0\n for (i in seq_len(nrow(u))) {\n logdc[i] <- (dim - 1) * lgamma(a) + lgamma(a + dim / 2) - dim * lgamma(a + 0.5) + (a + 0.5) * sum(log(q[i, ] + 1)) - (a + dim / 2) * log(sum(q[i, ]) + 1)\n }\n dc <- exp(logdc)\n dc[which(q == Inf)] <- 0\n if (log == TRUE) {\n out <- logdc\n } else {\n out <- dc\n }\n return(out)\n}\n\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#' \\dontrun{\n#'\n#' dcMGL180.multi(u = cbind(c(0.6, 0.1, 0.5), c(0.3, 0.9, 0.2)), pars = 2, log = FALSE)\n#'\n#' dcMGL180.multi(u = cbind(c(0.6, 0.1), c(0.3, 0.9), c(0.5, 0.6)), pars = 2, log = TRUE)\n#' }\ndcMGL180.multi <- function(u, pars, log = FALSE) {\n dcMGL.multi(u = 1 - u, pars = pars, log = log)\n}\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#' # 2-dim MGL copula\n#' pcMGL.multi(u = cbind(c(0.5, 0.5), c(0.01, 0.9)), pars = 3)\n#' # 3-dim MGL copula\n#' pcMGL.multi(u = cbind(c(0, 0.2, 0.5), c(0.5, 0.2, 0.5), c(0.01, 0.5, 0.9)), pars = 3)\npcMGL.multi <- function(u, pars) {\n # dim <- ncol(u)\n a <- 1 / pars[1]\n\n q <- (qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a)))\n z <- 0\n for (i in seq_len(nrow(u))) {\n if (any(q[i, ] %in% Inf)) {\n z[i] <- 0\n } else {\n temp <- as.vector(q[i, ])\n fin <- function(theta) { # rely on a\n # theta <- as.vector()\n m <- pracma::erfc((temp * theta)^0.5)\n k <- base::prod(m)\n out <- k * theta^(a - 1) * exp(-theta) / gamma(a)\n out\n }\n fin <- Vectorize(fin)\n z[i] <- as.numeric(pracma::integral(\n fun = fin,\n xmin = 0,\n xmax = Inf, method = \"Clenshaw\"\n ))\n }\n }\n return(z) # rely on k\n}\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#' pcMGL180.multi(u = cbind(c(0.5, 0.5), c(0.01, 0.9)), pars = 3)\npcMGL180.multi <- function(u, pars) {\n # dim <- ncol(u)\n delta <- pars[1]\n\n q <- (qbeta(u, shape1 = 0.5, shape2 = delta) / (1 - qbeta(u, shape1 = 0.5, shape2 = delta)))\n z <- 0\n for (i in seq_len(nrow(u))) {\n # if(any(q[i,] %in% Inf)) {\n # z[i] <- 0\n # } else {\n temp <- as.vector(q[i, ])\n fin <- function(theta) { # rely on theta\n m <- pgamma(q = temp / theta, shape = 0.5, scale = 1)\n k <- base::prod(m)\n out <- k * theta^(-(delta + 1)) * exp(-1 / theta) / gamma(delta)\n out\n }\n fin <- Vectorize(fin)\n\n z[i] <- as.numeric(pracma::integral(\n fun = fin,\n xmin = 0,\n xmax = Inf, method = \"Clenshaw\"\n ))\n }\n return(z)\n}\n# pcMGL180.multi(u = cbind(c(0.5, 0.1), c(0.9, 0.1)), pars = 1.5)\n# pcMGB2.bivar(u1 = c(0.5, 0.1), u2 = c(0.9, 0.1), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)\n\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#' Usim <- rcMGL.multi(n = 1000, d = 2, pars = 1)\n#' plot(Usim)\nrcMGL.multi <- function(n, d, pars) {\n a <- 1 / pars\n dseq <- seq(1:(d - 1))\n anew <- c(a, a + dseq / 2)\n Iinv_trans <- function(u, a) {\n qbeta(1 - u, shape1 = 0.5, shape2 = a) / (1 - qbeta(1 - u, shape1 = 0.5, shape2 = a))\n }\n umat <- matrix(data = runif(n * d, min = 0, max = 1), nrow = n, ncol = d)\n mmat <- qmat <- zmat <- Usim <- matrix(data = 0, nrow = n, ncol = d)\n\n for (j in seq_len(ncol(umat))) {\n qmat[, j] <- Iinv_trans(umat[, j], a = anew[j]) # column j denots the qj\n }\n\n mmat[, 1] <- qmat[, 1]\n mmat[, 2] <- (1 + mmat[, 1]) * qmat[, 2]\n if (d > 2) {\n for (j in 3:ncol(umat)) {\n tempmat <- mmat[, (1):(ncol(umat) - 1)]\n if (n == 1) {\n msum <- sum(tempmat)\n } else {\n msum <- apply(tempmat, MARGIN = 1, sum)\n }\n mmat[, j] <- (1 + msum) * qmat[, j]\n }\n }\n\n for (j in seq_len(ncol(zmat))) {\n k <- mmat[, j] / (mmat[, j] + 1)\n Usim[, j] <- 1 - pbeta(k, shape1 = 0.5, shape2 = a)\n }\n\n return(Usim)\n}\n\n\n#' @rdname cMGL.multi\n#' @export\n#' @examples\n#' Usim <- rcMGL180.multi(n = 1000, d = 2, pars = 1)\n#' plot(Usim)\nrcMGL180.multi <- function(n, d, pars) {\n 1 - rcMGL.multi(n = n, d = d, pars = pars)\n}\n", "meta": {"hexsha": "5ed28f1e6860d936db2d704f0d420e3e48c1941d", "size": 5406, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MGL-multi.r", "max_stars_repo_name": "lizhengxiao/rMGLReg", "max_stars_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/MGL-multi.r", "max_issues_repo_name": "lizhengxiao/rMGLReg", "max_issues_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-10T13:04:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T11:13:27.000Z", "max_forks_repo_path": "R/MGL-multi.r", "max_forks_repo_name": "lizhengxiao/rMGLReg", "max_forks_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.064516129, "max_line_length": 216, "alphanum_fraction": 0.5384757677, "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4797412012883977}} {"text": "#' Plot annual MSY\r\n#' \r\n#' Plot values associated with MSY using year-specific inputs.\r\n#' @param asap name of the variable that read in the asap.rdat file\r\n#' @param a1 list file produced by grab.aux.files function\r\n#' @param save.plots save individual plots\r\n#' @param od output directory for plots and csv files \r\n#' @param plotf type of plot to save\r\n#' @export\r\n\r\nPlotAnnualMSY <- function(asap,a1,save.plots,od,plotf){\r\n \r\n h.vals <- asap$SR.annual.parms$steepness.vec\r\n recr.par <- h.vals\r\n \r\n \r\n if (asap$control.parms$phases$phase.steepness>0 & max(h.vals)<1 ) { # test to make sure steepness was estimated\r\n \r\n nages<- asap$parms$nages\r\n nyears <- asap$parms$nyears\r\n years <- seq(asap$parms$styr,asap$parms$endyr) \r\n if (asap$options$isfecund == 1){\r\n fec.age <- asap$WAA.mats$WAA.ssb / asap$WAA.mats$WAA.ssb # matrix of 1s \r\n }else{\r\n fec.age <- asap$WAA.mats$WAA.ssb \r\n }\r\n mat.age <- asap$maturity\r\n wgt.age <- asap$WAA.mats$WAA.catch.all\r\n M.age <- asap$M.age\r\n sel.mat <- asap$F.age/apply(asap$F.age,1,max)\r\n \r\n spawn.time <- asap$options$frac.yr.spawn\r\n \r\n \r\n \r\n ahat.vals <- 4*h.vals/(1-h.vals)\r\n R0.vals <- asap$SR.annual.parms$R0.vec\r\n sr0.vals <- asap$SR.annual.parms$s.per.r.vec\r\n MSY.soln <- matrix(NA, nrow=9, ncol=nyears)\r\n rownames(MSY.soln) <- c(\"Fmsy\", \"MSY\", \"SPRmsy\", \"SSBmsy\", \"Rmsy\", \"YPRmsy\",\r\n \"Rel.SSBmsy\", \"Rel.Rmsy\", \"Conv.Code\")\r\n colnames(MSY.soln) <- seq(asap$parms$styr, asap$parms$endyr)\r\n \r\n for (i in 1:nyears) { \r\n F.start=0.25\r\n get.yield.f.min <- function(F.start) {\r\n temp.spr = s.per.recr(nages=nages, fec.age=fec.age[i,], mat.age=mat.age[i,], M.age= M.age[i,], F.mult=F.start, sel.age=sel.mat[i,], spawn.time=spawn.time) \r\n temp.ypr = ypr(nages=nages, wgt.age=wgt.age[i,], M.age=M.age[i,], F.mult=F.start, sel.age=sel.mat[i,] )\r\n temp.SSB = ssb.eq( recr.par=ahat.vals[i], R0.BH=R0.vals[i], spr=temp.spr, spr0=sr0.vals[i], is.steepness=F )\r\n yield = temp.ypr*temp.SSB/temp.spr #harvest in weight\r\n yy=-1*yield\r\n return(yy) \r\n } # end get.yield.f.min function\r\n \r\n F.nlmin <- nlminb( start=F.start , objective=get.yield.f.min, lower=0.01, upper=3.0,\r\n control=list(eval.max=500, iter.max=200 ) )\r\n \r\n \r\n \r\n MSY.soln[1, i] <- F.nlmin$par #Fmsy\r\n MSY.soln[2, i] <- -1*F.nlmin$objective #MSY\r\n \r\n # calculate other MSY quantities\r\n spr.nlmin <- s.per.recr(nages=nages, fec.age=fec.age[i,], mat.age=mat.age[i,], M.age= M.age[i,], F.mult=F.nlmin$par, sel.age=sel.mat[i,], spawn.time=spawn.time) \r\n MSY.soln[3, i] <- spr.nlmin/sr0.vals[i] #SPRmsy\r\n \r\n ssb.nlmin <- ssb.eq( recr.par=ahat.vals[i], R0.BH=R0.vals[i], spr=spr.nlmin, spr0=sr0.vals[i], is.steepness=F )\r\n MSY.soln[4, i] <- ssb.nlmin #SSBmsy\r\n \r\n \r\n Rmsy.nlmin <- bev.holt.alpha(S=ssb.nlmin,R0=R0.vals[i],recr.par=ahat.vals[i],spr0=sr0.vals[i])\r\n MSY.soln[5,i ] <- Rmsy.nlmin #Rmsy\r\n \r\n ypr.nlmin <- ypr(nages=nages, wgt.age=wgt.age[i,], M.age=M.age[i,], F.mult=F.nlmin$par, sel.age=sel.mat[i,] )\r\n MSY.soln[6,i ] <- ypr.nlmin #YPRmsy\r\n \r\n rel.ssb.nlmin <- ssb.nlmin/(R0.vals[i]*sr0.vals[i])\r\n MSY.soln[7, i] <- rel.ssb.nlmin #SSBmsy/SSB0\r\n \r\n MSY.soln[8, i] <- Rmsy.nlmin/R0.vals[i] #Rmsy/R0\r\n \r\n MSY.soln[9, i] <- F.nlmin$convergence #code=0 indicates convergence\r\n } # end i-loop over nyears\r\n \r\n f.hist <- hist(MSY.soln[1,], plot=F)\r\n MSY.hist <- hist(MSY.soln[2,], plot=F)\r\n R.hist <- hist(MSY.soln[5,], plot=F ) \r\n S.hist <- hist(MSY.soln[4,], plot=F ) \r\n \r\n h.hist <- hist(h.vals, plot=F)\r\n SPR.hist <- hist(MSY.soln[3,], plot=F)\r\n R0.hist <- hist(R0.vals, plot=F ) \r\n S0.hist <- hist(asap$SR.annual.parms$S0.vec, plot=F ) \r\n \r\n par(mfrow=c(2,2), mar=c(4,4,2,2), oma=c(0,0,2,0) )\r\n \r\n plot(f.hist$mids, f.hist$counts, xlab=\"Full F\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(f.hist$counts)) )\r\n lines(f.hist$mids, f.hist$counts, lwd=2)\r\n plot(S.hist$mids, S.hist$counts, xlab=\"SSB.MSY\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(S.hist$counts)) )\r\n lines(S.hist$mids, S.hist$counts, lwd=2)\r\n plot(MSY.hist$mids, MSY.hist$counts, xlab=\"MSY\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(MSY.hist$counts)) ) \r\n lines(MSY.hist$mids, MSY.hist$counts, lwd=2)\r\n plot(R.hist$mids, R.hist$counts, xlab=\"R.MSY\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(R.hist$counts)) )\r\n lines(R.hist$mids, R.hist$counts, lwd=2)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n if (save.plots) savePlot(paste0(od, \"MSY.4panel.hist1.\", plotf), type=plotf) \r\n \r\n \r\n plot(h.hist$mids, h.hist$counts, xlab=\"steepness\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(h.hist$counts)) )\r\n lines(h.hist$mids, h.hist$counts, lwd=2)\r\n plot(S0.hist$mids, S0.hist$counts, xlab=\"SSB0\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(S0.hist$counts)) )\r\n lines(S0.hist$mids, S0.hist$counts, lwd=2)\r\n plot(SPR.hist$mids, SPR.hist$counts, xlab=\"SPR.MSY\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(SPR.hist$counts)) )\r\n lines(SPR.hist$mids, SPR.hist$counts, lwd=2)\r\n plot(R0.hist$mids, R0.hist$counts, xlab=\"R0\", ylab=\"Frequency\", type='h', lwd=2, ylim=c(0, max(R0.hist$counts)) )\r\n lines(R0.hist$mids, R0.hist$counts, lwd=2)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n if (save.plots) savePlot(paste0(od, \"MSY.4panel.hist2.\", plotf), type=plotf) \r\n \r\n \r\n par(mfrow=c(1,1), mar=c(4,4,2,2) )\r\n \r\n h.order <- order(h.vals)\r\n steep.spr <- cbind(h.vals[h.order], MSY.soln[3,h.order])\r\n \r\n plot(steep.spr[,1], steep.spr[,2], xlab=\"Steepness\", ylab=\"SPR.MSY\", xlim=c(0.2,1), ylim=c(0,1),\r\n type='p', pch=16, col='blue3' )\r\n points(h.vals[1], MSY.soln[3,1], pch=16, cex=1.5, col=\"green3\") \r\n points(h.vals[nyears], MSY.soln[3,nyears], pch=16, cex=1.5, col=\"orange2\") \r\n legend('top', legend=c(\"First Year\", \"Last Year\"), pch=c(16,16), col=c(\"green3\", \"orange2\") )\r\n title (paste0(\"Annual Steepness and SPR.MSY (from S-R curve)\"), outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"MSY.h.vs.SPR.\", plotf), type=plotf) \r\n \r\n plot(years, MSY.soln[1,], xlab=\"Year\", ylab=\"Full F at MSY\", ylim=1.1*c(0, max(MSY.soln[1,])), type='l', lwd=2 ) \r\n points(years, MSY.soln[1,], pch=10)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"Annual.Fmsy.\", plotf), type=plotf) \r\n \r\n plot(years, MSY.soln[2,], xlab=\"Year\", ylab=\"MSY\", ylim=1.1*c(0, max(MSY.soln[2,])), type='l', lwd=2 ) \r\n points(years, MSY.soln[2,], pch=10)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"Annual.MSY.\", plotf), type=plotf) \r\n \r\n plot(years, MSY.soln[3,], xlab=\"Year\", ylab=\"%SPR at MSY\", ylim=1.1*c(0, 1), type='l', lwd=2 ) \r\n points(years, MSY.soln[3,], pch=10)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"Annual.SPR.MSY.\", plotf), type=plotf) \r\n \r\n plot(years, MSY.soln[4,], xlab=\"Year\", ylab=\"SSB at MSY\", ylim=1.1*c(0, max(MSY.soln[4,])), type='l', lwd=2 ) \r\n points(years, MSY.soln[4,], pch=10)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"Annual.SSB.MSY.\", plotf), type=plotf) \r\n \r\n plot(years, MSY.soln[5,], xlab=\"Year\", ylab=\"Recruitment at MSY\", ylim=1.1*c(0, max(MSY.soln[5,])), type='l', lwd=2 ) \r\n points(years, MSY.soln[5,], pch=10)\r\n title (paste0(\"Annual MSY Reference Points (from S-R curve)\"), \r\n outer=T, line=-1 ) \r\n \r\n if (save.plots) savePlot(paste0(od, \"Annual.Recr.MSY.\", plotf), type=plotf) \r\n \r\n frep1 <-asap$options$Freport.agemin\r\n frep2 <-asap$options$Freport.agemax\r\n if (frep1==frep2) freport <-MSY.soln[1,frep1:frep2]*sel.mat[,frep1:frep2]\r\n if (frep2>frep1) freport <-apply(MSY.soln[1,frep1:frep2]*sel.mat[,frep1:frep2],1,mean)\r\n freport.label <- paste0(\"Freport_\",frep1,\"-\",frep2)\r\n MSY.soln<- rbind(MSY.soln, freport)\r\n rownames(MSY.soln) <- \r\n c(\"Fmsy\", \"MSY\", \"SPRmsy\", \"SSBmsy\", \"Rmsy\", \"YPRmsy\",\r\n \"Rel.SSBmsy\", \"Rel.Rmsy\", \"Conv.Code\",paste0(\"Freport_\",frep1,\"-\",frep2))\r\n \r\n asap.name <- a1$asap.name\r\n write.csv( t(MSY.soln), file=paste0(od, \"MSY.soln.values_\", asap.name, \".csv\"), row.names=T )\r\n\r\n } # end test for steepness phase>0\r\n \r\n return()\r\n} # end function\r\n", "meta": {"hexsha": "f1afea22d3fcc305c19a2300836d21e98da280ad", "size": 8899, "ext": "r", "lang": "R", "max_stars_repo_path": "R/plot_annual_MSY.r", "max_stars_repo_name": "liz-brooks/ASAPplots", "max_stars_repo_head_hexsha": "f42263d80f28b9de5d1abd2f87676d26bb30d4ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-25T20:24:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T20:54:15.000Z", "max_issues_repo_path": "R/plot_annual_MSY.r", "max_issues_repo_name": "liz-brooks/ASAPplots", "max_issues_repo_head_hexsha": "f42263d80f28b9de5d1abd2f87676d26bb30d4ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-04-11T18:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T21:03:06.000Z", "max_forks_repo_path": "R/plot_annual_MSY.r", "max_forks_repo_name": "liz-brooks/ASAPplots", "max_forks_repo_head_hexsha": "f42263d80f28b9de5d1abd2f87676d26bb30d4ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-08-23T19:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T19:36:49.000Z", "avg_line_length": 48.6284153005, "max_line_length": 170, "alphanum_fraction": 0.5864703899, "num_tokens": 3314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4797165725920126}} {"text": "###############################################################################\n###############################################################################\n#\n#\n# Project: An exposure weighted warming\n# Team: Marcin Gajewski, Salma Al-Zadjali, Yasna Palmeiro Silva\n# \n# Analysis of UKCP18 dataset for \n# - Mean air temperature at 1.5m (°C)\n# - Maximum air temperature at 1.5m (°C)\n# - Minimum air temperature at 1.5m (°C)\n#\n# In order to obtain meaningful results, we used monthly data.\n#\n# Based on the data, we calculated temperature anomalies, considering\n# a historical baseline of 20 years (1980-2000). \n# \n# In order to calculate population-weighted average anomalies, \n# we used population estimations from 2000 onward. \n#\n###############################################################################\n###############################################################################\n\n# Libraries we need\nlibrary(raster) \nlibrary(sf)\nlibrary(sp)\nlibrary(ncdf4)\nlibrary(ggplot2)\nlibrary(rgdal)\nlibrary(rlang)\nlibrary(dplyr)\nlibrary(lubridate)\nlibrary(zoo)\nlibrary(stringr)\nlibrary(tidyverse) #include readr\nlibrary(ggthemes)\nlibrary(ggpubr)\n\n###############################################################################\n# SHAPEFILES\n###############################################################################\n\n# We need: ukcp18-uk-land-country-hires \nuk_borders <- st_read(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/ukcp-spatial-files/spatial-files/ukcp18-uk-land-country-hires/ukcp18-uk-land-country-hires.shp\")\nas_Spatial(uk_borders)\nplot(uk_borders)\n\nuk_borders$geo_region # \"Channel Islands\", \"England\", \"Isle of Man\", \"Northern Ireland\", \"Scotland\", \"Wales\"\n\n# In order to obtain some data for each region, we create subsets of polygons\nCha_borders <- uk_borders[uk_borders$geo_region == \"Channel Islands\",]\nEng_borders <- uk_borders[uk_borders$geo_region == \"England\",]\nIsl_borders <- uk_borders[uk_borders$geo_region == \"Isle of Man\",]\nNIr_borders <- uk_borders[uk_borders$geo_region == \"Northern Ireland\",]\nSco_borders <- uk_borders[uk_borders$geo_region == \"Scotland\",]\nWal_borders <- uk_borders[uk_borders$geo_region == \"Wales\",]\n\n###############################################################################\n# POPULATION\n###############################################################################\n\n# Dataset: SSP5 population projections on the OSGB grid \npop.nc <- nc_open(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/population/population-projections-ssp5-total.nc\")\nprint(pop.nc)\nnames(pop.nc$var) #\"crs\" \"ssp\"\n\npop <- brick(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/population/population-projections-ssp5-total.nc\")\npop # This dataset has 11 years: 2000, 2010, 2020, 2030, 2040, 2050, 2060, 2070, 2080, 2090, 2100.\n # We checked that resolution, extent, and CRS were the same for temperature projections. \n # This dataset contains absolute number of people living per grid.\n\n#################################################\n# Manipulation & interpolation\n#################################################\n\n# Masking (M) and cropping according to uk_borders\npopM <- mask(pop, uk_borders) %>% crop(uk_borders)\n\n# Checking a time series of population\npop_TS <- c(cellStats(popM, sum, na.rm=T))\npop_TS <- ts(pop_TS)\nplot(pop_TS) # Population estimation grows in a approximately linear fashion.\n\n# We can linearly interpolate years between given years\n# formula for linear interpolation: P(T) = P1 + [(P2-P1)*(T-T1)/(T2-T1)]\n# Interpolation is done decade by decade to preserve some different growth rates. \n\nUKpop2000_2100 <- brick(nrows=109, ncols=55, xmn=0, xmx=660000, ymn=-84000, ymx=1224000 , nl=81)\n\nUKpop2000_2100[[1]] <- popM[[1]] #2000\nUKpop2000_2100[[2]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2001-2000)) / (2010-2000))\nUKpop2000_2100[[3]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2002-2000)) / (2010-2000))\nUKpop2000_2100[[4]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2003-2000)) / (2010-2000))\nUKpop2000_2100[[5]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2004-2000)) / (2010-2000))\nUKpop2000_2100[[6]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2005-2000)) / (2010-2000))\nUKpop2000_2100[[7]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2006-2000)) / (2010-2000))\nUKpop2000_2100[[8]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2007-2000)) / (2010-2000))\nUKpop2000_2100[[9]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2008-2000)) / (2010-2000))\nUKpop2000_2100[[10]] <- popM[[1]] + (((popM[[2]] - popM[[1]]) * (2009-2000)) / (2010-2000))\nUKpop2000_2100[[11]] <- popM[[2]] #2010\nUKpop2000_2100[[12]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2011-2010)) / (2020-2010))\nUKpop2000_2100[[13]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2012-2010)) / (2020-2010))\nUKpop2000_2100[[14]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2013-2010)) / (2020-2010))\nUKpop2000_2100[[15]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2014-2010)) / (2020-2010))\nUKpop2000_2100[[16]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2015-2010)) / (2020-2010))\nUKpop2000_2100[[17]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2016-2010)) / (2020-2010))\nUKpop2000_2100[[18]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2017-2010)) / (2020-2010))\nUKpop2000_2100[[19]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2018-2010)) / (2020-2010))\nUKpop2000_2100[[20]] <- popM[[2]] + (((popM[[3]] - popM[[2]]) * (2019-2010)) / (2020-2010))\nUKpop2000_2100[[21]] <- popM[[3]] #2020\nUKpop2000_2100[[22]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2021-2020)) / (2030-2020))\nUKpop2000_2100[[23]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2022-2020)) / (2030-2020))\nUKpop2000_2100[[24]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2023-2020)) / (2030-2020))\nUKpop2000_2100[[25]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2024-2020)) / (2030-2020))\nUKpop2000_2100[[26]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2025-2020)) / (2030-2020))\nUKpop2000_2100[[27]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2026-2020)) / (2030-2020))\nUKpop2000_2100[[28]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2027-2020)) / (2030-2020))\nUKpop2000_2100[[29]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2028-2020)) / (2030-2020))\nUKpop2000_2100[[30]] <- popM[[3]] + (((popM[[4]] - popM[[3]]) * (2029-2020)) / (2030-2020))\nUKpop2000_2100[[31]] <- popM[[4]] #2030\nUKpop2000_2100[[32]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2031-2030)) / (2040-2030))\nUKpop2000_2100[[33]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2032-2030)) / (2040-2030))\nUKpop2000_2100[[34]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2033-2030)) / (2040-2030))\nUKpop2000_2100[[35]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2034-2030)) / (2040-2030))\nUKpop2000_2100[[36]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2035-2030)) / (2040-2030))\nUKpop2000_2100[[37]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2036-2030)) / (2040-2030))\nUKpop2000_2100[[38]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2037-2030)) / (2040-2030))\nUKpop2000_2100[[39]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2038-2030)) / (2040-2030))\nUKpop2000_2100[[40]] <- popM[[4]] + (((popM[[5]] - popM[[4]]) * (2039-2030)) / (2040-2030))\nUKpop2000_2100[[41]] <- popM[[5]] #2040\nUKpop2000_2100[[42]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2041-2040)) / (2050-2040))\nUKpop2000_2100[[43]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2042-2040)) / (2050-2040))\nUKpop2000_2100[[44]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2043-2040)) / (2050-2040))\nUKpop2000_2100[[45]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2044-2040)) / (2050-2040))\nUKpop2000_2100[[46]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2045-2040)) / (2050-2040))\nUKpop2000_2100[[47]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2046-2040)) / (2050-2040))\nUKpop2000_2100[[48]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2047-2040)) / (2050-2040))\nUKpop2000_2100[[49]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2048-2040)) / (2050-2040))\nUKpop2000_2100[[50]] <- popM[[5]] + (((popM[[6]] - popM[[5]]) * (2049-2040)) / (2050-2040))\nUKpop2000_2100[[51]] <- popM[[6]] #2050\nUKpop2000_2100[[52]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2051-2050)) / (2060-2050))\nUKpop2000_2100[[53]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2052-2050)) / (2060-2050))\nUKpop2000_2100[[54]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2053-2050)) / (2060-2050))\nUKpop2000_2100[[55]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2054-2050)) / (2060-2050))\nUKpop2000_2100[[56]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2055-2050)) / (2060-2050))\nUKpop2000_2100[[57]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2056-2050)) / (2060-2050))\nUKpop2000_2100[[58]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2057-2050)) / (2060-2050))\nUKpop2000_2100[[59]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2058-2050)) / (2060-2050))\nUKpop2000_2100[[60]] <- popM[[6]] + (((popM[[7]] - popM[[6]]) * (2059-2050)) / (2060-2050))\nUKpop2000_2100[[61]] <- popM[[7]] #2060\nUKpop2000_2100[[62]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2061-2060)) / (2070-2060))\nUKpop2000_2100[[63]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2062-2060)) / (2070-2060))\nUKpop2000_2100[[64]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2063-2060)) / (2070-2060))\nUKpop2000_2100[[65]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2064-2060)) / (2070-2060))\nUKpop2000_2100[[66]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2065-2060)) / (2070-2060))\nUKpop2000_2100[[67]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2066-2060)) / (2070-2060))\nUKpop2000_2100[[68]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2067-2060)) / (2070-2060))\nUKpop2000_2100[[69]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2068-2060)) / (2070-2060))\nUKpop2000_2100[[70]] <- popM[[7]] + (((popM[[8]] - popM[[7]]) * (2069-2060)) / (2070-2060))\nUKpop2000_2100[[71]] <- popM[[8]] #2070\nUKpop2000_2100[[72]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2071-2070)) / (2080-2070))\nUKpop2000_2100[[73]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2072-2070)) / (2080-2070))\nUKpop2000_2100[[74]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2073-2070)) / (2080-2070))\nUKpop2000_2100[[75]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2074-2070)) / (2080-2070))\nUKpop2000_2100[[76]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2075-2070)) / (2080-2070))\nUKpop2000_2100[[77]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2076-2070)) / (2080-2070))\nUKpop2000_2100[[78]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2077-2070)) / (2080-2070))\nUKpop2000_2100[[79]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2078-2070)) / (2080-2070))\nUKpop2000_2100[[80]] <- popM[[8]] + (((popM[[9]] - popM[[8]]) * (2079-2070)) / (2080-2070))\nUKpop2000_2100[[81]] <- popM[[9]] #2080\n\nyears <- seq(as.Date(\"2000/01/01\"), by = \"year\", length.out = 81)\nUKpop2000_2100 <- setZ(UKpop2000_2100, years, \"years\")\nnames(UKpop2000_2100) <- years\n\n#################################################\n# Getting the proportion of people per grid\n#################################################\n# To get population weighted average, we need the fraction of the population\n# that lives in each grid. So, we need to calculate D = pop in each grid / pop_TS\n\n# UK\nUKpop_TS2000_2100 <- c(cellStats(UKpop2000_2100, sum, na.rm=T)) # Total per layer\n\nUKpopD2000_2100 <- brick(nrows=109, ncols=55, xmn=0, xmx=660000, ymn=-84000, ymx=1224000 , nl=81)\n\nfor (i in 1:nlayers(UKpop2000_2100)){\n UKpopD2000_2100[[i]] <- (UKpop2000_2100[[i]] / UKpop_TS2000_2100[i] )\n} # UKpopD2000_2100 is a RasterBrick with the proportion of people living in each grid.\n\n\n# Population by regions - To calculate regional exposures\n# Channel Islands \nCha_pop2000_2100 <- mask(UKpop2000_2100, Cha_borders) %>% crop(Cha_borders) #NAs (due to size?)\n\n# England\nEng_pop2000_2100 <- mask(UKpop2000_2100, Eng_borders) %>% crop(Eng_borders)\nEng_pop_TS2000_2100 <- c(cellStats(Eng_pop2000_2100, sum, na.rm=T))\nEng_popD2000_2100 <- brick(nrows=55, ncols=48, xmn=84000, xmx=660000, ymn=0, ymx=660000, nl=81)\nfor (i in 1:nlayers(Eng_pop2000_2100)){\n Eng_popD2000_2100[[i]] <- (Eng_pop2000_2100[[i]] / Eng_pop_TS2000_2100[i] )\n} \n\n# Isle of Man\nIsl_pop2000_2100 <- mask(UKpop2000_2100, Isl_borders) %>% crop(Isl_borders)\nIsl_pop_TS2000_2100 <- c(cellStats(Isl_pop2000_2100, sum, na.rm=T))\nIsl_popD2000_2100 <- brick(nrows=3, ncols=3, xmn=216000, xmx=252000, ymn=468000, ymx=504000, nl=81)\nfor (i in 1:nlayers(Isl_pop2000_2100)){\n Isl_popD2000_2100[[i]] <- (Isl_pop2000_2100[[i]] / Isl_pop_TS2000_2100[i] )\n} \n\n# Northen Ireland\nNIr_pop2000_2100 <- mask(UKpop2000_2100, NIr_borders) %>% crop(NIr_borders)\nNIr_pop_TS2000_2100 <- c(cellStats(NIr_pop2000_2100, sum, na.rm=T))\nNIr_popD2000_2100 <- brick(nrows=12, ncols=15, xmn=0, xmx=180000, ymn=468000, ymx=612000, nl=81)\nfor (i in 1:nlayers(NIr_pop2000_2100)){\n NIr_popD2000_2100[[i]] <- (NIr_pop2000_2100[[i]] / NIr_pop_TS2000_2100[i] )\n} \n\n# Scotland\nSco_pop2000_2100 <- mask(UKpop2000_2100, Sco_borders) %>% crop(Sco_borders)\nSco_pop_TS2000_2100 <- c(cellStats(Sco_pop2000_2100, sum, na.rm=T))\nSco_popD2000_2100 <- brick(nrows=58, ncols=39, xmn=0, xmx=468000, ymn=528000, ymx=1224000, nl=81)\nfor (i in 1:nlayers(Sco_pop2000_2100)){\n Sco_popD2000_2100[[i]] <- (Sco_pop2000_2100[[i]] / Sco_pop_TS2000_2100[i] )\n} \n\n# Wales\nWal_pop2000_2100 <- mask(UKpop2000_2100, Wal_borders) %>% crop(Wal_borders)\nWal_pop_TS2000_2100 <- c(cellStats(Wal_pop2000_2100, sum, na.rm=T))\nWal_popD2000_2100 <- brick(nrows=19, ncols=17, xmn=156000, xmx=360000, ymn=168000, ymx=396000, nl=81)\nfor (i in 1:nlayers(Wal_pop2000_2100)){\n Wal_popD2000_2100[[i]] <- (Wal_pop2000_2100[[i]] / Wal_pop_TS2000_2100[i] )\n} \n\n\n###############################################################################\n# TEMPERATURE PROJECTIONS\n###############################################################################\n\ntasmin.nc <- nc_open(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmin_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\nprint(tasmin.nc)\nnames(tasmin.nc$var) #\"tasmin\"\ntasmin <- brick(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmin_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\ntasmin # 1200 layers = 100 years\n\ntasmax.nc <- nc_open(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmax_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\nprint(tasmax.nc)\nnames(tasmax.nc$var) #\"tasmax\"\ntasmax <- brick(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tasmax_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\n\ntas.nc <- nc_open(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tas_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\nprint(tas.nc)\nnames(tas.nc$var) #\"tasmin\"\ntas <- brick(\"/nfs/cfs/home4/rejb/rejbypa/UKCP18_R/mon/tas_rcp85_land-rcm_uk_12km_01_mon_198012-208011.nc\")\n\n#################################################\n# Masking and dates manipulations\n#################################################\n\n# Masking (M) and cropping some grids\ntasminM <- mask(tasmin, uk_borders) %>% crop(uk_borders)\ntasmaxM <- mask(tasmax, uk_borders) %>% crop(uk_borders)\ntasM <- mask(tas, uk_borders) %>% crop(uk_borders)\n\n# Standardized layers' dates - From .nc to rasterbrick there are some problems with layers' names. \nhead(names(tasminM)) # \"X1980.10.20\" \"X1980.11.19\" \"X1980.12.19\" \"X1981.01.18\" \"X1981.02.17\" \"X1981.03.19\"\ntail(names(tasminM)) # \"X2078.11.15\" \"X2078.12.15\" \"X2079.01.14\" \"X2079.02.13\" \"X2079.03.15\" \"X2079.04.14\"\n\ntime_layers <- seq(as.Date(\"1980/12/01\"), as.Date(\"2080/11/30\"), by = \"month\")\n\ntasminM <- setZ(tasminM, time_layers, \"months\")\nnames(tasminM) <- time_layers\n\ntasmaxM <- setZ(tasmaxM, time_layers, \"months\")\nnames(tasmaxM) <- time_layers\n\ntasM <- setZ(tasM, time_layers, \"months\")\nnames(tasM) <- time_layers\n\n#################################################\n# Anomaly calculations\n#################################################\n\n# First, we need to calculate averages by month to get \"historical\" baseline - 1980 Dec (nl= 1) to 2000 Nov (nl= 240)\n# We drop the layers we don't need (241:1200)\ntasmin1980_2000 <- dropLayer(tasminM, c(241:1200))\ntasmax1980_2000 <- dropLayer(tasmaxM, c(241:1200))\ntas1980_2000 <- dropLayer(tasM, c(241:1200))\n\nmonth_layers <- seq(as.Date(\"2000/12/1\"), by = \"month\", length.out = 12)\n\n# Using zApply, we have monthly means (of 20 Jans, 20 Febs...20 Decs). It stars from Dec-Nov\ntasminSA1980_2000 <- zApply(tasmin1980_2000, by=month, fun= mean, name = \"months\") \ntasminSA1980_2000 <- setZ(tasminSA1980_2000, month_layers, \"months\")\nnames(tasminSA1980_2000) <- month_layers \n\ntasmaxSA1980_2000 <- zApply(tasmax1980_2000, by=month, fun= mean, name = \"months\") \ntasmaxSA1980_2000 <- setZ(tasmaxSA1980_2000, month_layers, \"months\")\nnames(tasmaxSA1980_2000) <- month_layers \n\ntasSA1980_2000 <- zApply(tas1980_2000, by=month, fun= mean, name = \"months\")\ntasSA1980_2000 <- setZ(tasSA1980_2000, month_layers, \"months\")\nnames(tasSA1980_2000) <- month_layers\n\n# For current temperature: We're using from 2000 onward (Dec 1999 (nl= 229))\n# We drop layers we do not need (Dec 1980 to Nov 1999)\ntasmin2000_2080 <- dropLayer(tasminM, c(1:228))\ntasmax2000_2080 <- dropLayer(tasmaxM, c(1:228))\ntas2000_2080 <- dropLayer(tasM, c(1:228))\n\n# Now, we need to subtract current temperature minus historical temperature by month\nDec_layers <- seq(as.Date(\"1999/12/01\"), as.Date(\"2080/11/30\"), by = \"year\")\n\nTasMinAnom2000_2080 <-lapply(1:12, function(i) {\n m <- formatC(c(12,1:11), width = 2, flag= \"0\")[i]\n TasMinAnom <- (subset(tasmin2000_2080, which(substr(getZ(tasmin2000_2080),6,7) %in% c(m)))) - tasminSA1980_2000[[i]]\n if(m==\"12\") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,\"01\",sep= \"/\"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,\"01\",sep= \"/\"))}\n names(TasMinAnom) <- Dec_layers\n return(TasMinAnom)\n})\n\nTasMinAnom2000_2080 <- stack(TasMinAnom2000_2080)\n\nTasMaxAnom2000_2080 <-lapply(1:12, function(i) {\n m <- formatC(c(12,1:11), width = 2, flag= \"0\")[i]\n TasMaxAnom <- (subset(tasmax2000_2080, which(substr(getZ(tasmax2000_2080),6,7) %in% c(m)))) - tasmaxSA1980_2000[[i]]\n if(m==\"12\") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,\"01\",sep= \"/\"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,\"01\",sep= \"/\"))}\n names(TasMaxAnom) <- Dec_layers\n return(TasMaxAnom)\n})\n\nTasMaxAnom2000_2080 <- stack(TasMaxAnom2000_2080)\n\nTasAnom2000_2080 <-lapply(1:12, function(i) {\n m <- formatC(c(12,1:11), width = 2, flag= \"0\")[i]\n TasAnom <- (subset(tas2000_2080, which(substr(getZ(tas2000_2080),6,7) %in% c(m)))) - tasSA1980_2000[[i]]\n if(m==\"12\") {Dec_layers <- as.Date(sapply(1999:2079, paste,m,\"01\",sep= \"/\"))} else {Dec_layers <- as.Date(sapply(2000:2080, paste,m,\"01\",sep= \"/\"))}\n names(TasAnom) <- Dec_layers\n return(TasAnom)\n})\n\nTasAnom2000_2080 <- stack(TasAnom2000_2080)\n\n\nDec_layers <- seq(as.Date(\"1999/12/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nJan_layers <- seq(as.Date(\"2000/01/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nFeb_layers <- seq(as.Date(\"2000/02/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nMar_layers <- seq(as.Date(\"2000/03/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nApr_layers <- seq(as.Date(\"2000/04/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nMay_layers <- seq(as.Date(\"2000/05/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nJun_layers <- seq(as.Date(\"2000/06/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nJul_layers <- seq(as.Date(\"2000/07/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nAug_layers <- seq(as.Date(\"2000/08/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nSep_layers <- seq(as.Date(\"2000/09/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nOct_layers <- seq(as.Date(\"2000/10/01\"), as.Date(\"2080/11/30\"), by = \"year\")\nNov_layers <- seq(as.Date(\"2000/11/01\"), as.Date(\"2080/11/30\"), by = \"year\")\n\nAnom2000_2080_layers <- c(Dec_layers, Jan_layers, Feb_layers, Mar_layers, Apr_layers, May_layers,\n Jun_layers, Jul_layers, Aug_layers, Sep_layers, Oct_layers, Nov_layers)\n\nTasMinAnom2000_2080 <- setZ(TasMinAnom2000_2080 , Anom2000_2080_layers, name= \"Date\")\nTasMaxAnom2000_2080 <- setZ(TasMaxAnom2000_2080, Anom2000_2080_layers, name= \"Date\")\nTasAnom2000_2080 <- setZ(TasAnom2000_2080, Anom2000_2080_layers, name= \"Date\")\n\n# Sorting raster layers by date\nTasMinAnom2000_2080 <- TasMinAnom2000_2080[[order(getZ(TasMinAnom2000_2080))]]\nTasMaxAnom2000_2080 <- TasMaxAnom2000_2080[[order(getZ(TasMaxAnom2000_2080))]]\nTasAnom2000_2080 <- TasAnom2000_2080[[order(getZ(TasAnom2000_2080))]]\n\n#################################################\n# Area-weighted Average Monthly T Anomalies from 2000-2080\n#################################################\nUK_AWTasMinAnom2000_2080 <- c(cellStats(TasMinAnom2000_2080, mean, na.rm=T))\nUK_AWTasMaxAnom2000_2080 <- c(cellStats(TasMaxAnom2000_2080, mean, na.rm=T))\nUK_AWTasAnom2000_2080 <- c(cellStats(TasAnom2000_2080, mean, na.rm=T))\n\n# England\nEng_TasMinAnom2000_2080 <- mask(TasMinAnom2000_2080, Eng_borders) %>% crop(Eng_borders)\nEng_TasMaxAnom2000_2080 <- mask(TasMaxAnom2000_2080, Eng_borders) %>% crop(Eng_borders)\nEng_TasAnom2000_2080 <- mask(TasAnom2000_2080, Eng_borders) %>% crop(Eng_borders)\n\nEng_AWTasMinAnom2000_2080 <- c(cellStats(Eng_TasMinAnom2000_2080, mean, na.rm=T))\nEng_AWTasMaxAnom2000_2080 <- c(cellStats(Eng_TasMaxAnom2000_2080, mean, na.rm=T))\nEng_AWTasAnom2000_2080 <- c(cellStats(Eng_TasAnom2000_2080, mean, na.rm=T))\n\n# Isle of Man\nIsl_TasMinAnom2000_2080 <- mask(TasMinAnom2000_2080, Isl_borders) %>% crop(Isl_borders)\nIsl_TasMaxAnom2000_2080 <- mask(TasMaxAnom2000_2080, Isl_borders) %>% crop(Isl_borders)\nIsl_TasAnom2000_2080 <- mask(TasAnom2000_2080, Isl_borders) %>% crop(Isl_borders)\n\nIsl_AWTasMinAnom2000_2080 <- c(cellStats(Isl_TasMinAnom2000_2080, mean, na.rm=T))\nIsl_AWTasMaxAnom2000_2080 <- c(cellStats(Isl_TasMaxAnom2000_2080, mean, na.rm=T))\nIsl_AWTasAnom2000_2080 <- c(cellStats(Isl_TasAnom2000_2080, mean, na.rm=T))\n\n# Northen Ireland\nNIr_TasMinAnom2000_2080 <- mask(TasMinAnom2000_2080, NIr_borders) %>% crop(NIr_borders)\nNIr_TasMaxAnom2000_2080 <- mask(TasMaxAnom2000_2080, NIr_borders) %>% crop(NIr_borders)\nNIr_TasAnom2000_2080 <- mask(TasAnom2000_2080, NIr_borders) %>% crop(NIr_borders)\n\nNIr_AWTasMinAnom2000_2080 <- c(cellStats(NIr_TasMinAnom2000_2080, mean, na.rm=T))\nNIr_AWTasMaxAnom2000_2080 <- c(cellStats(NIr_TasMaxAnom2000_2080, mean, na.rm=T))\nNIr_AWTasAnom2000_2080 <- c(cellStats(NIr_TasAnom2000_2080, mean, na.rm=T))\n\n# Scotland\nSco_TasMinAnom2000_2080 <- mask(TasMinAnom2000_2080, Sco_borders) %>% crop(Sco_borders)\nSco_TasMaxAnom2000_2080 <- mask(TasMaxAnom2000_2080, Sco_borders) %>% crop(Sco_borders)\nSco_TasAnom2000_2080 <- mask(TasAnom2000_2080, Sco_borders) %>% crop(Sco_borders)\n\nSco_AWTasMinAnom2000_2080 <- c(cellStats(Sco_TasMinAnom2000_2080, mean, na.rm=T))\nSco_AWTasMaxAnom2000_2080 <- c(cellStats(Sco_TasMaxAnom2000_2080, mean, na.rm=T))\nSco_AWTasAnom2000_2080 <- c(cellStats(Sco_TasAnom2000_2080, mean, na.rm=T))\n\n# Wales\nWal_TasMinAnom2000_2080 <- mask(TasMinAnom2000_2080, Wal_borders) %>% crop(Wal_borders)\nWal_TasMaxAnom2000_2080 <- mask(TasMaxAnom2000_2080, Wal_borders) %>% crop(Wal_borders)\nWal_TasAnom2000_2080 <- mask(TasAnom2000_2080, Wal_borders) %>% crop(Wal_borders)\n\nWal_AWTasMinAnom2000_2080 <- c(cellStats(Wal_TasMinAnom2000_2080, mean, na.rm=T))\nWal_AWTasMaxAnom2000_2080 <- c(cellStats(Wal_TasMaxAnom2000_2080, mean, na.rm=T))\nWal_AWTasAnom2000_2080 <- c(cellStats(Wal_TasAnom2000_2080, mean, na.rm=T))\n\n\n#################################################\n# Population-weighted Average Monthly T Anomalies\n#################################################\n\n# UK\nUK_PWTasMinAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))\nUK_PWTasMaxAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))\nUK_PWTasAnom2000_2080 <- brick(extend(UKpopD2000_2100, UKpopD2000_2100))\nfor (i in 1:nlayers(UKpopD2000_2100)){\n for (j in 1:12) {\n UK_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- TasMinAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]\n UK_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- TasMaxAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]\n UK_PWTasAnom2000_2080[[(12*(i-1))+j]] <- TasAnom2000_2080[[(12*(i-1))+j]] * UKpopD2000_2100[[i]]\n }\n}\n\nUKv_PWTasMinAnom2000_2080 <- c(cellStats(UK_PWTasMinAnom2000_2080, sum, na.rm=T))\nUKv_PWTasMaxAnom2000_2080 <- c(cellStats(UK_PWTasMaxAnom2000_2080, sum, na.rm=T))\nUKv_PWTasAnom2000_2080 <- c(cellStats(UK_PWTasAnom2000_2080, sum, na.rm=T))\n\n# Eng\nEng_PWTasMinAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))\nEng_PWTasMaxAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))\nEng_PWTasAnom2000_2080 <- brick(extend(Eng_popD2000_2100, Eng_popD2000_2100))\nfor (i in 1:nlayers(Eng_popD2000_2100)){\n for (j in 1:12) {\n Eng_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasMinAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]\n Eng_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]\n Eng_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Eng_TasAnom2000_2080[[(12*(i-1))+j]] * Eng_popD2000_2100[[i]]\n }\n}\n\nEngv_PWTasMinAnom2000_2080 <- c(cellStats(Eng_PWTasMinAnom2000_2080, sum, na.rm=T))\nEngv_PWTasMaxAnom2000_2080 <- c(cellStats(Eng_PWTasMaxAnom2000_2080, sum, na.rm=T))\nEngv_PWTasAnom2000_2080 <- c(cellStats(Eng_PWTasAnom2000_2080, sum, na.rm=T))\n\n# NIr\nNIr_PWTasMinAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))\nNIr_PWTasMaxAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))\nNIr_PWTasAnom2000_2080 <- brick(extend(NIr_popD2000_2100, NIr_popD2000_2100))\nfor (i in 1:nlayers(NIr_popD2000_2100)){\n for (j in 1:12) {\n NIr_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasMinAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]\n NIr_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasMaxAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]\n NIr_PWTasAnom2000_2080[[(12*(i-1))+j]] <- NIr_TasAnom2000_2080[[(12*(i-1))+j]] * NIr_popD2000_2100[[i]]\n }\n}\n\nNIrv_PWTasMinAnom2000_2080 <- c(cellStats(NIr_PWTasMinAnom2000_2080, sum, na.rm=T))\nNIrv_PWTasMaxAnom2000_2080 <- c(cellStats(NIr_PWTasMaxAnom2000_2080, sum, na.rm=T))\nNIrv_PWTasAnom2000_2080 <- c(cellStats(NIr_PWTasAnom2000_2080, sum, na.rm=T))\n\n# Sco\nSco_PWTasMinAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))\nSco_PWTasMaxAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))\nSco_PWTasAnom2000_2080 <- brick(extend(Sco_popD2000_2100, Sco_popD2000_2100))\nfor (i in 1:nlayers(Sco_popD2000_2100)){\n for (j in 1:12) {\n Sco_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasMinAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]\n Sco_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]\n Sco_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Sco_TasAnom2000_2080[[(12*(i-1))+j]] * Sco_popD2000_2100[[i]]\n }\n}\n\nScov_PWTasMinAnom2000_2080 <- c(cellStats(Sco_PWTasMinAnom2000_2080, sum, na.rm=T))\nScov_PWTasMaxAnom2000_2080 <- c(cellStats(Sco_PWTasMaxAnom2000_2080, sum, na.rm=T))\nScov_PWTasAnom2000_2080 <- c(cellStats(Sco_PWTasAnom2000_2080, sum, na.rm=T))\n\n\n# Wal\nWal_PWTasMinAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))\nWal_PWTasMaxAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))\nWal_PWTasAnom2000_2080 <- brick(extend(Wal_popD2000_2100, Wal_popD2000_2100))\nfor (i in 1:nlayers(Wal_popD2000_2100)){\n for (j in 1:12) {\n Wal_PWTasMinAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasMinAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]\n Wal_PWTasMaxAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasMaxAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]\n Wal_PWTasAnom2000_2080[[(12*(i-1))+j]] <- Wal_TasAnom2000_2080[[(12*(i-1))+j]] * Wal_popD2000_2100[[i]]\n }\n}\n\nWalv_PWTasMinAnom2000_2080 <- c(cellStats(Wal_PWTasMinAnom2000_2080, sum, na.rm=T))\nWalv_PWTasMaxAnom2000_2080 <- c(cellStats(Wal_PWTasMaxAnom2000_2080, sum, na.rm=T))\nWalv_PWTasAnom2000_2080 <- c(cellStats(Wal_PWTasAnom2000_2080, sum, na.rm=T))\n\n\nwrite.csv(as.data.frame(cbind(UK_AWTasMinAnom2000_2080, UK_AWTasMaxAnom2000_2080, UK_AWTasAnom2000_2080,\n Eng_AWTasMinAnom2000_2080, Eng_AWTasMaxAnom2000_2080, Eng_AWTasAnom2000_2080, \n NIr_AWTasMinAnom2000_2080, NIr_AWTasMaxAnom2000_2080, NIr_AWTasAnom2000_2080,\n Sco_AWTasMinAnom2000_2080, Sco_AWTasMaxAnom2000_2080, Sco_AWTasAnom2000_2080,\n Wal_AWTasMinAnom2000_2080, Wal_AWTasMaxAnom2000_2080, Wal_AWTasAnom2000_2080,\n UKv_PWTasMinAnom2000_2080, UKv_PWTasMaxAnom2000_2080, UKv_PWTasAnom2000_2080,\n Engv_PWTasMinAnom2000_2080, Engv_PWTasMaxAnom2000_2080, Engv_PWTasAnom2000_2080, \n NIrv_PWTasMinAnom2000_2080, NIrv_PWTasMaxAnom2000_2080, NIrv_PWTasAnom2000_2080,\n Scov_PWTasMinAnom2000_2080, Scov_PWTasMaxAnom2000_2080, Scov_PWTasAnom2000_2080,\n Walv_PWTasMinAnom2000_2080, Walv_PWTasMaxAnom2000_2080, Walv_PWTasAnom2000_2080)), \"AW_PW_MonthlyTAnomalies2000_2080.csv\")\n\n\n\n###############################################################################\n# VISUALISATIONS\n###############################################################################\n\n#################################################\n# Area-weighted Average Monthly T Anomalies from 2000-2080\n#################################################\n\nAW_PW_MonthlyTAnomalies2000_2080 <- read.csv(\"AW_PW_MonthlyTAnomalies2000_2080.csv\")\nAW_PW_MonthlyTAnomalies2000_2080$date <- as.Date(seq(as.Date(\"1999/12/01\"), as.Date(\"2080/11/01\"), by = \"month\"))\n\n#TasMin\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasMinAnom2000_2080, fill= S_UK_AWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Minimum Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMinAnom2000_2080, fill= S_Eng_AWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Minimum Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasMinAnom2000_2080, fill= S_NIr_AWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Minimum Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasMinAnom2000_2080, fill= S_Sco_AWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Minimum Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_TasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasMinAnom2000_2080, fill= S_Wal_AWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Minimum Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np1 <- ggarrange(UK_TasMin, ncol=1, nrow=1)\np2 <- ggarrange(Eng_TasMin, NIr_TasMin, Sco_TasMin, Wal_TasMin, ncol=2, nrow=2)\np3 <- ggarrange(p1, p2, ncol=1, nrow= 2)\n\n\n#TasMax\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasMaxAnom2000_2080, fill= S_UK_AWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Maximum Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMaxAnom2000_2080, fill= S_Eng_AWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Maximum Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasMaxAnom2000_2080, fill= S_NIr_AWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Maximum Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasMaxAnom2000_2080, fill= S_Sco_AWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Maximum Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_TasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasMaxAnom2000_2080, fill= S_Wal_AWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Maximum Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np4 <- ggarrange(UK_TasMax, ncol=1, nrow=1)\np5 <- ggarrange(Eng_TasMax, NIr_TasMax, Sco_TasMax, Wal_TasMax, ncol=2, nrow=2)\np6 <- ggarrange(p4, p5, ncol=1, nrow= 2)\n\n\n#Tas\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UK_AWTasAnom2000_2080, fill= S_UK_AWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Mean Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasAnom2000_2080, fill= S_Eng_AWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Mean Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIr_AWTasAnom2000_2080, fill= S_NIr_AWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Mean Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Sco_AWTasAnom2000_2080, fill= S_Sco_AWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Mean Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_AWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_Tas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Wal_AWTasAnom2000_2080, fill= S_Wal_AWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Mean Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np7 <- ggarrange(UK_Tas, ncol=1, nrow=1)\np8 <- ggarrange(Eng_Tas, NIr_Tas, Sco_Tas, Wal_Tas, ncol=2, nrow=2)\np9 <- ggarrange(p7, p8, ncol=1, nrow= 2)\n\n\n#################################################\n# Population-weighted Average Monthly Anomalies\n#################################################\n\n#TasMin\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasMinAnom2000_2080, fill= S_UK_PWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Minimum Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Eng_AWTasMinAnom2000_2080, fill= S_Eng_PWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Minimum Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasMinAnom2000_2080, fill= S_NIr_PWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Minimum Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasMinAnom2000_2080, fill= S_Sco_PWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Minimum Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasMinAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMinAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_PWTasMin <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasMinAnom2000_2080, fill= S_Wal_PWTasMinAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Minimum Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np10 <- ggarrange(UK_PWTasMin, ncol=1, nrow=1)\np11 <- ggarrange(Eng_PWTasMin, NIr_PWTasMin, Sco_PWTasMin, Wal_PWTasMin, ncol=2, nrow=2)\np12 <- ggarrange(p10, p11, ncol=1, nrow= 2)\n\n\n\n#TasMax\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasMaxAnom2000_2080, fill= S_UK_PWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Maximum Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Engv_PWTasMaxAnom2000_2080, fill= S_Eng_PWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Maximum Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasMaxAnom2000_2080, fill= S_NIr_PWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Maximum Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasMaxAnom2000_2080, fill= S_Sco_PWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Maximum Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasMaxAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMaxAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_PWTasMax <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasMaxAnom2000_2080, fill= S_Wal_PWTasMaxAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Maximum Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np13 <- ggarrange(UK_PWTasMax, ncol=1, nrow=1)\np14 <- ggarrange(Eng_PWTasMax, NIr_PWTasMax, Sco_PWTasMax, Wal_PWTasMax, ncol=2, nrow=2)\np15 <- ggarrange(p13, p14, ncol=1, nrow= 2)\n\n\n#Tas\nAW_PW_MonthlyTAnomalies2000_2080$S_UK_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nUK_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, UKv_PWTasAnom2000_2080, fill= S_UK_PWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Mean Temperature anomaly (°C) in the UK 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Eng_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nEng_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Engv_PWTasAnom2000_2080, fill= S_Eng_PWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n #scale_x_date(date_breaks = \"years\", date_labels = \"%Y\") +\n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Mean Temperature anomaly (°C) in England 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_NIr_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nNIr_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, NIrv_PWTasAnom2000_2080, fill= S_NIr_PWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Mean Temperature anomaly (°C) in the Northern Ireland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Sco_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nSco_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Scov_PWTasAnom2000_2080, fill= S_Sco_PWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Mean Temperature anomaly (°C) in Scotland 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\nAW_PW_MonthlyTAnomalies2000_2080$S_Wal_PWTasAnom2000_2080 <- ifelse(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasAnom2000_2080 >0, \"pos\",\"neg\") %>% factor(c(\"pos\", \"neg\"))\nWal_PWTas <- (ggplot(AW_PW_MonthlyTAnomalies2000_2080, aes(date, Walv_PWTasAnom2000_2080, fill= S_Wal_PWTasAnom2000_2080)) + \n geom_bar(stat = \"identity\", show.legend = FALSE) + \n scale_y_continuous(breaks = seq(-4, 10, 2)) +\n scale_fill_manual(values = c(\"#99000d\", \"#034e7b\")) +\n labs(y = \"Temperature anomaly (°C)\", x = \"\", \n title= \"Monthly Population-weighted Mean Temperature anomaly (°C) in Wales 2000-2080\", subtitle= \"compared to 1980-2000 average\",\n caption= \"Data: UKCP18\") +\n theme(plot.title= element_text(size= 10), plot.subtitle = element_text(size=9)) +\n theme_hc())\n\n\np16 <- ggarrange(UK_PWTas, ncol=1, nrow=1)\np17 <- ggarrange(Eng_PWTas, NIr_PWTas, Sco_PWTas, Wal_PWTas, ncol=2, nrow=2)\np18 <- ggarrange(p16, p17, ncol=1, nrow= 2)\n\n\n#################################################\n# Time series plots for AW an PW\n#################################################\ndata.frame(colnames(AW_PW_MonthlyTAnomalies2000_2080))\n\nlayout(matrix(c(1,1,2,3,4,5), 3, 2, byrow = TRUE))\n\nAW_PW_MonthlyTAnomalies2000_2080$Year <- as.numeric(substr(AW_PW_MonthlyTAnomalies2000_2080$date,1,4))\nAW_PW_MonthlyTAnomalies2000_2080$Month <- as.numeric(substr(AW_PW_MonthlyTAnomalies2000_2080$date,6,7))\nAW_PW_MonthlyTAnomalies2000_2080$DecimalDate <- AW_PW_MonthlyTAnomalies2000_2080$Year + (AW_PW_MonthlyTAnomalies2000_2080$Month / 12) - 1/24\n\n#TasMin\n# UK\nUK_TasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nUK_PWTasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(2,17)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Minimum Temperature anomaly (°C) in the UK 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_TasMin.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTasMin.decomp$time.series[,2], col=\"red\", lwd=3)\nlegend(\"bottomright\", legend= c(\"Area Weighted\", \"Population Weighted\"), lwd= 2, col=c(\"lightblue\", \"salmon\"), bg= (\"white\"), horiz= F)\n\n# England\nEng_TasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nEng_PWTasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(5,20)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Minimum Temperature anomaly (°C) in the England 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_TasMin.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTasMin.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# NIr\nNIr_TasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nNIr_PWTasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(8,23)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Minimum Temperature anomaly (°C) in the N.I. 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_TasMin.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTasMin.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Scotland\nSco_TasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nSco_PWTasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(11,26)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Minimum Temperature anomaly (°C) in the Scotland 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_TasMin.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTasMin.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Wales\nWal_TasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nWal_PWTasMin.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMinAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(14,29)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Minimum Temperature anomaly (°C) in the Wales 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_TasMin.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTasMin.decomp$time.series[,2], col=\"red\", lwd=3)\n\n\n#TasMax\n# UK\nUK_TasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nUK_PWTasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(3,18)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Maximum Temperature anomaly (°C) in the UK 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_TasMax.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTasMax.decomp$time.series[,2], col=\"red\", lwd=3)\nlegend(\"bottomright\", legend= c(\"Area Weighted\", \"Population Weighted\"), lwd= 2, col=c(\"lightblue\", \"salmon\"), bg= (\"white\"), horiz= F)\n\n# England\nEng_TasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nEng_PWTasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(6,21)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Maximum Temperature anomaly (°C) in the England 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_TasMax.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTasMax.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# NIr\nNIr_TasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nNIr_PWTasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(9,24)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Maximum Temperature anomaly (°C) in the N.I. 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_TasMax.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTasMax.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Scotland\nSco_TasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nSco_PWTasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(12,27)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Maximum Temperature anomaly (°C) in the Scotland 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_TasMax.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTasMax.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Wales\nWal_TasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nWal_PWTasMax.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasMaxAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(15,30)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Maximum Temperature anomaly (°C) in the Wales 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_TasMax.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTasMax.decomp$time.series[,2], col=\"red\", lwd=3)\n\n\n#Tas\n# UK\nUK_Tas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UK_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nUK_PWTas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$UKv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(4,19)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Mean Temperature anomaly (°C) in the UK 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_Tas.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, UK_PWTas.decomp$time.series[,2], col=\"red\", lwd=3)\nlegend(\"bottomright\", legend= c(\"Area Weighted\", \"Population Weighted\"), lwd= 2, col=c(\"lightblue\", \"salmon\"), bg= (\"white\"), horiz= F)\n\n# England\nEng_Tas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Eng_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nEng_PWTas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Engv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(7,22)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Mean Temperature anomaly (°C) in the England 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_Tas.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Eng_PWTas.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# NIr\nNIr_Tas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIr_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nNIr_PWTas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$NIrv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(10,25)], type=\"l\", \n xlab=\"Year\", main= \"Monthly MeanTemperature anomaly (°C) in the N.I. 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_Tas.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, NIr_PWTas.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Scotland\nSco_Tas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Sco_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nSco_PWTas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Scov_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(13,28)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Mean Temperature anomaly (°C) in the Scotland 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_Tas.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Sco_PWTas.decomp$time.series[,2], col=\"red\", lwd=3)\n\n# Wales\nWal_Tas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Wal_AWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nWal_PWTas.decomp <- \n stl(ts(AW_PW_MonthlyTAnomalies2000_2080$Walv_PWTasAnom2000_2080, frequency=12, start = c(1999, 12)), \n s.window=11, t.window=121)\nmatplot(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, AW_PW_MonthlyTAnomalies2000_2080[,c(16,31)], type=\"l\", \n xlab=\"Year\", main= \"Monthly Mean Temperature anomaly (°C) in the Wales 2000-2080\", ylab=expression(degree * \"C\"), \n col=c(\"lightblue\", \"salmon\"), lwd=2, lty=1)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_Tas.decomp$time.series[,2], col=\"blue\", lwd=3)\nlines(AW_PW_MonthlyTAnomalies2000_2080$DecimalDate, Wal_PWTas.decomp$time.series[,2], col=\"red\", lwd=3)\n\n\n\n\n", "meta": {"hexsha": "45529efb3b135d6c25b0fb285f71f7a2f23e8fac", "size": 70986, "ext": "r", "lang": "R", "max_stars_repo_path": "Code.r", "max_stars_repo_name": "Zvapowany/HackingClimate-An-exposure-weighted-warming", "max_stars_repo_head_hexsha": "c99218b88a843343a5704adbf051655e76396fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code.r", "max_issues_repo_name": "Zvapowany/HackingClimate-An-exposure-weighted-warming", "max_issues_repo_head_hexsha": "c99218b88a843343a5704adbf051655e76396fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code.r", "max_forks_repo_name": "Zvapowany/HackingClimate-An-exposure-weighted-warming", "max_forks_repo_head_hexsha": "c99218b88a843343a5704adbf051655e76396fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-01T15:31:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T13:13:04.000Z", "avg_line_length": 62.5427312775, "max_line_length": 175, "alphanum_fraction": 0.6563547742, "num_tokens": 26150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.47952856934950905}} {"text": "# -------------------------------------------\n# App Title: Benford's Law and Data Examples\n# Author: Jimmy Doi\n# -------------------------------------------\n\nlibrary(RColorBrewer)\nlibrary(rvest)\nlibrary(xml2)\n\nshinyUI(navbarPage(\"Benford's Law: Data Examples\",\n\n #open tabPanel#1\n #############################################################################\n ## tabPanel: Census Data I ##\n #############################################################################\n tabPanel(\"(1) Census Data I\",\n fluidPage(\n tags$head(tags$link(rel = \"icon\", type = \"image/x-icon\", href = \"https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico\")),\n\n # Give the page a title\n h3(\"(1) Benford's Law: US Census Data I\",HTML(\"–\"),\"Population Estimates\"),\n\n div(\"Note: Please adjust width of browser if only one column is visible.\",br(),\n HTML(\"[Click here for another Shiny app on Benford's Law]\"),\n style = \"font-size: 9pt;color:teal\"),br(),\n\n p(\"The first-digit distribution of many US Census variables is known to closely follow\",\n HTML(\"Benford's Law.\"),\n \"We will consider several census variables available from\",\n HTML(\"\n County Totals Dataset: Population, Population Change and Estimated\n Components of Population Change.\"),\n \"The app will apply a goodness of fit test of the observed frequencies of first-digits\n for the selected variable. The variables under consideration are: Annual Resident Total Population\n Estimate (2013 to 2016), Annual Births (2013 to 2016), Annual Deaths (2013 to 2016).\"),\n\n p(\"Note: It may be the case that some variables do not sufficiently adhere\n to Benford's Law according to the goodness of fit test.\n However bear in mind that relatively small deviations from what is expected\n can lead to a small P-value for the test due to a large sample size. Nevertheless,\n it is still interesting to see that, for any census variable from this app, the observed\n proportions of first-digits are not uniformly equal to 1/9 as one might expect and that Benford's\n Law can at least serve as a rough approximation.\"),\n\n HTML(\"
\"),\n\n # Generate a row with a sidebar\n fluidRow(\n column(4,wellPanel(\n\n selectInput(\"sel.var.cens\", label = h5(\"Select Census Variable:\"),\n choices = list(\"Population Est. 2016\" = 16,\n \"Population Est. 2015\" = 15,\n \"Population Est. 2014\" = 14,\n \"Population Est. 2013\" = 13,\n \"Births, 2016\" = 30,\n \"Births, 2015\" = 29,\n \"Births, 2014\" = 28,\n \"Births, 2013\" = 27,\n \"Deaths, 2016\" = 37,\n \"Deaths, 2015\" = 36,\n \"Deaths, 2014\" = 35,\n \"Deaths, 2013\" = 34\n ),\n selected = 16),\n\n br(), br(), br(), br(),\n\n div(\"Shiny app by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Base R code by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Shiny source files:\", a(href=\"https://gist.github.com/calpolystat/94fe941ab0d8a4f36d8b\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\",\n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\")\n ) # Close wellPanel\n ), # Close column-4\n\n column(8,\n div(span(\"Data from:\",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n HTML(\"\n County Totals Dataset\"),\n style=\"font-size:11pt;\"),\n\n div(span(\"Total Number of Counties in Data Set: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"comp.rows.cens\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\")),\n\n div(span(\"Census Variable: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"out.var.cens\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\")\n ),\n\n\n HTML(\"
\"),\n\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test:\")),\n verbatimTextOutput(\"goodness.cens\")\n ),\n column(8,\n plotOutput(\"cens.pmf\")\n )#closes column-8\n ),#closes fluidRow\n HTML(\"
\")\n ) #closes column-8\n ) #closes fluidRow\n ) #closes fluidPage\n ), #close tabPanel#1\n\n #open tabPanel#2\n #############################################################################\n ## tabPanel: Census Data II ##\n #############################################################################\n tabPanel(\"(2) Census Data II\",\n fluidPage(\n\n # Give the page a title\n h3(\"(2) Benford's Law: US Census Data II\",HTML(\"–\"),\"QuickFacts\"),\n\n div(\"Note: Please adjust width of browser if only one column is visible.\",br(),\n HTML(\"[Click here for another Shiny app on Benford's Law]\"),\n style = \"font-size: 9pt;color:teal\"),br(),\n\n p(\"The first-digit distribution of many US Census variables is known to closely follow\",\n HTML(\"Benford's Law.\"),\n \"We will consider several census variables available from\",\n HTML(\"US Census State & County QuickFacts.\"),\n \"The app will apply a goodness of fit test of the observed frequencies of first-digits\n for the selected variable. The variables under consideration are:\n Housing Units (2013),\n Households (2008-12),\n Veterans (2008-12),\n Nonemployer Establishments (2012),\n *Private Nonfarm Establishments (2012),\n *Private Nonfarm Employment (2012),\n *Retail Sales (2007).\"),\n\n p(\"*A small fraction (less than 2%) of the 3143 counties had entries of\n zero for the variables listed with an asterisk. For these cases, only the non-zero\n values were used for the goodness of fit test.\",style=\"font-style:normal;font-size:9pt\"),\n\n p(\"Note: It may be the case that some variables do not sufficiently adhere\n to Benford's Law according to the goodness of fit test.\n However bear in mind that relatively small deviations from what is expected\n can lead to a small P-value for the test due to a large sample size. Nevertheless,\n it is still interesting to see that, for any census variable from this app, the observed\n proportions of first-digits are not uniformly equal to 1/9 as one might expect and that Benford's\n Law can at least serve as a rough approximation.\"),\n\n HTML(\"
\"),\n\n # Generate a row with a sidebar\n fluidRow(\n column(4,wellPanel(\n\n selectInput(\"sel.var.quick\", label = h5(\"Select Census Variable:\"),\n choices = list(\"Housing Units, 2013\" = 25,\n \"Households, 2008-12\" = 29,\n \"Veterans, 2008-12\" = 23,\n \"Nonemployer Est., 2012\" = 37,\n \"*Private Nonfarm Est., 2012\" = 34,\n \"*Private Nonfarm Emp., 2012\" = 35,\n \"*Retail Sales, 2007 ($1000)\" = 47),\n selected = 25),\n\n br(), br(), br(), br(),\n\n div(\"Shiny app by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Base R code by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Shiny source files:\", a(href=\"https://gist.github.com/calpolystat/94fe941ab0d8a4f36d8b\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\",\n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\")\n ) # Close wellPanel\n ), # Close column-4\n\n column(8,\n div(span(\"Data from:\",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n HTML(\"US Census State & County QuickFacts\"),\n style=\"font-size:11pt;\"),\n\n div(span(\"Total Number of Counties in Data Set: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"comp.rows.quick\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\")),\n\n div(span(\"Census Variable: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"out.var.quick\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\")\n ),\n\n\n HTML(\"
\"),\n\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test:\")),\n verbatimTextOutput(\"goodness.quick\")\n ),\n column(8,\n plotOutput(\"quick.pmf\")\n )#closes column-8\n ),#closes fluidRow\n HTML(\"
\")\n ) #closes column-8\n ) #closes fluidRow\n ) #closes fluidPage\n ), #close tabPanel#2\n\n #open tabPanel#3\n #############################################################################\n ## tabPanel: Stock Exchange ##\n #############################################################################\n tabPanel(\"(3) US Stock Markets\",\n fluidPage(\n\n # Give the page a title\n h3(\"(3) Benford's Law: US Stock Markets\"),\n\n div(\"Note: Please adjust width of browser if only one column is visible.\",\n style = \"font-size: 9pt;color:teal\"),br(),\n\n p(\"After a given day of trading, if we consider the first-digit of the\n volume of shares traded for each listed company in the New York Stock Exchange,\n the corresponding distribution will closely follow\",\n HTML(\"Benford's Law.\"),\n \"Does the first-digit distribution for other variables such as a stock's closing cost\n closely follow Benford's Law? And does the specific stock market have any influence on the\n first-digit distribution of market variables?\"),\n\n p(\"This app will download information from the\",\n span(HTML(\"Wall Street Journal website\")),\n \"from the\",span(\"most recent end of day market data.\",style=\"font-weight:bold\"),\n \"The data will be based on various\n market variables for all\n companies listed in one of four stock markets.\n The app will apply a goodness of fit test of the observed frequencies of first-digits\n for the selected variable in the specified stock market.\"),\n\n p(\"Note: It may be the case that some stock price variables do not sufficiently adhere\n to Benford's Law according to the goodness of fit test.\n However bear in mind that relatively small deviations from what is expected\n can lead to a small P-value for the test due to a large sample size. Nevertheless,\n it is still interesting to see that, for any variable in this app, the observed\n proportions of first-digits are not uniformly equal to 1/9 as one might expect and that Benford's\n Law can at least serve as a rough approximation.\"),\n\n HTML(\"
\"),\n\n # Generate a row with a sidebar\n fluidRow(\n column(4,wellPanel(\n\n selectInput(\"stock\", label = h5(\"Select Stock Market:\"),\n choices = c(\"New York Stock Exchange\",\n \"Nasdaq Stock Market\",\n \"Nasdaq Capital Market\",\n \"NYSE MKT Stock Exchange\"),\n selected = \"New York Stock Exchange\"), br(),\n\n selectInput(\"sel.var\", label = h5(\"Select Variable\"),\n choices = list(\"Volume of Shares Traded\" = 9,\n \"Opening Price\" = 3,\n \"High Price\" = 4,\n \"Low Price\" = 5,\n \"Closing Price\" = 6),\n selected = 9),\n\n br(), br(), br(), br(),\n\n div(\"Shiny app by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Base R code by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Shiny source files:\", a(href=\"https://gist.github.com/calpolystat/f4475cbfe4cc77cef168\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\",\n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\")\n ) # Close wellPanel\n ), # Close column-4\n\n column(8,\n\n div(span(imageOutput(\"USA.icon.stock\",height=24),style=\"vertical-align: middle;display:inline-block\"),\n span(HTML(\" Currency:\"),style=\"text-align:left;\n font-size:11pt;vertical-align: middle;display:inline-block\"),\n span(HTML(\" \"),style=\"text-align:left;font-size:11pt;vertical-align: middle;display:inline-block\"),\n span(textOutput(\"USA.curr.stock\"),style=\"text-align:left;font-size:11pt;color:#5C8AE6;\n display:inline-block;vertical-align: middle\"),\n span(HTML(\"         \"),style=\"text-align: right;vertical-align: middle;font-size:11pt\"),\n span(\"End of Day Market Data from: \",style=\"text-align:\n right;font-size:11pt;vertical-align: middle;display:inline-block\"),\n span(HTML(\" \"),style=\"text-align: right;vertical-align: middle;font-size:11pt\"),\n span(textOutput(\"comp.date\"),style=\"text-align: right;vertical-align: middle;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\"),\n style=\"text-align: right;font-size:0pt;display:inline-block;\"),br(),\n\n div(span(\"Market Source: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"short.stock\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\"),\n span(HTML(\"    \"),style=\"text-align: right;font-size:11pt\"),\n span(\"Total Number of Stocks in Data Set: \",style=\"text-align:\n right;font-size:11pt;display:inline-block\"),\n span(textOutput(\"comp.rows\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal\")),\n\n HTML(\"
\"),\n\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test:\")),\n div(span(textOutput(\"out.var\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal;text-align: center\")),\n br(),\n verbatimTextOutput(\"goodness\")\n ),\n column(8,\n plotOutput(\"stock.pmf\")\n )#closes column-8\n ),#closes fluidRow\n HTML(\"
\")\n ) #closes column-8\n ) #closes fluidRow\n ) #closes fluidPage\n ), #close tabPanel#3\n\n #open tabPanel#4\n #############################################################################\n ## tabPanel: World Stock Exchange ##\n #############################################################################\n tabPanel(\"(4) World Stock Markets\",\n fluidPage(\n\n # Give the page a title\n h3(\"(4) Benford's Law: World Stock Markets\"),\n\n div(\"Note: Please adjust width of browser if only one column is visible.\",br(),\n HTML(\"[Click here for another Shiny app on Benford's Law]\"),\n style = \"font-size: 9pt;color:teal\"),br(),\n\n p(\"For the New York Stock Exchange (see previous tab),\n we found that the first-digit distribution of stock prices\n closely follows\",\n HTML(\"Benford's Law.\"),\n \"Does Benford's Law also apply to the first-digit distribution for stock prices from other world markets?\n Does currency have any influence on the\n first-digit distribution of market variables?\"),\n\n p(\"This app will download market data from the\",\n span(HTML(\"Investing.com website. \")),\n \"For the selected stock market, if trading is \", span(\"active \",style=\"font-weight:bold\"),\n \"at the point of data access,\n the results will be based on the \", span(\"most current market data.\",style=\"font-weight:bold\"),\n \"If the market is closed at point of access, then all information will be based on the most recent\n end of day market data. The app will apply a goodness of fit test of the observed frequencies of first-digits\n for the selected variable in the specified stock market.\"),\n\n p(\"Note: It may be the case that some stock price variables do not sufficiently adhere\n to Benford's Law according to the goodness of fit test.\n However bear in mind that relatively small deviations from what is expected\n can lead to a small P-value for the test due to a large sample size. Nevertheless,\n it is still interesting to see that, for any variable in this app, the observed\n proportions of first-digits are not uniformly equal to 1/9 as one might expect and that Benford's\n Law can at least serve as a rough approximation.\"),\n\n HTML(\"
\"),\n\n # Generate a row with a sidebar\n fluidRow(\n column(4,wellPanel(\n\n selectInput(\"w.stock\", label = h5(\"Select World Market:\"),\n choices = c(\"Australia\",\n \"Canada\",\n \"China\",\n \"Denmark\",\n \"England\",\n \"France\",\n \"Germany\",\n \"India\",\n \"Japan\",\n \"Korea\",\n \"Netherlands\",\n \"Poland\",\n \"Sri Lanka\",\n \"Switzerland\",\n \"Turkey\"),\n selected = \"Australia\"), br(),\n\n selectInput(\"w.sel.var\", label = h5(\"Select Variable:\"),\n choices = list(\"Most Recent Price\" = 3,\n \"High Price\" = 4,\n \"Low Price\" = 5),\n selected = 3),\n\n br(), br(), br(), br(),\n\n div(\"Shiny app by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Base R code by\", a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\",\n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(\"Shiny source files:\", a(href=\"https://gist.github.com/calpolystat/94fe941ab0d8a4f36d8b\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\",\n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\")\n ) # Close wellPanel\n ), # Close column-4\n\n column(8,\n\n div(span(imageOutput(\"w.icon.stock\",height=24),style=\"vertical-align: middle;display:inline-block\"),\n span(HTML(\" Currency:\"),style=\"text-align:left;\n font-size:11pt;vertical-align: middle;display:inline-block\"),\n span(HTML(\" \"),style=\"text-align:left;font-size:11pt;vertical-align: middle;display:inline-block\"),\n span(textOutput(\"w.curr.stock\"),style=\"text-align:left;font-size:11pt;color:#5C8AE6;\n display:inline-block;vertical-align: middle\"),\n span(HTML(\"          \"),\n style=\"text-align: left;font-size:11pt;vertical-align: middle\"),\n span(\"Access Point: \",style=\"text-align:\n left;font-size:11pt;display:inline-block;vertical-align: middle\"),\n span(HTML(\" \"),style=\"text-align: left;font-size:11pt\"),\n span(textOutput(\"w.time.stock\"),style=\"text-align: left;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal;vertical-align: middle\"),\n style=\"text-align: right;font-size:0pt;display:inline-block;\"),br(),\n\n div(span(\"Market Status:\",style=\"text-align:\n left;font-size:11pt;display:inline-block;vertical-align: middle\"),\n span(textOutput(\"w.mkt.status\"),style=\"text-align: left;font-size:11pt;\n display:inline-block;color:red;font-weight:normal;vertical-align: middle\"),\n span(HTML(\"    \"),style=\"text-align: left;font-size:11pt;vertical-align: middle\"),\n span(\"Source: \",style=\"text-align:\n left;font-size:11pt;display:inline-block;vertical-align: middle\"),\n span(textOutput(\"w.short.stock\"),style=\"text-align: left;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal;vertical-align: middle\"),\n span(HTML(\"    \"),style=\"text-align: left;font-size:11pt;vertical-align: middle\"),\n span(\"Total Stocks: \",style=\"text-align:\n left;font-size:11pt;display:inline-block;vertical-align: middle\"),\n span(textOutput(\"w.comp.rows\"),style=\"text-align: left;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal;vertical-align: middle\")\n ),\n\n HTML(\"
\"),\n\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test:\")),\n div(span(textOutput(\"w.out.var\"),style=\"text-align: right;font-size:11pt;\n display:inline-block;color:#5C8AE6;font-weight:normal;text-align: center\")),\n br(),\n verbatimTextOutput(\"w.goodness\")\n ),\n column(8,\n plotOutput(\"w.stock.pmf\")\n )#closes column-8\n ),#closes fluidRow\n HTML(\"
\")\n ) #closes column-8\n ) #closes fluidRow\n ) #closes fluidPage\n ) #close tabPanel#4\n\n ) #closes navbarPage\n) #closes shinyUI\n", "meta": {"hexsha": "84ab09d3097395a4a02edc3d2a9fe0e0060046cf", "size": 27611, "ext": "r", "lang": "R", "max_stars_repo_path": "BenfordData/ui.r", "max_stars_repo_name": "townsenddw/shiny1", "max_stars_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BenfordData/ui.r", "max_issues_repo_name": "townsenddw/shiny1", "max_issues_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BenfordData/ui.r", "max_forks_repo_name": "townsenddw/shiny1", "max_forks_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T12:48:05.000Z", "avg_line_length": 55.6673387097, "max_line_length": 160, "alphanum_fraction": 0.5220021006, "num_tokens": 5898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.47948364648128583}} {"text": "subroutine delseg(delsgs,ndel,nadj,madj,npd,x,y,ntot,nerror)\n\n# Output the endpoints of the line segments joining the\n# vertices of the Delaunay triangles.\n# Called by master.\n\nimplicit double precision(a-h,o-z)\nlogical value\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\ndimension delsgs(6,ndel)\n\n# For each distinct pair of points i and j, if they are adjacent\n# then put their endpoints into the output array.\nnpd = ntot-4\nkseg = 0\ndo i = 2,npd {\n do j = 1,i-1 {\n call adjchk(i,j,value,nadj,madj,ntot,nerror)\n\t\tif(nerror>0){\n return\n }\n if(value) {\n\t\t\tkseg = kseg+1\n\t\t\tif(kseg > ndel) {\n\t\t\t\tnerror = 14\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdelsgs(1,kseg) = x(i)\n\t\t\tdelsgs(2,kseg) = y(i)\n\t\t\tdelsgs(3,kseg) = x(j)\n\t\t\tdelsgs(4,kseg) = y(j)\n\t\t\tdelsgs(5,kseg) = i\n\t\t\tdelsgs(6,kseg) = j\n }\n }\n}\nndel = kseg\n\nreturn\nend\n", "meta": {"hexsha": "d7d4be8ed64c4b0e89a4c437c099df177db4dc9a", "size": 900, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/SavedRatfor/delseg.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/SavedRatfor/delseg.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/ratfor/delseg.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 21.9512195122, "max_line_length": 64, "alphanum_fraction": 0.5877777778, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.47948362263698113}} {"text": "\n# In the integrated analysis, all of the data components share the same mean Linf parameter (\"mu.Linf\").\n# The tagging and otolith components include a random Linf parameter, so also share the same \"sig.Linf\";\n# whereas the length-frequency component does not include a random Linf (thus no \"sig.Linf\") since\n# the data are for young fish that are not near their asymptotic length.\n\n# There is no information about the a0 parameter from the tagging data, so this parameter is estimated\n# from the otolith and length-frequency data sets\n\n# The variance parameters are assumed to be unique for each data set\n\n# The length-frequency (LF) component assumes that a model decomposition has already been applied to the\n# raw data, such that the dataset input to the growth analysis is the lengths and ages corresponding to\n# the modes in the LF data.\n\n# - param.f contains the parameters of the growth function, f (note L=Linf*f, so param.f does not include Linf)\n# (e.g. param.f={k} for the standard VB model; param.f={k,u,w} for VB with seasonal growth)\n# - npf = number of parameters for the growth function, f; i.e., length of param.f\n# (e.g. npf=1 for standard VB; npf=3 for VB with seasonal growth)\n# - param.A contains the parameters for the distribution of A (e.g. log normal in our example)\n# - npA = number of parameters for distribution of A, i.e., length of param.A (e.g. npA=2 for log normal)\n# - param contains all of the parameters being estimated, including the variance parameters; note that\n# for the tagging component, we allow measurement error in length to be different for scientists vs fishermen\n# since many of our recaptures were measured by fishermen, hence the 2 variance parameters sig.s and sig.f\n# (e.g., param = {mu.Linf, sig.Linf, param.f, param.A, sig.s, sig.f, a0, sig.oto, sig.lf}\n\n\n# 1) Otolith negative log-likelihood component:\n# - assumes data is a matrix with columns: age, length\n\nlogl.oto.f <- function(param, npf, npA, otodat)\n{\n #print(param)\n # Get data:\n\tage <- otodat[, 1]\n\tlen <- otodat[, 2]\n n <- nrow(otodat)\n\n\t# Get param:\n\tmu.L <- param[1]\n\tsig.L <- param[2]\n\tparam.f <- param[3:(npf+2)]\n\ta0 <- param[2+npf+npA+3]\n\tsig.oto <- param[2+npf+npA+4]\n\t\n\tgrwth <- growth.ssnl.f(age - a0, param.f, age)\n\texp.len <- mu.L * grwth\n\tvar.len <- (grwth * sig.L)^2 + sig.oto^2\n\tneglogl <- 1/2 * sum(log(2 * pi * var.len) + ((len - exp.len)^2)/var.len)\n\t\n\t#print(neglogl)\n\treturn(neglogl)\n}\n\n\n#2) Length-frequency (LF) negative log-likelihood component:\n# - assumes data is in a matrix with columns: age, mean.mode, se.mode\n\nlogl.lf.f <- function(param, npf, npA, lfdat)\n{\n\t# Get data:\n\tage <- lfdat[, 1]\n\tmu.mode <- lfdat[, 2]\n\tse.mode <- lfdat[, 3]\n\tn <- nrow(lfdat)\n\n\t# Get parameters:\n\tmu.L <- param[1]\n\tparam.f <- param[3:(npf+2)]\n\ta0 <- param[2+npf+npA+3]\n\t#a0 = 0 # Note: Uncomment this to remove the effect of fitting a0.\n\tsig.lf <- param[2+npf+npA+5]\n\n\tgrwth <- growth.ssnl.f(age - a0, param.f, age)\n\texp.mode <- mu.L * grwth\n\tvar.mode <- sig.lf^2 + se.mode^2\n\tneglogl <- 1/2 * sum(log(2 * pi * var.mode) + ((mu.mode - exp.mode)^2)/var.mode)\n\t#print(param)\n\t#print(neglogl)\n\treturn(neglogl)\n}\n\n#3) Tagging negative log-likelihood component:\n# - code and description found in file 'tag lkhd.r'\n#source(\"/Users/stephenscherrer/Google Drive/Weng Lab/Data/Bottomfish/Okamoto's 1990s Mark Recapture Data/src/Laslett Functions/tag_lkhd.r\")\n\n\n# JOINT LIKELIHOOD:\njoint.logl.f <- function(param,npf,npA,tagdat,otodat,lfdat,wt.oto=1,wt.tag=1,wt.lf=1)\n{\n neglogl.tag<- 0\n neglogl.oto<- 0\n neglogl.lf<- 0\n if(wt.tag>0) neglogl.tag <- logl.ssnl.f(param,npf,npA,tagdat)\n if(wt.oto>0) neglogl.oto <- logl.oto.f(param,npf,npA,otodat)\n if(wt.lf>0) neglogl.lf <- logl.lf.f(param,npf,npA,lfdat)\n neglogl <- wt.tag*neglogl.tag + wt.oto*neglogl.oto + wt.lf*neglogl.lf\n #print(param)\n #print(c(neglogl.tag, neglogl.oto, neglogl.lf, neglogl))\n return(neglogl)\n}\n\n# where...\n\n# logl.ssnl.f is for tagging data and is found in \"tag lkhd.r\" (along with all\n# necessary associated functions)\n\n\n\n\n", "meta": {"hexsha": "cd9a53fd5c15fcd6b44c3827a20797d02feb6893", "size": 4034, "ext": "r", "lang": "R", "max_stars_repo_path": "Analysis/src/Laslett Functions/joint_lkhd.r", "max_stars_repo_name": "stevescherrer/Ch4-Opakapaka-Growth", "max_stars_repo_head_hexsha": "b8c0d3881be889d8197bb0f9251f011ed98850f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Analysis/src/Laslett Functions/joint_lkhd.r", "max_issues_repo_name": "stevescherrer/Ch4-Opakapaka-Growth", "max_issues_repo_head_hexsha": "b8c0d3881be889d8197bb0f9251f011ed98850f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis/src/Laslett Functions/joint_lkhd.r", "max_forks_repo_name": "stevescherrer/Ch4-Opakapaka-Growth", "max_forks_repo_head_hexsha": "b8c0d3881be889d8197bb0f9251f011ed98850f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3423423423, "max_line_length": 140, "alphanum_fraction": 0.6963311849, "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4792622609067989}} {"text": "\n subset.biomass = function(Q, R, nodes, type=\"mature.only\", fraction11 = 0.2) {\n out = NULL\n names(Q) = nodes\n names(R) = nodes\n\n Q[!is.finite(Q)] = 0\n R[!is.finite(R)] = 0\n\n if (type ==\"historic\") {\n tot = fraction11 * (Q[\"imm.11\"] + Q[\"imm.sm.11\"] + Q[\"CC3to4.11\"] + Q[\"CC5.11\"]) +\n (Q[\"imm.12\"] + Q[\"imm.sm.12\"] + Q[\"CC3to4.12\"] + Q[\"CC5.12\"]) +\n ( Q[\"CC3to4.13\"] + Q[\"CC5.13\"])\n\n err = sqrt( fraction11^2 * (R[\"imm.11\"]^2 + R[\"imm.sm.11\"]^2 + R[\"CC3to4.11\"]^2 + R[\"CC5.11\"]^2) +\n R[\"imm.12\"]^2 + R[\"imm.sm.12\"]^2 + R[\"CC3to4.12\"]^2 + R[\"CC5.12\"]^2 +\n R[\"CC3to4.13\"]^2 + R[\"CC5.13\"]^2\n )\n } else if (type ==\"mature.only\") {\n tot = fraction11 * ( Q[\"CC3to4.11\"] + Q[\"CC5.11\"]) + \n ( Q[\"CC3to4.12\"] + Q[\"CC5.12\"]) +\n ( Q[\"CC3to4.13\"] + Q[\"CC5.13\"])\n\n err = sqrt( fraction11^2 * ( R[\"CC3to4.11\"]^2 + R[\"CC5.11\"]^2) +\n R[\"CC3to4.12\"]^2 + R[\"CC5.12\"]^2 +\n R[\"CC3to4.13\"]^2 + R[\"CC5.13\"]^2\n )\n }\n \n names(tot) = NULL\n return( c(tot,err) )\n }\n\n\n", "meta": {"hexsha": "b79951c9652a23f8190ecc2f5454cef77355ba99", "size": 1279, "ext": "r", "lang": "R", "max_stars_repo_path": "R/subset.biomass.r", "max_stars_repo_name": "jae0/snowcrab", "max_stars_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/subset.biomass.r", "max_issues_repo_name": "jae0/snowcrab", "max_issues_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/subset.biomass.r", "max_forks_repo_name": "jae0/snowcrab", "max_forks_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:57:48.000Z", "avg_line_length": 36.5428571429, "max_line_length": 104, "alphanum_fraction": 0.3737294762, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47870831006640735}} {"text": "#' compute Area under the Curve (AUC)\n#' @param target the target\n#' @param score the score, the higher the score the less targets\n#' @importFrom data.table setkey shift data.table\nauc <- function(target, score) {\n a = data.table::data.table(target, score = -score)\n data.table::setkey(a, score)\n a1 = a[,.(h = sum(target), w = .N), score]\n \n \n a1[,height:=cumsum(h)/sum(h)]\n a1[,ctot:=cumsum(w)/sum(w)]\n \n a1[,lag_height:=shift(height,1)]\n a1[1,lag_height := 0]\n \n a1[,area := (lag_height + height)*w/sum(w)/2]\n a1[,sum(area)]\n}", "meta": {"hexsha": "7ccc2c42e623d8eb0506ed4af67ca9907d6fc057", "size": 542, "ext": "r", "lang": "R", "max_stars_repo_path": "R/auc.r", "max_stars_repo_name": "xiaodaigh/disk.frame.ml", "max_stars_repo_head_hexsha": "ce0853b7307089fbfc5cc986ab03d2d3f6f936ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-03-31T08:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-25T01:18:38.000Z", "max_issues_repo_path": "R/auc.r", "max_issues_repo_name": "xiaodaigh/disk.frame.ml", "max_issues_repo_head_hexsha": "ce0853b7307089fbfc5cc986ab03d2d3f6f936ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-18T23:42:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-16T11:37:21.000Z", "max_forks_repo_path": "R/auc.r", "max_forks_repo_name": "xiaodaigh/disk.frame.ml", "max_forks_repo_head_hexsha": "ce0853b7307089fbfc5cc986ab03d2d3f6f936ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5263157895, "max_line_length": 64, "alphanum_fraction": 0.6346863469, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}} {"text": "#!/usr/bin/Rscript\nlibrary(psycho) # used for SDT analysis\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(lmerTest)\n\ndefault_filename <- 'data/cat_20190321_turtle_feedback.csv'\n\n# accept a filename as an optional command-line argument\nargs <- commandArgs(trailingOnly=T)\nif (length(args) < 1) {\n args <- c(default_filename)\n}\n\n# estimates SDT measures of sensitivity & bias for each subject/condition\nrunSDT <- function(data) {\n # count the number of correct/incorrect trials for each condition\n nIncorrect <- aggregate(wasCorrect ~ subject+condition+isTarget+isFoil+isOld, data,\n function(x) sum(x==0))$wasCorrect\n data <- aggregate(wasCorrect ~ subject+condition+isTarget+isFoil+isOld, data, sum)\n data$nCorrect <- data$wasCorrect\n data$nIncorrect <- nIncorrect\n \n # group the old/new stimuli by subject and condition\n data <- merge(subset(data, isOld==1), subset(data, isOld==0), sort=F,\n by=c('subject', 'condition', 'isTarget', 'isFoil'),\n suffixes=c('.old', '.new'))\n write.csv(data, 'sdt.csv')\n \n # get sensitivty & bias for each subject on each condition\n indices <- psycho::dprime(data$nCorrect.old, data$nIncorrect.new,\n data$nIncorrect.old, data$nCorrect.new)\n sdtData <- cbind(data, indices)\n \n # analyze sensitivity (dprime)\n writeLines('\\n\\nSensitivity (dprime)')\n print(summary(lmer(dprime ~ condition*isTarget*isFoil + (1|subject), data=sdtData)))\n \n # analyze bias (c)\n writeLines('\\n\\nBias (C)')\n print(summary(lmer(c ~ condition*isTarget*isFoil + (1|subject), data=sdtData)))\n return(sdtData)\n}\n\n# analyze data from each file\nfor (i in 1:length(args)) {\n filename <- args[i]\n writeLines(args[i])\n\n memData <- subset(read.csv(filename, header=T), task=='test')\n memData$condition <- as.factor(memData$condition)\n memData$isTarget <- as.factor(memData$isTarget)\n memData$isFoil <- as.factor(memData$isFoil)\n learnData <- subset(read.csv(filename, header=T), task=='learn')\n endAcc <- aggregate(wasCorrect~subject, learnData, function (trials) mean(tail(trials, 20)))\n testRT <- aggregate(RT ~ subject, memData, mean)\n learnRT <- aggregate(RT ~ subject, learnData, mean)\n writeLines(sprintf('Total number of subjects: %d', length(unique(memData$subject))))\n\n # exclude subjects with high RT or low learning accuracy\n writeLines(sprintf('Mean Test RT+3SD: %f', (mean(memData$RT)+3*sd(memData$RT)) / 1000))\n writeLines(sprintf('Mean Learning RT+3SD: %f', (mean(learnData$RT)+3*sd(learnData$RT)) / 1000))\n excluded = unique(c(learnRT$subject[learnRT$RT > (mean(learnRT$RT) + 3*sd(learnRT$RT))],\n testRT$subject[testRT$RT > (mean(testRT$RT) + 3*sd(testRT$RT))],\n endAcc$subject[endAcc$wasCorrect < 0.85]))\n memData <- memData[!(memData$subject %in% excluded),]\n learnData <- learnData[!(learnData$subject %in% excluded),]\n writeLines(sprintf('After exclusion: %d', length(unique(memData$subject))))\n\n print(aggregate(subject~condition, memData, function (s) length(unique(s))))\n \n writeLines('\\n\\nRT')\n print(summary(lmer(RT ~ condition*isTarget*isFoil + (1|subject), data=memData)))\n \n hits <- subset(memData, isOld==1)\n FAs <- subset(memData, isOld==0)\n FAs$wasCorrect <- 1-FAs$wasCorrect # we want FA rate, not CR rate\n \n writeLines('\\n\\nHits')\n print(summary(glmer(wasCorrect ~ condition*isTarget*isFoil + (1|subject),\n data=hits, family=binomial(link='logit'))))\n writeLines('\\n\\nFAs')\n print(summary(glmer(wasCorrect ~ condition*isTarget*isFoil + (1|subject),\n data=FAs, family=binomial(link='logit'))))\n\n sdtData <- runSDT(memData)\n writeLines('\\n\\n\\n\\n\\n')\n write.csv(sdtData, 'sdt.csv')\n \n # plot interaction plots\n png('feedback_RT.png', height=1000, width=1000)\n # remove individual differences (for within-subject studies)\n subjAvgs <- memData %>% group_by(subject) %>% summarise(subjAvg=mean(RT))\n condAvgs <- memData %>% group_by(condition) %>% summarise(condAvg=mean(RT))\n memData$RT <- apply(memData, 1, function (x) as.numeric(x['RT'])\n - subset(subjAvgs, subject==as.numeric(x['subject']))$subjAvg\n + subset(condAvgs, condition == x['condition'])$condAvg)\n print(ggplot(memData %>% group_by(condition, isTarget, isFoil) %>%\n summarise(N=length(RT), rt=mean(RT), sd=sd(RT), ci=(1.96*sd/sqrt(N)))) +\n aes(x=interaction(isFoil, isTarget), y=rt, fill=isTarget) +\n geom_col(size=2) + theme_classic() + ylab('Reaction Time') +\n geom_errorbar(aes(ymin=rt-ci, ymax=rt+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n aes(x=interaction(isFoil, isTarget), y=rt, fill=isTarget) +\n geom_col(size=2) + theme_classic() + ylab('Reaction Time') +\n geom_errorbar(aes(ymin=rt-ci, ymax=rt+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n scale_x_discrete(labels=c('Neither', 'Not Learned', 'Learned', 'Both')) +\n theme(axis.text=element_text(size=20),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=36, margin=margin(r=0.5, unit='cm')),\n legend.position='none',\n strip.background=element_blank(),\n strip.placement='outside',\n strip.text=element_text(size=36),\n plot.margin=margin(t=1, b=1, unit='cm')))\n dev.off()\n \n png('feedback_hits.png', height=1000, width=1000)\n # remove individual differences (for within-subject studies)\n subjAvgs <- hits %>% group_by(subject) %>% summarise(subjAvg=mean(wasCorrect))\n condAvgs <- hits %>% group_by(condition) %>% summarise(condAvg=mean(wasCorrect))\n hits$wasCorrect <- apply(hits, 1, function (x) as.numeric(x['wasCorrect'])\n - subset(subjAvgs, subject==as.numeric(x['subject']))$subjAvg\n + subset(condAvgs, condition == x['condition'])$condAvg)\n print(ggplot(hits %>% group_by(condition, isTarget, isFoil) %>%\n summarise(N=length(wasCorrect), hits=mean(wasCorrect),\n sd=sd(wasCorrect), ci=(1.96*sd/sqrt(N)))) +\n aes(x=interaction(isFoil, isTarget), y=hits, fill=isTarget) +\n geom_col(size=2) + theme_classic() + ylab('Hit Rate') +\n geom_errorbar(aes(ymin=hits-ci, ymax=hits+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n scale_x_discrete(labels=c('Neither', 'Not Learned', 'Learned', 'Both')) +\n theme(axis.text=element_text(size=20),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=36, margin=margin(r=0.5, unit='cm')),\n legend.position='none',\n strip.background=element_blank(),\n strip.placement='outside',\n strip.text=element_text(size=36),\n plot.margin=margin(t=1, b=1, unit='cm')))\n dev.off()\n \n png('feedback_FAs.png', height=1000, width=1000)\n # remove individual differences (for within-subject studies)\n subjAvgs <- FAs %>% group_by(subject) %>% summarise(subjAvg=mean(wasCorrect))\n condAvgs <- FAs %>% group_by(condition) %>% summarise(condAvg=mean(wasCorrect))\n FAs$wasCorrect <- apply(FAs, 1, function (x) as.numeric(x['wasCorrect'])\n - subset(subjAvgs, subject==as.numeric(x['subject']))$subjAvg\n + subset(condAvgs, condition == x['condition'])$condAvg)\n print(ggplot(FAs %>% group_by(condition, isTarget, isFoil) %>%\n summarise(N=length(wasCorrect), FAs=mean(wasCorrect),\n sd=sd(wasCorrect), ci=(1.96*sd/sqrt(N)))) +\n aes(x=interaction(isFoil, isTarget), y=FAs, fill=isTarget) +\n geom_col(size=2) + theme_classic() + ylab('FA Rate') +\n geom_errorbar(aes(ymin=FAs-ci, ymax=FAs+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n scale_x_discrete(labels=c('Neither', 'Not Learned', 'Learned', 'Both')) +\n theme(axis.text=element_text(size=20),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=36, margin=margin(r=0.5, unit='cm')),\n legend.position='none',\n strip.background=element_blank(),\n strip.placement='outside',\n strip.text=element_text(size=36),\n plot.margin=margin(t=1, b=1, unit='cm')))\n dev.off()\n \n png('feedback_sensitivity.png', height=1000, width=1000)\n # remove individual differences (for within-subject studies)\n subjAvgs <- sdtData %>% group_by(subject) %>% summarise(subjAvg=mean(dprime))\n condAvgs <- sdtData %>% group_by(condition) %>% summarise(condAvg=mean(dprime))\n sdtData$dprime <- apply(sdtData, 1, function (x) as.numeric(x['dprime'])\n - subset(subjAvgs, subject==as.numeric(x['subject']))$subjAvg\n + subset(condAvgs, condition == x['condition'])$condAvg)\n print(ggplot(sdtData %>% group_by(condition, isTarget, isFoil) %>%\n summarise(N=length(dprime), sensitivity=mean(dprime),\n sd=sd(dprime), ci=(1.96*sd/sqrt(N)))) +\n aes(x=interaction(isFoil, isTarget), y=sensitivity, fill=isTarget) +\n geom_col(size=2) + theme_classic() +\n geom_errorbar(aes(ymin=sensitivity-ci, ymax=sensitivity+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n aes(x=interaction(isFoil, isTarget), y=sensitivity, fill=isTarget) +\n geom_col(size=2) + theme_classic() +\n geom_errorbar(aes(ymin=sensitivity-ci, ymax=sensitivity+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n ylab(expression(paste('Sensitivity (', d*minute, ')'))) +\n scale_x_discrete(labels=c('Neither', 'Not Learned', 'Learned', 'Both')) +\n theme(axis.text=element_text(size=20),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=36, margin=margin(r=0.5, unit='cm')),\n legend.position='none',\n strip.background=element_blank(),\n strip.placement='outside',\n strip.text=element_text(size=36),\n plot.margin=margin(t=1, b=1, unit='cm')))\n dev.off()\n \n png('feedback_bias.png', height=1000, width=1000)\n # remove individual differences (for within-subject studies)\n subjAvgs <- sdtData %>% group_by(subject) %>% summarise(subjAvg=mean(c))\n condAvgs <- sdtData %>% group_by(condition) %>% summarise(condAvg=mean(c))\n sdtData$c <- apply(sdtData, 1, function (x) as.numeric(x['c'])\n - subset(subjAvgs, subject==as.numeric(x['subject']))$subjAvg\n + subset(condAvgs, condition == x['condition'])$condAvg)\n print(ggplot(sdtData %>% group_by(condition, isTarget, isFoil) %>%\n summarise(N=length(c), bias=mean(c), sd=sd(c), ci=(1.96*sd/sqrt(N)))) +\n aes(x=interaction(isFoil, isTarget), y=bias, fill=isTarget) +\n geom_col(size=2) + theme_classic() + ylab('Bias (C)') +\n geom_errorbar(aes(ymin=bias-ci, ymax=bias+ci), width=.2) +\n facet_wrap(~condition, strip.position='bottom') +\n scale_x_discrete(labels=c('Neither', 'Not Learned', 'Learned', 'Both')) +\n theme(axis.text=element_text(size=20),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=36, margin=margin(r=0.5, unit='cm')),\n legend.position='none',\n strip.background=element_blank(),\n strip.placement='outside',\n strip.text=element_text(size=36),\n plot.margin=margin(t=1, b=1, unit='cm')))\n dev.off()\n}\n", "meta": {"hexsha": "2aeec066465e10cc2699933aa42ba13b1db9ca74", "size": 12038, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/mturk/feedback_memory.r", "max_stars_repo_name": "IMC-Lab/CategoryLearning", "max_stars_repo_head_hexsha": "84f9f973e267f20f7790dbbd7d3a555e58bb90dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-10T22:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-10T22:07:25.000Z", "max_issues_repo_path": "analysis/mturk/feedback_memory.r", "max_issues_repo_name": "IMC-Lab/CategoryLearning", "max_issues_repo_head_hexsha": "84f9f973e267f20f7790dbbd7d3a555e58bb90dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/mturk/feedback_memory.r", "max_forks_repo_name": "IMC-Lab/CategoryLearning", "max_forks_repo_head_hexsha": "84f9f973e267f20f7790dbbd7d3a555e58bb90dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.9820627803, "max_line_length": 99, "alphanum_fraction": 0.6088220635, "num_tokens": 3188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4781077110492607}} {"text": "# Load packages -----------------------\nlibrary(dplyr)\nlibrary(tidyr)\nlibrary(purrr)\nlibrary(ggplot2)\nlibrary(cowplot)\n\n# Functions ---------------------------\n# biomass estimation based on Niiyama et al. (2010)\nbiomass <- function(dbh, component = \"agb\") {\n h <- 1 / (1 / (1.61 * dbh) + 1 / 69.) # tree height (m) from dbh (cm)\n w_s <- 0.036 * (dbh * dbh * h)^1.01 # trunk plus branch stem (kg in dry mass)\n w_l <- 1 / (1 / (0.108 * w_s^0.75) + 1 / 105) # leaves (kg in dry mass)\n w_r <- 0.023 * dbh^2.59 # coarse root (kg in dry mss)\n if (component == \"agb\") {\n return(w_s + w_l)\n } else if (component == \"all\") {\n return(w_s + w_l + w_r)\n } else if (component == \"stem\") {\n return(w_s)\n } else if (component == \"leaf\") {\n return(w_l)\n } else if (component == \"root\") {\n return(w_r)\n } else {\n stop(\"Invalid 'component'. Expected one of: 'all', 'agb', 'stem', 'leaf', 'root'\")\n }\n}\n\n\n# common turnover rate\nturnover <- function(y, z, t) {\n f <- function(rho) {\n sum(y * exp(-rho * t) - z)\n }\n df <- function(rho) {\n sum(-t * y * exp(-rho * t))\n }\n # Newton-Rapton iteration\n rho <- 0.02\n precision <- 1.0e-12 # to stop iteration\n change <- precision + 1.0\n\n while (change > precision) {\n rho2 <- rho - f(rho) / df(rho)\n change <- abs(rho2 - rho)\n rho <- rho2\n }\n return(rho)\n}\n\n\n# production rate\nproductivity <- function(dbh1, dbh2, w1, w2, t, dbh_min, mass_min, area) {\n si <- ifelse(dbh1 >= dbh_min & dbh2 >= dbh_min, 1, 0) # survival\n di <- ifelse(dbh1 >= dbh_min & dbh2 < dbh_min, 1, 0) # death\n ri <- ifelse(dbh1 < dbh_min & dbh2 >= dbh_min, 1, 0) # recruitment\n\n Ns0 <- sum(si, na.rm = TRUE)\n N0 <- Ns0 + sum(di, na.rm = TRUE)\n NT <- Ns0 + sum(ri, na.rm = TRUE)\n Bs0 <- sum(si * w1, na.rm = TRUE)\n BsT <- sum(si * w2, na.rm = TRUE)\n B0 <- Bs0 + sum(di * w1, na.rm = TRUE)\n BT <- BsT + sum(ri * w2, na.rm = TRUE)\n # period-mean biomass and abundance\n Nw <- ifelse(NT != N0, (NT - N0) / log(NT / N0), N0)\n N <- Nw / area # (per ha)\n Bw <- ifelse(BT != B0, (BT - B0) / log(BT / B0), B0)\n B <- Bw / area\n\n # Standardized maximum tree mass for initial population\n W_max <- as.numeric(quantile(w1[ri != 1], 0.99)) # Mg\n\n # turnover rates\n r <- turnover(si + ri, si, t)\n m <- turnover(si + di, si, t)\n p <- turnover(w2, si * w1, t)\n l <- turnover(w1, si * w1, t)\n\n # absolute productivity (Mg per ha per year)\n P <- p * B\n P_simple <- sum(((si + ri) * w2 - si * w1) / t)\n P_simple_Clark <- sum(si * (w2 - w1) / t + ri * (w2 - mass_min) / t)\n P_simple <- P_simple / area\n P_simple_Clark <- P_simple_Clark / area # cf. Clark et al. (2001, Ecol. Appl.)\n\n return(list(\n \"B\" = B,\n \"N\" = N,\n \"W_max\" = W_max,\n \"p\" = p,\n \"l\" = l,\n \"r\" = r,\n \"m\" = m,\n \"P\" = P,\n \"P_simple\" = P_simple,\n \"P_simple_Clark\" = P_simple_Clark\n ))\n}\n\n\n# Load data ---------------------------\ndf1 <- read.csv(\"data/pfr_observed.csv.gz\", header = TRUE)\ndf2 <- read.csv(\"data/pfr_identity_free.csv.gz\", header = TRUE)\n\n# Boundary size in dbh (cm)\ndbh_min <- 1.\n\ndata_preparation <- function(d) {\n # remove rows if both dbh1 and dbh2 lower than dbh_min\n d <- filter(d, dbh1 >= dbh_min | dbh2 >= dbh_min)\n\n # add some columns to the dataframe\n d <- d %>%\n mutate(\n dbh1 = ifelse(dbh1 >= dbh_min, dbh1, 0),\n dbh2 = ifelse(dbh2 >= dbh_min, dbh2, 0),\n w1 = biomass(dbh1) / 1000, # tree biomass in Mg\n w2 = biomass(dbh2) / 1000,\n )\n\n # Select species with NsT >= 100\n counts <- table(pull(filter(d, dbh1 >= dbh_min & dbh2 >= dbh_min), Cd))\n sp_list <- names(counts)[counts >= 100]\n\n # rename the remaining species to 'Others'\n d <- d %>%\n mutate(\n Cd = ifelse(Cd %in% sp_list, as.character(Cd), \"Others\"),\n Cd = factor(Cd, levels = c(sp_list, \"Others\"))\n )\n\n # sort Cd to make 'Others' to be the last\n sp_order <- order(d$Cd)\n d <- d[sp_order, ]\n return(d)\n}\n\ndf1 <- data_preparation(df1)\ndf2 <- data_preparation(df2)\n\n# Estimate production rate ------------\n# for each Cd\ndbh_min <- 1.\nmass_min <- biomass(2) / 1000 # tree biomass in Mg at dbh = 2 cm\narea <- 50 # total area in ha\n\nres1 <- df1 %>%\n group_nest(Cd) %>%\n mutate(y = purrr::map(data, ~ as_tibble(\n with(., productivity(dbh1, dbh2, w1, w2, t, dbh_min, mass_min, area))\n ))) %>%\n select(-data) %>%\n unnest(cols = y)\n\nres2 <- df2 %>%\n group_nest(Cd) %>%\n mutate(y = purrr::map(data, ~ as_tibble(\n with(., productivity(dbh1, dbh2, w1, w2, t, dbh_min, mass_min, area))\n ))) %>%\n select(-data) %>%\n unnest(cols = y)\n\n\n# write results\noutdir <- \"output\"\ndir.create(outdir, showWarnings = FALSE)\nwrite.csv(res1, file.path(outdir, \"res_pfr_observed.csv\"), row.names = FALSE)\nwrite.csv(res2, file.path(outdir, \"res_pfr_identity_free.csv\"), row.names = FALSE)\n\n\n# Plot productivity ~ biomass ---------\n# Cd-sum plot-level productivity (Mg per ha per year)\nPs1 <- with(res1, c(sum(p * B), sum(P_simple), sum(P_simple_Clark)))\nPs2 <- with(res2, c(sum(p * B), sum(P_simple), sum(P_simple_Clark)))\nnames(Ps1) <- c(\"P\", \"P_simple\", \"P_simple_Clark\")\nnames(Ps2) <- c(\"P\", \"P_simple\", \"P_simple_Clark\")\nprint(\"Observed\")\nprint(Ps1)\nprint(\"Identity free\")\nprint(Ps2)\n\n# fit the linear regression model\nfit1 <- lm(log(p) ~ log(B), data = filter(res1, Cd != \"Others\"))\npval1 <- summary(fit1)$coefficients[2, 4]\nprint(\"Observed\")\nprint(summary(fit1))\n\nfit2 <- lm(log(p) ~ log(B), data = filter(res2, Cd != \"Others\"))\npval2 <- summary(fit2)$coefficients[2, 4]\nprint(\"Identity-free\")\nprint(summary(fit2))\n\n# draw a plot\nxbreaks = c(.01, 1, 100)\np1 <- ggplot(filter(res1, Cd != \"Others\"), aes(x = B, y = p)) +\n geom_point(alpha = .5) +\n geom_point(data = filter(res1, Cd == \"Others\"), shape = 18, size = 3, alpha = .5) +\n annotate(\n \"curve\",\n x = 20, y = .12, xend = 45.4, yend = .028,\n curvature = -.25,\n arrow = arrow(length = unit(2, \"mm\"))\n ) +\n annotate(\"text\", x = 10, y = .2, label = \"rare species\\ncombined\", hjust = .5) +\n scale_x_log10(limits = c(.0005, 100), breaks = xbreaks, labels = xbreaks) +\n scale_y_log10(limits = c(.001, .5)) +\n labs(\n title = \"(a) observed\",\n x = parse(text = \"Biomass*','~B~(Mg %.% ha^{-1})\"),\n y = parse(text = \"Relative~productivity*','~p~(year^{-1})\")\n )\n\np2 <- ggplot(filter(res2, Cd != \"Others\"), aes(x = B, y = p)) +\n geom_point(alpha = .5) +\n geom_point(data = filter(res2, Cd == \"Others\"), shape = 18, size = 3, alpha = .5) +\n scale_x_log10(limits = c(.0005, 100), breaks = xbreaks, labels = xbreaks) +\n scale_y_log10(limits = c(.001, .5)) +\n labs(\n title = \"(b) identity-free\",\n x = parse(text = \"Biomass*','~B~(Mg %.% ha^{-1})\"),\n y = parse(text = \"Relative~productivity*','~p~(year^{-1})\")\n )\n\nif (pval1 < .05) {\n p1 <- p1 + geom_smooth(method = \"lm\", formula = y ~ x)\n}\n\nif (pval2 < .05) {\n p2 <- p2 + geom_smooth(method = \"lm\", formula = y ~ x)\n}\n\np <- cowplot::plot_grid(p1, p2)\n\n# save a plot\noutdir <- \"figs\"\ndir.create(outdir, showWarnings = FALSE)\nggsave(p, file = file.path(outdir, \"p-B.png\"), width = 8.5, height = 4)\n", "meta": {"hexsha": "d17218a30d3a1dbb567f6938bec641e93a24372d", "size": 7011, "ext": "r", "lang": "R", "max_stars_repo_path": "turnover_pfr.r", "max_stars_repo_name": "kohyamat/p-B", "max_stars_repo_head_hexsha": "e2eacb755aa865def87b7ca17e91c7284e110675", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-27T16:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T03:43:27.000Z", "max_issues_repo_path": "turnover_pfr.r", "max_issues_repo_name": "kohyamat/p-B", "max_issues_repo_head_hexsha": "e2eacb755aa865def87b7ca17e91c7284e110675", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "turnover_pfr.r", "max_forks_repo_name": "kohyamat/p-B", "max_forks_repo_head_hexsha": "e2eacb755aa865def87b7ca17e91c7284e110675", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2125, "max_line_length": 86, "alphanum_fraction": 0.5779489374, "num_tokens": 2521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.478107704702877}} {"text": "# Inverse function\nmyginv <- function (X, tol = sqrt(.Machine$double.eps)){\n ## the ginv function for symmetric matrices. it avoid some errors.\n if (length(dim(X)) > 2L || !(is.numeric(X) || is.complex(X)))\n stop(\"'X' must be a numeric or complex matrix\")\n if (!is.matrix(X))\n X <- as.matrix(X)\n\t if(!isSymmetric(X))\n\t\t X <- (X + t(X))/2\n Xeigen <- eigen(X,symmetric=T)\n Positive <- Xeigen$values > max(tol * Xeigen$values[1L], 0)\n if (all(Positive))\n Xeigen$vectors %*% (1/Xeigen$values * t(Xeigen$vectors))\n else if (!any(Positive))\n array(0, dim(X)[2L:1L])\n else Xeigen$vectors[, Positive, drop = FALSE] %*% ((1/Xeigen$values[Positive]) *\n t(Xeigen$vectors[, Positive, drop = FALSE]))\n}\n \nmtxInvPrx <- function(d,w,LD.matrix,thrw,thrctd=1,thrp=length(d)/2,thrp2=thrp/2,thrp3=5){ ### This function approximates the inverse of D+diag(w)%*%LD.matrix%*%diag(w)\n p <- length(w)\n wsq <- w^2\n rkwsq <- rank(wsq)\n wsqcumsum <- sapply(1:p, function(ii) sum(wsq[rkwsq<=ii]))\n wstat <- wsqcumsum+sqrt((p-(1:p))*wsqcumsum)\n rkthr <- min(max(which(wstatrkthr)\n if(sum(ix1) != 1){\n ctdmax <- apply(abs(LD.matrix-diag(diag(LD.matrix)))[ix1,],2,max)\n ctdmax[ix1] <- 0\n ix1 <- ix1|(ctdmax>=thrctd)\n ix2 <- !ix1 \n \n M0 <- sapply(1:p, function(ii) w[ii]*LD.matrix[ii,])\n M0 <- sapply(1:p, function(ii) w[ii]*M0[ii,])\n M <- diag(d)+M0\n Minv <- diag(1/d)\n if(isSymmetric(M[ix1,ix1])){\n Minv[ix1,ix1] <- myginv(M[ix1,ix1]) \n }else Minv[ix1,ix1] <- myginv((M[ix1,ix1]+t(M[ix1,ix1]))/2)#myginv(M[ix1,ix1])\n out <- Minv\n }else out <- 'ginv'\n out \n}\n\n\nvestepDirectSS <- function(posterior, para, LD.matrix, wzy, ycy, anno = matrix(1, length(wzy), 1), thrw.mtxinv = 0.1, thrctd.mtxinv = 0.8, thrp.mtxinv = length(wzy)){\n\tp <- length(wzy)\n\tgammabeta <- para$gammabeta\n\tlodanno <- anno%*%gammabeta \n\tqlodbeta <- matrix(posterior$lodbeta,p,1)\n\tqbeta <- 1/(1+exp(-qlodbeta))\n\n\t### update the posterior distribution of the prior distribution of pibeta\n\tupdatePibeta <- function(expanno, qbeta){\n\t\tshape1pibeta <- expanno + qbeta\n\t\tshape2pibeta <- 1/expanno+1-qbeta\n\t\tepibeta <- shape1pibeta/(shape1pibeta+shape2pibeta)\n\t\telogpibeta <- digamma(shape1pibeta) - digamma(shape1pibeta+shape2pibeta)\n\t\telogpibetac <- digamma(shape2pibeta) - digamma(shape1pibeta+shape2pibeta)\n\t\telodpibeta <- elogpibeta - elogpibetac\n\t\tout <- list(par = list(shape1pibeta = shape1pibeta, shape2pibeta = shape2pibeta), stat = list(epibeta = epibeta,\n\t\t\telodpibeta = elodpibeta, elogpibeta = elogpibeta, elogpibetac = elogpibetac))\n\t\tout\n\t}\n \n \n\t### update the posterior distribution of tau\n\tupdateTau <- function(para, qbeta){\n\t\tvareps <- para$vareps\n\t\tnutau <- para$nutau\n\t\tAt <- try(myginv(diag(as.vector(qbeta))%*%LD.matrix%*%diag(as.vector(qbeta))+diag(as.vector(qbeta-qbeta^2))+diag(1,p)/nutau))\n\t\tif (class(At) == 'try-error') {\n\t\t\tcat('Caught an error during full inversion, trying approximation.\\n')\n\t\t\tAt <- mtxInvPrx(d=1/nutau+as.vector(qbeta-qbeta^2), w=qbeta, LD.matrix=LD.matrix, thrw=thrw.mtxinv, thrctd=thrctd.mtxinv, thrp=thrp.mtxinv, thrp2=thrp.mtxinv/2) \n\t\t}\n\t\tvartau <- vareps*At\n\t\tmutau <- At%*%(qbeta*wzy)\n\t\tout <- list(A = At, vartau = vartau, mutau = mutau)\n\t\tout\n\t}\n \n\tpost.tau <- updateTau(para,qbeta)\n\n\t### update the posterior distribution of sbeta (signal of each SNP)\n\tupdateSbeta <- function(para, lodprior, posttau, qbeta){\n\t\tvareps <- para$vareps\n\t\tvartau <- posttau$vartau\n\t\tmutau <- posttau$mutau\n\t\tmuwzy <- LD.matrix%*%(mutau*qbeta)\n\t\tres <- (wzy - muwzy)\n\t\tpost.lodbeta <- lodprior-(1/(2*vareps))*(diag(LD.matrix)*(mutau^2+diag(vartau))-2*mutau*res-2*mutau^2*qbeta+2*(LD.matrix*vartau)%*%qbeta-2*diag(LD.matrix)*diag(vartau)*qbeta)\n\t\tout <- list(lodbeta = post.lodbeta)\n\t\tout\n\t}\n\t\n\tpost.sbeta <- updateSbeta(para, lodanno, posttau = post.tau, qbeta)\n \n\tout <- list(posterior = c(post.sbeta, post.tau), stat = NULL)\n\tout\n} ### End of \"vestepDirectSS\"\n\n\nvmstepDirectSS <- function(post, LD.matrix, wzy, ycy, init = list(gammabeta = rep(0, dim(anno)[2]), vareps = 1, nutau = 5), anno = matrix(1, length(wzy), 1), iter.max.mstep = 100){\n\tp <- length(wzy)\n\tmutau <- post[['posterior']]$mutau\n\tvartau <- post[['posterior']]$vartau\n\tlodbeta <- post[['posterior']]$lodbeta\n\tqbeta <- 1/(1+exp(-lodbeta))\n\tmubeta <- mutau*qbeta\n\tqdly <- (ycy-2*sum(wzy*mubeta)+sum(mubeta*(LD.matrix%*%mubeta))+sum(qbeta*((LD.matrix*vartau)%*%qbeta))+sum(diag(LD.matrix)*(qbeta-qbeta^2)*(mutau^2+diag(vartau))))\n\tqdltau <- sum((mutau^2+diag(vartau))*qbeta) \n \n\tvareps <- qdly/(p-sum(qbeta))\n\tnutau <- qdltau/sum(qbeta)/vareps \n \n\tloglkpibetaprior <- function(gammabeta){\n\t\tlodanno <- anno%*%matrix(gammabeta, ncol = 1)\n\t\tout <- -qbeta*lodanno+log(1+exp(lodanno))\n\t\tsum(out)\n\t}\n\t\n\tout.loglkpibetaprior <- optim(par = init$gammabeta, fn = loglkpibetaprior, method = \"BFGS\", hessian = TRUE, control = list(maxit = iter.max.mstep))\n\tout <- list(par = list(gammabeta = out.loglkpibetaprior$par, vareps = vareps, nutau = nutau), hess = list(pibetaprior = out.loglkpibetaprior$hessian))\n\tout\n} ### End of \"vmstepDirectSS\"\n\n\n\nvemDirectSS <- function(LD.matrix, GEMsummstats, anno = NULL, iter.max = 200, iter.max.mstep = 100, er.max = 1e-5, \n init = list(gammabeta = c(-1, rep(0, dim(anno)[2] - 1)), vareps = sd(GEMsummstats)^2, nutau = 2), \n posterior.init = list(lodbeta = matrix(0, length(GEMsummstats), 1))){\n thrw.mtxinv = 0.1 \n thrctd.mtxinv=0.8\n wzy <- GEMsummstats\n\tp <- length(wzy)\n\tif(is.null(anno)) anno <- matrix(1, p, 1)\n\tLD.matrix.inv <- myginv(LD.matrix)\n\tycy <- as.numeric(t(wzy)%*%LD.matrix.inv%*%wzy)\n\tposterior.old <- posterior.init\n\twzy <- matrix(wzy,p,1)\n\n\tvaicDirect <- function(para,post){\n \t\tmutau <- post[['posterior']]$mutau\n\t\tvartau <- post[['posterior']]$vartau\n\t\tlodbeta <- post[['posterior']]$lodbeta\n\t\tvareps <- para[['vareps']]\n\t\tqbeta <- 1/(1+exp(-lodbeta))\n\t\tmubeta <- mutau*qbeta\n\t\tp <- length(lodbeta)\n\t\tqdly <- (ycy-2*sum(wzy*mubeta)+sum(mubeta*(LD.matrix%*%mubeta))+sum(qbeta*((LD.matrix*vartau)%*%qbeta))+sum(diag(LD.matrix)*(qbeta-qbeta^2)*(mutau^2+diag(vartau))))\n\t\tely <- -qdly/(2*vareps) -(p/2)*log(vareps)\n\t\tmly <- -(ycy-2*sum(wzy*mubeta)+sum(mubeta*(LD.matrix%*%mubeta)))/(2*vareps) -(p/2)*log(vareps)\n\t\tpd <- 2*(mly-ely)\n\t\tvaic <- -2*mly+2*pd\n\t\tvaic\n\t}\n\n\ter <- Inf\n\tll.all <- Inf\n\tll.old <- Inf\n\titer <- 1\n\tmstep.all <- list()\n\n\t### The algorithm stop until the hyperparameter estimation converges in relative error.\n\twhile((abs(er)>er.max)&(iterer.max)&(iter0)\n if(sum(y)>0){ x1 <- mean(x[y])\n }else{ x1 <- 0}\n x1\n}\n\nlbAnno <- function(x, y, post, nrep=1000){ \n y <- as.numeric(y)\n n <- length(y)\n n1 <- sum(y>0)\n shm <- sapply(1:nrep, function(ii){\n idii <- sample(n,n1,replace=FALSE)\n out <- mean(x[idii])\n out })\n out <- sum(shm >= post)/nrep\n out\n}\n\nannoEnrich <- function(iFunMedNull, annoMtx, Nperm = 5000, cores = 20){\n require(parallel)\n idanno <- colnames(annoMtx)\n ## posterior porbabilities from the null model\n post.null <- list(GEM = iFunMedNull[['PostProb']][['GEM']],\n DEM = iFunMedNull[['PostProb']][['DEM']])\n \n ## average posterior probability of inclusion of the SNPs with the annotation, for each annotation\n post.meananno.null <- lapply(post.null, function(x) apply(annoMtx, 2, meanAnno, x = x))\n \n anno.enrichment <- mclapply(names(post.null), function(x) sapply(1:length(idanno), function(y) lbAnno(post.null[[x]], annotation.matrix[, y], post.meananno.null[[x]][y], nrep = Nperm)), mc.cores = cores, mc.preschedule = FALSE)\n names(anno.enrichment) <- names(post.null)\n names(anno.enrichment[['GEM']]) <- names(post.meananno.null[['GEM']])\n names(anno.enrichment[['DEM']]) <- names(post.meananno.null[['DEM']])\n \n return(list(enrichmentPval = anno.enrichment, avePP = post.meananno.null))\n}\n", "meta": {"hexsha": "fcaab446b055d541fd475d1d076281814da39dfa", "size": 16192, "ext": "r", "lang": "R", "max_stars_repo_path": "iFunMed_base.r", "max_stars_repo_name": "mcrojo/iFunMed", "max_stars_repo_head_hexsha": "c0f6d8417c340f69d7c939188988e28f803bbf6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-31T19:56:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-31T19:56:18.000Z", "max_issues_repo_path": "iFunMed_base.r", "max_issues_repo_name": "keleslab/iFunMed", "max_issues_repo_head_hexsha": "c0f6d8417c340f69d7c939188988e28f803bbf6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iFunMed_base.r", "max_forks_repo_name": "keleslab/iFunMed", "max_forks_repo_head_hexsha": "c0f6d8417c340f69d7c939188988e28f803bbf6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-13T22:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-14T01:41:06.000Z", "avg_line_length": 38.6443914081, "max_line_length": 229, "alphanum_fraction": 0.646986166, "num_tokens": 5957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4778913740392869}} {"text": "#' Effective number of codons\n#'\n#' This function calculate the effective number of codons (ENC) using Wright's formula.\n#'\n#' @param x a list of KZsqns objects\n#' @param spp.list an array indicating the the species identity of each KZsqns object in the list \\emph{x}. The default option is to calculate an ENC for each KZsqns object. When \\emph{spp.list} is specified, an ENC is calculated for each unique element of \\emph{spp.list}\n#' @param y a number to assign the type of codon table to be used for the translation. 0 = standard codon table, 2 = vertibrate mitchodrial (See dna2aa for additional options). If no number is specified or an option other than those provided above is specified, there will be a warning and the standard codon table will be used\n#' @param formula a char array to denote the formula for calculating ENC. Options include: 'w': Wright's formula, 'f4-': Fuglsang's Ncf4- formula.\n#' @return an numeric array of the ENCs\n#' @section Warning:\n#' According to Wright's formula, the ENC is the sum of the heterogeneity of all the degeneracy classes. When all the codons belonging to a degeneracy class is missing, the ENC can not be calculated. A warning will result when it happens. The most likely situation leading to such a condition is that the sequence of codons is too short. When the sequence is short, the calculated ENC is likely to deviate much from the underlying value. It is recommended to increase the sample size to solve this issue when Wright's formula is prefered. Alternatively, Fuglsang's Ncf4- formula could be used instead.\n#' @references\n#' Fuglsang, A., 2006 Estimating the \"Effective Number of Codons\": The Wright way of determining codon homozygosity leads to superior estimates. Genetics 172:1301-1307\n#' Wright, F., 1990 The 'effective number of codons' used in a gene. Gene 87: 23-29.\n#' @examples\n#' dnalist = vector('list', 2)\n#' dnalist[[1]] = CodonTable2[sample(1:64, 1e4, TRUE),1]\n#' attr(dnalist[[1]], 'class') <- 'KZsqns'\n#' dnalist[[2]] = CodonTable2[sample(1:64, 1e4, TRUE),1]\n#' attr(dnalist[[2]], 'class') <- 'KZsqns'\n#' enc(x = dnalist, y = 2) # Two numbers should be around 60 as there are 60 animo acid coding codons and 4 stop codons for codon table 2\n#'\n#' dnalist = vector('list', 2)\n#' dnalist[[1]] = CodonTable2[sample(1:64, 1e4, TRUE),1]\n#' attr(dnalist[[1]], 'class') <- 'KZsqns'\n#' dnalist[[2]] = CodonTable2[sample(1:64, 1e4, TRUE),1]\n#' attr(dnalist[[2]], 'class') <- 'KZsqns'\n#' enc(x = dnalist, y = 4) # Two numbers should be around 62 as there are 60 animo acid coding codons and 2 stop codons for codon table 4\n#' @export\n\nenc <- function(x, y=0, spp.list='n', formula = 'w'){\n if(!is.list(x)) x = list(x)\n cTable = arg_check(x[[1]], \"KZsqns\", y)\n calc = nc_wright\n switch(formula,\n 'f4-' = {calc = nc_fuglsang4m},\n 'w' = {},\n {\n warning(\"Not a valid formula, and Wright's formula will be used.\")\n })\n if(length(spp.list)==1 && spp.list=='n'){\n cat(\"No species list is provided\\nCalculating ENCs for each KZsqns object.\\n\")\n return(sapply(x, function(i){calc(table(i), cTable)}))\n } else {\n if (length(spp.list)!=length(x)) stop(\"The lengths of the species list and the list of KZsqns do not match\")\n spp = unique(spp.list)\n fixx = function(i){\n jobs = which(spp.list==spp[i])\n ans = rep(0, 64)\n for(j in jobs){\n ans = rbind(ans, table(x[[j]])[cTable[,1]])\n }\n ans = colSums(ans, na.rm = TRUE)\n names(ans) <- cTable[,1]\n return(ans)\n }\n ans = sapply(1:length(spp), function(i){calc(fixx(i), cTable)})\n names(ans) <- spp\n return(ans)\n }\n}\n", "meta": {"hexsha": "2b5e0b1b8399545fdf228f08fd6f7ae37b3018fb", "size": 3641, "ext": "r", "lang": "R", "max_stars_repo_path": "R/enc.r", "max_stars_repo_name": "HVoltBb/kondonz", "max_stars_repo_head_hexsha": "5fd777eca9f07a983c485be76de981a52efa42f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/enc.r", "max_issues_repo_name": "HVoltBb/kondonz", "max_issues_repo_head_hexsha": "5fd777eca9f07a983c485be76de981a52efa42f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-07T00:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-07T18:19:25.000Z", "max_forks_repo_path": "R/enc.r", "max_forks_repo_name": "HVoltBb/kodonz", "max_forks_repo_head_hexsha": "5fd777eca9f07a983c485be76de981a52efa42f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.7258064516, "max_line_length": 601, "alphanum_fraction": 0.6816808569, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.47773833392425685}} {"text": "# rocauc.r - plot ROC and compute AUC given score+label table with R using RROC\n#\n# Alex Stivala, October 2008\n#\n# Requires the ROCR package from CRAN (developed with version 1.0-2)\n# (ROCR in turn requires gplots, gtools, gdata)\n#\n# Run this on the output of e.g. tsevalfn.py with the -l option,\n# it is a table with one column of scores from classifier, and second\n# column of true class label (0 or 1)\n#\n# Uses commandArgs() R function to get trailing arguments from R command\n# line ie after the --args option. The filename of the .slrtab file\n# is obtained from --args, and the output file is constructed form it\n# eg foo.slrtab results in foo.eps file for ROC plot with\n# \n# R --vanilla -f rocauc.r --args foo.slrtab\n#\n#\n# The citation for the ROCR package is\n# Sing et al 2005 \"ROCR: visualizing classifier performance in R\"\n# Bioinformatics 21(20):3940-3941\n# \n# \n# Also calculate stdand eror (and 95% confidence inteval) for the AUC,\n# according to Hanley-McNeil method:\n# Hanley & McNeil 1982 \"The Meaning and Use of the Area under a Receiver\n# Operating Characteristic (ROC) Curve\" Radiology 143(1):29-36\n# ROCR has all sorts of featuers but this isn't one of them so had\n# to implement it here.\n#\n\n# $Id: rocauc.r 3606 2010-05-04 06:03:55Z alexs $\n\nlibrary(ROCR)\n\n#\n# functions\n#\n\n#\n# compute AUC and standard error and 95% CI by Hanley-McNeil method,\n# using R wilcox.test for the Wilcoxon rank-sum (aka Mann-Whitney) test\n# \n# Parameters:\n# tab : data frame with score and label columns\n# \n# Return value:\n# list with auc and stderror members\n#\ncompute_auc_error <- function(tab)\n{\n # tab is a data frame with score and label columns\n x <- tab$score[tab$label == 1]\n y <- tab$score[tab$label == 0]\n wilcox <- wilcox.test(x,y)\n nA <- length(x)\n nN <- length(y)\n stopifnot(nA + nN == length(tab$label))\n nA <- as.double(nA)\n nN <- as.double(nN)\n U <- wilcox$statistic # Mann-Whitney U statistic\n theta <- U / (nA * nN) # AUC\n theta2 <- theta*theta\n Q1 <- theta / (2 - theta)\n Q2 <- 2*theta2 / (1 + theta)\n SE2 <- (theta*(1-theta) + (nA - 1)*(Q1 - theta2) + (nN - 1)*(Q2 - theta2)) /\n (nA*nN)\n SE <- sqrt(SE2)\n\n retval <- list()\n retval$auc <- theta\n retval$stderror <- SE\n return(retval)\n}\n\n#\n# plot the ROC curve and compute AUC using ROCR\n#\nplotroc <- function(filename)\n{\n tab <- read.table(filename, header=TRUE)\n # tab is a data frame with score and label columns\n pred <- prediction(tab$score, tab$label)\n perfroc <- performance(pred, measure=\"tpr\",x.measure=\"fpr\")\n perfauc <- performance(pred, measure=\"auc\")\n\n # EPS suitable for inserting into LaTeX\n postscript(sub('[.]slrtab$','.eps',filename),\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\n plot(perfroc)\n auc <- perfauc@y.values\n legend('bottomright', legend=paste('AUC =', format(auc, digits=4)), bty='n')\n dev.off()\n\n aucerr <- compute_auc_error(tab)\n quantile <- 1.96 # 0.975 quantile of normal distrib\n low95 <- aucerr$auc - quantile * aucerr$stderr\n high95 <- aucerr$auc + quantile * aucerr$stderr\n\n cat(filename,':\\n')\n cat('RROC AUC =',format(perfauc@y.values,digits=4),'\\n')\n cat('Hanley-McNeil AUC =',format(aucerr$auc,digits=4),'\\n')\n cat(' std. error =',format(aucerr$stderror,digits=5),'\\n')\n cat(' 95% CI =',format(low95,digits=4),',',\n format(high95,digits=4),'\\n')\n}\n\n\n#\n# main\n#\nfilename <- commandArgs(trailingOnly=TRUE)\nplotroc(filename)\n\n", "meta": {"hexsha": "be8159c76d8142983334754343ccfa025ac4758b", "size": 3588, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/rocauc.r", "max_stars_repo_name": "stivalaa/cuda_satabsearch", "max_stars_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/rocauc.r", "max_issues_repo_name": "stivalaa/cuda_satabsearch", "max_issues_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/rocauc.r", "max_forks_repo_name": "stivalaa/cuda_satabsearch", "max_forks_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 80, "alphanum_fraction": 0.6460423634, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4774420138170171}} {"text": "#' Time derivative of DO concentration\n#' \n#' @param t Time step for the ode integration\n#' @param y Current state (dissolved oxygen concentration)\n#' @param parms a named vector of parameters; see details\n#' @param data a list of data for the ode; see details\n#' @param return_list logical, should a list (suitable for deSolve) be returned?\n#' @details `params` must be a vector including the following named items:\n#' * `P1` $(W min g^{-1} O_2)$ inverse of the slope of a photosynthesis–irradiance curve at low\n#' \t\t light intensity\n#' * `P2` $(m^2 min g^{-1} O_2)$ inverse maximum photosynthesis rate; can be zero to assume\n#' \t\t GPP is linear with light intensity instead of saturating\n#' * `k600` coefficient of gas exchange for a gas with a Schmidt number of 600 (see [kT()]).\n#' * `ER24_20` daily ecosystem respiration rate, standardized at 20 degrees C\n#' \n#' `data` is a named list of (constant) data items, including the following:\n#' * `PAR` a function that takes time as a parameter and returns light intensity $(W/m^2)$\n#' * `temp` a function that takes time as a parameter and returns water temperature (degrees C)\n#' * `P` pressure, in atmospheres\n#' * `z` Depth, in meters\n#' \n#' @references Fuß, T. et al. (2017). Land use controls stream ecosystem metabolism by shifting\n#' \t\t dissolved organic matter and nutrient regimes. *Freshw Biol* **62**:582–599.\n#' \n#'\t\t Van de Bogert MC et al. 2007. Assessing pelagic and benthic metabolism using free\n#' \t\t water measurements. *Limnol. Oceanogr. Methods* **5**:145–155. \n#' \n#' @return Time derivative of dissolved oxygen\n#' @export\noneStation_dDOdt <- function(t, y, parms, data, return_list=FALSE)\n{\n\twarning(\"oneStation_dDOdt is deprecated; use DOCalibration(..., method = 'stan' instead)\")\n\t# gross primary production; Fuß et al eq 2\n\tGPP <- gpp(data$PAR(t), parms['P1'], parms['P2'])\n\n\t# rearation flux, Van de Bogert et al eqn 4; note that k600 is fixed\n\tRF <- kT(data$temp(t), parms['k600']) * (osat(data$temp(t), data$P) - y)\n\n\t# ecosystem respiration; Fuß et al eq 4\n\tER <- (parms['ER24_20'] / (60*24)) * (1.045^(data$temp(t) - 20))\n\n\tval <- (GPP + ER + RF) / data$z\n\tif(return_list) {\n\t\treturn(list(val))\n\t} else {\n\t\treturn(val)\n\t}\n}\n\n#' Predict a time series of dissolved oxygen concentration\n#' @param initial initial dissolved oxygen concentration\n#' @param times The times at which to solve the system\n#' @param params a named vector of parameters; see details\n#' @param data a list of data for the ode; see details\n#' @param dt Time step for integration; only used if `method == 'euler'`\n#' @param method The integration method to use; default is euler\n#' @param gpp Logical, should GPP at each time step be returned as well?\n#' @details Light and temperature time series will be approximated using linear interpolation\n#' \t\tat the desired time steps\n#' \n#' `params` must be a vector including the following named items:\n#' * `P1` $(W min g^{-1} O_2)$ inverse of the slope of a photosynthesis–irradiance curve at low\n#' \t\t light intensity\n#' * `P2` $(m^2 min g^{-1} O_2)$ inverse maximum photosynthesis rate; can be zero to assume\n#' \t\t GPP is linear with light intensity instead of saturating\n#' * `k600` coefficient of gas exchange for a gas with a Schmidt number of 600; (see [kT()])\n#' * `ER24_20` daily ecosystem respiration rate, standardized at 20 degrees C\n#' \n#' `data` is a named list of (constant) data items, including the following:\n#' * `PAR` 2-column data frame; first column is light, second is time of observation\n#' * `temp` 2-column data frame; first column is temperature, second is time of observation\n#' * `P` pressure, in atmospheres\n#' * `z` Depth, in meters\n#' @return Time series of dissolved oxygen concentrations\n#' @export\noneStation_DOPredict <- function(initial, times, params, data, dt = 1, \n\t\t\tmethod=c('euler', 'lsoda'), gpp = FALSE) {\n\twarning(\"oneStation_DOPredict is deprecated; use DOCalibration(..., method = 'stan' instead)\")\n\tmethod <- match.arg(method)\n\tif(method == \"lsoda\" && !(requireNamespace(\"deSolve\")))\n\t\tstop(\"Package deSolve is required for method lsoda; please install it and try again\")\n\tif(times[1] != 0)\n\t\tstop('first time step must be 0')\n\tif(method == 'euler' && sum(times %% dt) != 0)\n\t\tstop('dt must divide evenly into all values in times')\n\n\tdDOData <- list(\n\t\tPAR = approxfun(x = data$PAR[,2], y = data$PAR[,1], rule = 2),\n\t\ttemp = approxfun(x = data$temp[,2], y = data$temp[,1], rule = 2),\n\t\tP = data$P,\n\t\tz = data$z)\n\n\tif(method == 'euler') {\n\t\tstate <- numeric(length(times))\n\t\tstate[1] <- statet <- initial\n\t\tt <- times[1]\n\t\tfor(i in 2:length(state)) {\n\t\t\twhile(t < times[i]) {\n\t\t\t\tstatet <- statet + dt * oneStation_dDOdt(t, statet, params, dDOData)\n\t\t\t\tt <- t + dt\n\t\t\t}\n\t\t\tstate[i] <- statet\n\t\t}\n\t} else {\n\t\tstate <- deSolve::ode(initial, times = times, func = oneStation_dDOdt, parms = params, \n\t\t\tdata = dDOData, return_list=TRUE)\n\t\tstate <- state[,2]\n\t}\n\tif(gpp) {\n\t\tstate <- cbind(DO = state, GPP = gpp(dDOData$PAR(times), params['P1'], params['P2']))\n\t}\n\treturn(state)\n}\n\n#' Log posterior probability for the DO curve given empirical data\n#' @param params A named vector of model parameters; see details\n#' @param data A list of model data, see details\n#' @param prior A list of prior hyperparameters; see details\n#' @param ... Additional parameters to be passed to [DO_predict()]\n#' @details #' `params` must be a vector including the following named items:\n#' * `logP1` $(W min g^{-1} O_2)$ log(inverse of the slope of a photosynthesis–irradiance curve)\n#' \t\t at low light intensity\n#' * `logP2` $(m^2 min g^{-1} O_2)$ log(inverse maximum photosynthesis rate)\n#' * `logk600` coefficient of gas exchange for a gas with a Schmidt number of 600; (see [kT()])\n#' * `logMinusER24_20` log(-1 * daily ecosystem respiration rate), standardized at 20 degrees C\n#' * `logsd` log(Error standard deviation)\n#' \n#' `data` is a named list of (constant) data items, including the following:\n#' * `DO` 2-column data frame; first column is dissolved oxygen, second is time of observation\n#' * `PAR` 2-column data frame; first column is light, second is time of observation\n#' * `temp` 2-column data frame; first column is temperature, second is time of observation\n#' * `P` pressure, in atmospheres\n#' * `z` Depth, in meters\n#' \n#' `prior` is a list of hyperparameters for the priors on parameters listed under `params`.\n#' All priors are normal. Thus, each list item should be named (following the names from \n#' `params`), and each item should be a vector of length two giving the mean and standard\n#' deviation of the prior for that parameter. Note that each parameter is optional \n#' (as is the entire list); missing items will get a minimally informative normal(0,10)\n#' distribution.\n#' @return The unnormalized log probability of the model given the data\n#' @export\noneStation_DOlogprob <- function(params, data, prior = list(), ...) {\n\twarning(\"oneStation_DOlogprob is deprecated; use DOCalibration(..., method = 'stan' instead)\")\n\t# check for each parameter, assign default priors if not specified\n\ttrParNames <- c('logP1', 'logP2', 'logk600', 'logMinusER24_20', 'logsd')\n\tparNames <- c('P1', 'P2', 'k600', 'ER24_20', 'sd')\n\tfor(nm in trParNames) {\n\t\tif(! nm %in% names(prior))\n\t\t\tprior[[nm]] <- c(0,10)\n\t}\n\n\tinitial <- data$DO[1,1]\n\ttimes <- data$DO[,2]\n\n\t# parameters are log transformed to make sampling nicer\n\tdoParams <- oneStation_parTransform(params)\n\tpredicted <- oneStation_DOPredict(initial, times, doParams, data)\n\n\tlogprob <- sum(dnorm(data$DO[,1], predicted, doParams['sd'], log = TRUE)) + \n\t\tdnorm(params['logP1'], prior[['logP1']][1], prior[['logP1']][2], log = TRUE) + \n\t\tdnorm(params['logP2'], prior[['logP2']][1], prior[['logP2']][2], log = TRUE) + \n\t\tdnorm(params['logk600'], prior[['logk600']][1], prior[['logk600']][2], log = TRUE) + \n\t\tdnorm(params['logMinusER24_20'], prior[['logMinusER24_20']][1], prior[['logMinusER24_20']][2], log = TRUE) + \n\t\tdnorm(params['logsd'], prior[['logsd']][1], prior[['logsd']][2], log = TRUE)\n\n\treturn(logprob)\n}\n\n\n#' Transfornm parameters for the one station model\n#' @param params The vector of parameters, see [oneStation_DOlogprob()], or a matrix of\n#' \t\tsamples (in which case the transformation is applied to app samples)\n#' @param reverse Should the reverse transformation be applied?\n#' @details This function transforms the parameters of the one station model from the\n#' \tscale at which the parameters are calibrated to the scale of modelling. If\n#' `reverse == TRUE` the opposite transformation is performed.\n#' @return The transformed parameters\n#' @keywords internal\noneStation_parTransform <- function(params, reverse = FALSE) {\n\tif(reverse) {\n\t\tif(is.matrix(params)) {\n\t\t\tlogP1 <- log(params[,'P1'])\n\t\t\tlogP2 <- log(params[,'P2'])\n\t\t\tlogk600 <- log(params[,'k600'])\n\t\t\tlogMinusER24_20 <- log(-1 * params[,'ER24_20'])\n\t\t\tlogsd <- log(params[,'sd'])\n\t\t\tresult <- cbind(logP1, logP2, logk600, logMinusER24_20, logsd)\n\t\t} else {\n\t\t\tlogP1 <- log(params['P1'])\n\t\t\tlogP2 <- log(params['P2'])\n\t\t\tlogk600 <- log(params['k600'])\n\t\t\tlogMinusER24_20 <- log(-1 * params['ER24_20'])\n\t\t\tlogsd <- log(params['sd'])\n\t\t\tresult <- c(logP1 = logP1, logP2 = logP2, logk600 = logk600, \n\t\t\t\tlogMinusER24_20 = logMinusER24_20, logsd = logsd)\n\t\t}\n\t} else {\n\t\tif(is.matrix(params)) {\n\t\t\tP1 <- exp(params[,'logP1'])\n\t\t\tP2 <- exp(params[,'logP2'])\n\t\t\tk600 <- exp(params[,'logk600'])\n\t\t\tER24_20 <- -1 * exp(params[,'logMinusER24_20'])\n\t\t\tsd <- exp(params[,'logsd'])\n\t\t\tresult <- cbind(P1, P2, k600, ER24_20, sd)\n\t\t} else {\n\t\t\tP1 <- exp(params['logP1'])\n\t\t\tP2 <- exp(params['logP2'])\n\t\t\tk600 <- exp(params['logk600'])\n\t\t\tER24_20 <- -1 * exp(params['logMinusER24_20'])\n\t\t\tsd <- exp(params['logsd'])\n\t\t\tresult <- c(P1, P2, k600, ER24_20, sd)\n\t\t\tnames(result) <- c(\"P1\", \"P2\", \"k600\", \"ER24_20\", \"sd\")\n\t\t}\n\t}\n\treturn(result)\n}\n\n#' Produce posterior simulations for DO curve and GPP\n#' @param params Parameter posterior matrix returned (e.g.) from [DOCalibration()].\n#' @param data Data list as required by [oneStation_DOPredict()].\n#' @return list including predicted DO and GPP at each time step as well as the prediction times.\noneStation_DOSim <- function(params, data) {\n\tinitial <- data$DO[1,1]\n\ttimes <- data$DO[,2]\n\n\tsims <- apply(params, 1, function(par) {\n\t\tc(oneStation_DOPredict(initial, times, par, data, dt = 1, gpp=TRUE))\n\t})\n\tlist(DO = sims[1:length(times),], GPP = sims[(length(times)+1):nrow(sims),], times = times)\n}\n", "meta": {"hexsha": "542e580a05bfe6521c578f5a8a101af7c550895a", "size": 10439, "ext": "r", "lang": "R", "max_stars_repo_path": "R/onestation.r", "max_stars_repo_name": "mtalluto/NSmetabolism", "max_stars_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/onestation.r", "max_issues_repo_name": "mtalluto/NSmetabolism", "max_issues_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/onestation.r", "max_forks_repo_name": "mtalluto/NSmetabolism", "max_forks_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9956896552, "max_line_length": 111, "alphanum_fraction": 0.6799501868, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47731995698290386}} {"text": "#' @export\n\nd_rho <- function(rho, parms, z = 4) {\n with(parms, r* b* rho * (1 - rho/K) - m * rho - (a * rho * L)/(1 + a * h * rho) )\n}\n\n\n#' @export\nnoymeir <- list(\n defparms = list(\n m = 0.05,\n r = 1,\n b = 0.9,\n K = 0.9,\n a = 0.6,\n h = 100,\n L = 5\n ),\n odesys <- function (t, rho, parms = parms) {\n list( d_rho(rho, parms) )\n }\n)\n\n", "meta": {"hexsha": "55593d7b9b001d245e0bb3f83d0d23cc1432510b", "size": 351, "ext": "r", "lang": "R", "max_stars_repo_path": "R/noymeir.r", "max_stars_repo_name": "fdschneider/livestock", "max_stars_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-01T02:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:59:02.000Z", "max_issues_repo_path": "R/noymeir.r", "max_issues_repo_name": "fdschneider/livestock", "max_issues_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/noymeir.r", "max_forks_repo_name": "fdschneider/livestock", "max_forks_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.625, "max_line_length": 83, "alphanum_fraction": 0.4501424501, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4772030954526447}} {"text": "#!/usr/bin/Rscript\n\ncdfFromLogScaledCbf <- function()\n{\n # This function fabricates a cdf from a\n # \"Piecewise LogLinear Cumulative Byte Function\" of a workload.\n # all you need to do is to specify sizeIntervals and cbf (cumulative byte\n # function) values in below. The assumption is that cbf is piecewise linear\n # function of log10(sizeIntervals) with breakpoints defined in sizeIntervals\n # and cbf vectors.\n\n # monotonically increasing vector of msg sizes\n #sizeIntervals <- c(1, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 3529904)\n sizeIntervals <- c(1, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 15158197)\n\n # monotonically increaing cbf (cumulative byte function) vector. First element\n # is always 0 and last element is always one. Each cbf value in this vector\n # corresponds to a size in the sizeIntervals vector.\n #cbf <- c(0, .0016, .0160256, .01923077, .07051282, .4455128, .525641, .6025641, .6987179, .7403846, .7532051, .7660256, .7884615, .900641, .9455128, .9519231, 1)\n cbf <- c(0, .0001205128, .001010256, .0070385, .01602564, .05128205, .07051282, .09294872, .1185897, .1762821, .2564103, .3012821, .3461538, .4679487, .5512321, .6826923, 1)\n\n multipLiers <- (cbf[2:length(cbf)] - cbf[1:length(cbf)-1]) *\n (1/sizeIntervals[1:length(cbf)-1] - 1/sizeIntervals[2:length(cbf)]) /\n (log10(sizeIntervals[2:length(cbf)]) - log10(sizeIntervals[1:length(cbf)-1]))\n avgSize <- log(10)/sum(multipLiers)\n cdfRanges <- cumsum(multipLiers)/sum(multipLiers)\n cdfConsts <- c(0, cdfRanges[1:length(cdfRanges)-1])\n\n\n #create cdf sample vector and find the corresponding sizes.\n #cdf sample vector must be sorted: cdf <- seq(0.001, 1, 0.001)\n cdf <- c()\n cdfBounds <- c(0, cdfRanges)\n numElemDouble = 3\n for (ind in seq(1, length(cdfRanges)))\n {\n numElemDouble <- numElemDouble*1.3\n numElem <- as.integer(numElemDouble)\n cdf <- c(cdf, seq(cdfBounds[ind], cdfBounds[ind+1], (cdfBounds[ind+1] - cdfBounds[ind])/numElem))\n }\n cdf <- sort(unique(cdf))\n\n\n #Corresponding sizes for cdf values\n sizes <- c()\n for (cdfVal in cdf)\n {\n ind <- match(1, findInterval(cdfRanges, cdfVal))\n invMsgSize <- (1 / sizeIntervals[ind]) -\n ((cdfVal - cdfConsts[ind]) * log(10) *\n (log10(sizeIntervals[ind+1]) - log10(sizeIntervals[ind])) /\n (cbf[ind+1]-cbf[ind]) / avgSize)\n sizes <- c(sizes, 1/invMsgSize)\n }\n\n # round the sizes to integers and remove possible duplicates that rounding might\n # have caused.\n sizes <- round(sizes)\n unik <- !duplicated(sizes) #logical vector of unique values\n ind <- seq_along(sizes)[unik] #indices of unique values\n cdf <- cdf[ind]\n sizes <- sizes[ind]\n pdf <- cdf - c(0, cdf[1:length(cdf)-1])\n avgSize <- sum(pdf*sizes)\n\n filename = \"Google_AllRPC.txt\"\n write(avgSize, file=filename)\n df <- data.frame(sizes, cdf)\n write.table(df, file=filename, row.names=FALSE, col.names=FALSE, append=TRUE)\n}\n\ncdfFromCdfSamples <- function()\n{\n # This function fabricates a cdf from a\n # \"Piecewise LogLinear CDF Function\" of a workload.\n # all you need to do is to specify sizeIntervals and cdf\n # values in below. The assumption is that cdf is piecewise linear\n # function of log10(sizeIntervals) with breakpoints defined in sizeIntervals\n # and cdf vectors.\n\n # monotonically increasing vector of msg sizes\n sizeIntervals <- c()\n\n\n # monotonically increaing cdf vector. First element\n # is always 0 and last element is always one. Each cdf value in this vector\n # corresponds to a size in the sizeIntervals vector.\n cdfIntervals <- c()\n\n # For Facebook Hadoop All\n sizeIntervals <- c(50, 92 ,217 ,271 ,300 ,326 ,376 ,425 ,480 ,600 ,679 ,737 ,800 ,885 ,1042 ,1277 ,\n 1413 ,1534 ,1664 ,2214 ,3396 ,5210 ,7830 ,31946 ,36844 ,39973 ,44260 ,47050 ,51046 ,62583 ,\n 70722 ,75180 ,81565 ,102058 ,115331 ,133013 ,156563 ,184284 ,212546 ,240177 ,288520 ,470507 ,\n 736642 ,940700 ,1769244 ,2169118 ,10000000)\n cdfIntervals <- c(0, 0.0074 ,0.0149 ,0.0409 ,0.0520 ,0.1375 ,0.2026 ,0.2230 ,0.2639 ,0.4591 ,\n 0.5167 ,0.5520 ,0.5762 ,0.5912 ,0.6097 ,0.6282 ,0.6394 ,0.6468 ,0.6673 ,0.6747 ,0.6840 ,\n 0.6933 ,0.7082 ,0.7212 ,0.7305 ,0.7398 ,0.7584 ,0.7788 ,0.8160 ,0.8234 ,0.8327 ,0.8420 ,\n 0.8717 ,0.8885 ,0.8978 ,0.9070 ,0.9164 ,0.9257 ,0.9349 ,0.9442 ,0.9535 ,0.9628 ,0.9684 ,\n 0.9721 ,0.9814 ,0.9870 ,1.0000)\n\n # For FacebookWebServer\n #sizeIntervals <- c(50, 84 ,153 ,301 ,500 ,639 ,800 ,900 ,1000 ,1085 ,1357 ,1534 ,\n # 1664 ,1843 ,2000 ,3000 ,4000 ,5000 ,6000 ,7000 ,8000 ,9000 ,10000 ,14140 ,20000 ,\n # 24512 ,30000 ,34660 ,40000 ,45171 ,50000 ,60000 ,70000 ,80000 ,100000 ,144310 ,\n # 200000 ,260573 ,300000 ,353730 ,400000 ,442606 ,565213 ,778003 ,1000000)\n #\n #cdfIntervals <- c(0.0 ,0.061 ,0.126 ,0.215 ,0.226 ,0.2407 ,0.2537 ,0.2667 ,0.2926 ,\n # 0.3130 ,0.3352 ,0.3500 ,0.3722 ,0.3963 ,0.4093 ,0.4796 ,0.5259 ,0.5630 ,0.5889 ,\n # 0.6111 ,0.6260 ,0.6407 ,0.6519 ,0.6852 ,0.7148 ,0.7315 ,0.7463 ,0.7574 ,0.7667 ,\n # 0.7759 ,0.7815 ,0.7926 ,0.8 ,0.8074 ,0.8148 ,0.8241 ,0.8574 ,0.8944 ,0.9222 ,\n # 0.9556 ,0.9741 ,0.9833 ,0.9907 ,0.9963 ,1.0)\n\n # For Facebook CacheFollower Intracluster\n #sizeIntervals <- c(50 ,68 ,144 ,266 ,340 ,490 ,577 ,639 ,707 ,900 ,1042 ,1110 ,1303 ,1414 ,1440 ,2000 ,\n # 2450 ,3000 ,3466 ,4000 ,5000 ,6000 ,8000 ,10000 ,13855 ,16643 ,18057 ,25531 ,28270 ,36101 ,44260 ,\n # 62583 , 72178 ,81565 ,92173 ,102060 ,110726 ,127700 ,141398 ,156563 ,169860 ,184283 ,199933 ,212537 ,\n # 225934 ,245121 ,260573 ,276998 ,326042 ,391670 ,531696 ,588724 ,1385457 ,1503111 ,1597864 ,1681372 ,\n # 1787361 ,1842836 ,1959004 ,2125366 ,2213771 ,2329467 ,2553169 ,2827011 ,3006219 ,3260426 ,3837698)\n #cdfIntervals <- c(0.0 ,0.0204 ,0.0409 ,0.0539 ,0.1803 ,0.2770 ,0.3048 ,0.3178 ,0.3532 ,0.3643 ,0.3773 ,\n # 0.3996 ,0.4052 ,0.4126 ,0.4238 ,0.4368 ,0.4461 ,0.4535 ,0.4572 ,0.4610 ,0.4665 ,0.4703 ,0.4758 ,0.4777 ,\n # 0.4833 ,0.4870 ,0.4888 ,0.4944 ,0.5000 ,0.5037 ,0.5091 ,0.5186 ,0.5223 ,0.5260 ,0.5297 ,0.5335 ,0.5390 ,\n # 0.5465 ,0.5558 ,0.5651 ,0.5743 ,0.5836 ,0.5923 ,0.6022 ,0.6115 ,0.6208 ,0.6301 ,0.6394 ,0.6580 ,0.6766 ,\n # 0.6952 ,0.7138 ,0.7200 ,0.7230 ,0.7416 ,0.7602 ,0.7787 ,0.7974 ,0.8160 ,0.8346 ,0.8532 ,0.8717 ,0.9276 ,\n # 0.9740 ,0.9888 ,0.9944 ,1.0)\n\n cdfRanges <- cdfIntervals[2:length(cdfIntervals)]\n cdfConsts <- cdfIntervals[1:length(cdfIntervals)-1]\n\n #create cdf sample vector and find the corresponding sizes.\n #cdf sample vector must be sorted: cdf <- seq(0.001, 1, 0.001)\n cdf <- c()\n for (ind in seq(1, length(cdfRanges)))\n {\n cdf <- c(cdf, seq(cdfIntervals[ind], cdfIntervals[ind+1], (cdfIntervals[ind+1] - cdfIntervals[ind])/5))\n }\n cdf <- sort(unique(cdf))\n\n\n #Corresponding sizes for cdf values\n sizes <- c()\n for (cdfVal in cdf)\n {\n ind <- match(1, findInterval(cdfRanges, cdfVal))\n logMsgSize <- (cdfVal - cdfConsts[ind]) *\n (log10(sizeIntervals[ind+1])-log10(sizeIntervals[ind])) /\n (cdfRanges[ind]-cdfConsts[ind]) + log10(sizeIntervals[ind])\n sizes <- c(sizes, 10**(logMsgSize))\n }\n\n # round the sizes to integers and remove possible duplicates that rounding might\n # have caused.\n sizes <- round(sizes)\n unik <- !duplicated(sizes) #logical vector of unique values\n ind <- seq_along(sizes)[unik] #indices of unique values\n cdf <- cdf[ind]\n sizes <- sizes[ind]\n pdf <- cdf - c(0, cdf[1:length(cdf)-1])\n avgSize <- sum(pdf*sizes)\n\n filename = \"Facebook_HadoopDist_All.txt\"\n write(avgSize, file=filename)\n df <- data.frame(sizes, cdf)\n write.table(df, file=filename, row.names=FALSE, col.names=FALSE, append=TRUE)\n}\n\ncdfFromLogScaledCbf()\n", "meta": {"hexsha": "8d82a9c2de828fb6bc9ebd1ce59c91ba63fbbaad", "size": 8043, "ext": "r", "lang": "R", "max_stars_repo_path": "data/traffic/others/cdfFabricator.r", "max_stars_repo_name": "guiladkatz/NetAction", "max_stars_repo_head_hexsha": "436c5ac9dcf0e2064bcc9a2facca556828de6703", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2021-08-20T08:10:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:24:50.000Z", "max_issues_repo_path": "homatransport/sizeDistributions/cdfFabricator.r", "max_issues_repo_name": "googleinterns/vectio", "max_issues_repo_head_hexsha": "0d8ef1d504c821de733110c82b16b2ae43332c5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-06T15:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T21:56:36.000Z", "max_forks_repo_path": "data/traffic/others/cdfFabricator.r", "max_forks_repo_name": "guiladkatz/NetAction", "max_forks_repo_head_hexsha": "436c5ac9dcf0e2064bcc9a2facca556828de6703", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-20T08:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T06:15:02.000Z", "avg_line_length": 48.1616766467, "max_line_length": 177, "alphanum_fraction": 0.6391893572, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47660653528167796}} {"text": "\\name{extreme_deconvolution}\n\\alias{extreme_deconvolution}\n\n\\title{Density estimation using Gaussian mixtures in the presence of\n noisy, heterogeneous and incomplete data}\n\n\\description{We present a general algorithm to infer a d-dimensional\ndistribution function given a set of heterogeneous, noisy observations\nor samples. This algorithm reconstructs the error-deconvolved or\n'underlying' distribution function common to all samples, even when the\nindividual samples have unique error and missing-data properties. The\nunderlying distribution is modeled as a mixture of Gaussians, which is\ncompletely general. Model parameters are chosen to optimize a justified,\nscalar objective function: the logarithm of the probability of the data\nunder the error-convolved model, where the error convolution is\ndifferent for each data point. Optimization is performed by an\nExpectation Maximization (EM) algorithm, extended by a regularization\ntechnique and 'split-and-merge' procedure. These extensions mitigate\nproblems with singularities and local maxima, which are often\nencountered when using the EM algorithm to estimate Gaussian density\nmixtures.}\n\n\\usage{\nextreme_deconvolution(ydata,ycovar,xamp,xmean,xcovar,\n projection=NULL,weight=NULL,\n fixamp=NULL,fixmean=NULL,fixcovar=NULL,\n tol=1.e-6,maxiter=1e9,w=0,logfile=NULL,\n splitnmerge=0,maxsnm=FALSE,likeonly=FALSE,\n logweight=FALSE)\n}\n\n\\arguments{\n \\item{ydata}{[ndata,dy] matrix of observed quantities}\n \\item{ycovar}{[ndata,dy] / [ndata,dy,dy] / [dy,dy,ndata] matrix, list or 3D array\n of observational error covariances\n (if [ndata,dy] then the error correlations are assumed to vanish)}\n \\item{xamp}{[ngauss] array of initial amplitudes (*not* [1,ngauss])}\n \\item{xmean}{[ngauss,dx] matrix of initial means}\n \\item{xcovar}{[ngauss,dx,dx] list of matrices of initial covariances}\n \\item{projection}{[ndata,dy,dx] list of projection matrices}\n \\item{weight}{[ndata] array of weights to be applied to the data points}\n \\item{logweight}{(bool, default=False) if True, weight is actually\n log(weight)}\n \\item{fixamp}{(default=None) None, True/False, or list of bools}\n \\item{fixmean}{(default=None) None, True/False, or list of bools}\n \\item{fixcovar}{(default=None) None, True/False, or list of bools}\n \\item{tol}{(double, default=1.e-6) tolerance for convergence}\n \\item{maxiter}{(long, default= 10**9) maximum number of iterations to perform}\n \\item{w}{(double, default=0.) covariance regularization parameter\n (of the conjugate prior)}\n \\item{logfile}{basename for several logfiles (_c.log has output from\n the c-routine; _loglike.log has the log likelihood path of\n all the accepted routes, i.e. only parts which increase\n the likelihood are included, during splitnmerge)}\n \\item{splitnmerge}{(int, default=0) depth to go down the splitnmerge path}\n \\item{maxsnm}{(Bool, default=False) use the maximum number of split 'n'\n merge steps, K*(K-1)*(K-2)/2}\n \\item{likeonly}{(Bool, default=False) only compute the total log\n likelihood of the data}\n}\n\n\\value{\n \\item{avgloglikedata}{avgloglikedata after convergence}\n \\item{xamp}{updated xamp}\n \\item{xmean}{updated xmean}\n \\item{xcovar}{updated xcovar}\n}\n\n\\details{\n ...\n}\n\n\\author{Jo Bovy, David W. Hogg, & Sam T. Roweis}\n\n\\references{\nInferring complete distribution functions from\nnoisy, heterogeneous and incomplete observations Jo Bovy, David\nW. Hogg, & Sam T. Roweis, Submitted to AOAS (2009) [arXiv/0905.2979]\n}\n\n\\examples{\nlibrary(ExtremeDeconvolution)\n\nydata <-\nc(2.62434536, 0.38824359, 0.47182825, -0.07296862, 1.86540763,\n-1.30153870, 2.74481176, 0.23879310, 1.31903910, 0.75062962,\n2.46210794, -1.06014071, 0.67758280, 0.61594565, 2.13376944,\n-0.09989127, 0.82757179, 0.12214158, 1.04221375, 1.58281521,\n-0.10061918, 2.14472371, 1.90159072, 1.50249434, 1.90085595,\n0.31627214, 0.87710977, 0.06423057, 0.73211192, 1.53035547,\n0.30833925, 0.60324647, 0.31282730, 0.15479436, 0.32875387,\n0.98733540, -0.11731035, 1.23441570, 2.65980218, 1.74204416,\n0.80816445, 0.11237104, 0.25284171, 2.69245460, 1.05080775,\n0.36300435, 1.19091548, 3.10025514, 1.12015895, 1.61720311,\n1.30017032, 0.64775015, -0.14251820, 0.65065728, 0.79110577,\n1.58662319, 1.83898341, 1.93110208, 1.28558733, 1.88514116,\n0.24560206, 2.25286816, 1.51292982, 0.70190717, 1.48851815,\n0.92442829, 2.13162939, 2.51981682, 3.18557541, -0.39649633,\n-0.44411380, 0.49553414, 1.16003707, 1.87616892, 1.31563495,\n-1.02220122, 0.69379599, 1.82797464, 1.23009474, 1.76201118,\n0.77767186, 0.79924193, 1.18656139, 1.41005165, 1.19829972,\n1.11900865, 0.32933771, 1.37756379, 1.12182127, 2.12948391,\n2.19891788, 1.18515642, 0.62471505, 0.36126959, 1.42349435,\n1.07734007, 0.65614632, 1.04359686, 0.37999916, 1.69803203,\n0.55287144, 2.22450770, 1.40349164, 1.59357852, -0.09491185,\n1.16938243, 1.74055645, 0.04629940, 0.73378149, 1.03261455,\n-0.37311732, 1.31515939, 1.84616065, 0.14048406, 1.35054598,\n-0.31228341, 0.96130449, -0.61577236, 2.12141771, 1.40890054,\n0.97538304, 0.22483838, 2.27375593, 2.96710175, -0.85798186,\n2.23616403, 2.62765075, 1.33801170, -0.19926803, 1.86334532,\n0.81907970, 0.39607937, -0.23005814, 1.55053750, 1.79280687,\n0.37646927, 1.52057634, -0.14434139, 1.80186103, 1.04656730,\n0.81343023, 0.89825413, 1.86888616, 1.75041164, 1.52946532,\n1.13770121, 1.07782113, 1.61838026, 1.23249456, 1.68255141,\n0.68988323, -1.43483776, 2.03882460, 3.18697965, 1.44136444,\n0.89984477, 0.86355526, 0.88094581, 1.01740941, -0.12201873,\n0.48290554, 0.00297317, 1.24879916, 0.70335885, 1.49521132,\n0.82529684, 1.98633519, 1.21353390, 3.19069973, -0.89636092,\n0.35308331, 1.90148689, 3.52832571, 0.75136522, 1.04366899,\n0.77368576, 2.33145711, 0.71269214, 1.68006984, 0.68019840,\n-0.27255875, 1.31354772, 1.50318481, 2.29322588, 0.88955297,\n0.38263794, 1.56276110, 1.24073709, 1.28066508, 0.92688730,\n2.16033857, 1.36949272, 2.90465871, 2.11105670, 1.65904980,\n-0.62743834, 1.60231928, 1.42028220, 1.81095167, 2.04444209)\n\nydata <- matrix(ydata,length(ydata),1)\nN <- dim(ydata)[1]\nycovar <- ydata*0 + 0.01\nxamp <- c(0.5,0.5)\nxmean <- matrix(c(0.86447943, 0.67078879, 0.322681, 0.45087394),2,2)\nxcovar <-\n list(matrix(c(0.03821028, 0.04014796, 0.04108113, 0.03173839),2,2),\n matrix(c(0.06219194, 0.09738021, 0.04302473, 0.06778009),2,2))\nprojection <- list()\nfor (i in 1:N)\n projection[[i]] = matrix(c(i\\%\\%2,(i+1)\\%\\%2),1,2)\nres <- extreme_deconvolution(ydata, ycovar, xamp, xmean, xcovar,\n projection=projection, logfile=\"ExDeconDemo\")\nprint(res)\nstopifnot((res$avgloglikedata - (-1.3114744655258121)) **2. < 10.**-8)\nstopifnot((res$xmean[1,1]-2.30368235)**2. < 10.**-5)\nstopifnot((res$xmean[1,2]-1.70701517)**2. < 10.**-5)\nstopifnot((res$xmean[2,1]-1.08009397)**2. < 10.**-5)\nstopifnot((res$xmean[2,2]-0.8888667)**2. < 10.**-5)\nstopifnot((res$xcovar[[1]][1,1]-0.445645987259)**2. < 10.**-5.)\nstopifnot((res$xamp[1]-0.11968415)**2. < 10.**-5)\nstopifnot((res$xamp[2]-0.880315852981)**2. < 10.**-5)\n}\n", "meta": {"hexsha": "3e3b5b6a528a5f461b69d1f8ac00c11029ed3d79", "size": 7143, "ext": "rd", "lang": "R", "max_stars_repo_path": "r/man/extreme_deconvolution.rd", "max_stars_repo_name": "philastrophist/extreme-deconvolution", "max_stars_repo_head_hexsha": "b0450717c0faeda8b9cd9f0567755989b3be5c5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_issues_repo_path": "r/man/extreme_deconvolution.rd", "max_issues_repo_name": "philastrophist/extreme-deconvolution", "max_issues_repo_head_hexsha": "b0450717c0faeda8b9cd9f0567755989b3be5c5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_forks_repo_path": "r/man/extreme_deconvolution.rd", "max_forks_repo_name": "philastrophist/extreme-deconvolution", "max_forks_repo_head_hexsha": "b0450717c0faeda8b9cd9f0567755989b3be5c5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "avg_line_length": 47.9395973154, "max_line_length": 83, "alphanum_fraction": 0.7155256895, "num_tokens": 2812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47643683268438014}} {"text": "LISP Interpreter Run\n\n[[[[[\n\n Show that a formal axiomatic system (fas) can only prove \n that finitely many LISP expressions are elegant. \n (An expression is elegant if no smaller expression has \n the same value.)\n\n More precisely, show that a fas of LISP complexity N can't \n prove that a LISP expression X is elegant if X's size is \n greater than N + 356.\n\n (fas N) returns the theorem proved by the Nth proof \n (Nth S-expression) in the fas, or nil if the proof is \n invalid, or stop to stop everything.\n\n]]]]]\n\n[\n This expression searches for an elegant expression \n that is larger than it is and returns the value of \n that expression as its own value.\n]\n\ndefine expression [Formal Axiomatic System #1]\n let (fas n) if = n 1 '(is-elegant x)\n if = n 2 nil\n if = n 3 '(is-elegant yyy)\n [else] stop \n\n let (loop n)\n let theorem [be] display (fas n)\n if = nil theorem [then] (loop + n 1)\n if = stop theorem [then] fas-has-stopped\n if = is-elegant car theorem\n if > display size cadr theorem \n display + 356 size fas\n [return] eval cadr theorem\n [else] (loop + n 1)\n [else] (loop + n 1)\n\n (loop 1)\n\ndefine expression\nvalue ((' (lambda (fas) ((' (lambda (loop) (loop 1))) ('\n (lambda (n) ((' (lambda (theorem) (if (= nil theo\n rem) (loop (+ n 1)) (if (= stop theorem) fas-has-s\n topped (if (= is-elegant (car theorem)) (if (> (di\n splay (size (car (cdr theorem)))) (display (+ 356 \n (size fas)))) (eval (car (cdr theorem))) (loop (+ \n n 1))) (loop (+ n 1))))))) (display (fas n))))))))\n (' (lambda (n) (if (= n 1) (' (is-elegant x)) (if\n (= n 2) nil (if (= n 3) (' (is-elegant yyy)) stop\n ))))))\n\n\n[Show that this expression knows its own size.]\n\nsize expression\n\nexpression (size expression)\nvalue 456\n\n \n[\n Run #1.\n\n Here it doesn't find an elegant expression \n larger than it is:\n]\n\neval expression\n\nexpression (eval expression)\ndisplay (is-elegant x)\ndisplay 1\ndisplay 456\ndisplay ()\ndisplay (is-elegant yyy)\ndisplay 3\ndisplay 456\ndisplay stop\nvalue fas-has-stopped\n\n\ndefine expression [Formal Axiomatic System #2]\n let (fas n) if = n 1 '(is-elegant x)\n if = n 2 nil\n if = n 3 '(is-elegant yyy)\n if = n 4 cons is-elegant \n cons ^ 10 509 [<=====]\n nil\n [else] stop \n\n let (loop n)\n let theorem [be] display (fas n)\n if = nil theorem [then] (loop + n 1)\n if = stop theorem [then] fas-has-stopped\n if = is-elegant car theorem\n if > display size cadr theorem \n display + 356 size fas\n [return] eval cadr theorem\n [else] (loop + n 1)\n [else] (loop + n 1)\n\n (loop 1)\n\ndefine expression\nvalue ((' (lambda (fas) ((' (lambda (loop) (loop 1))) ('\n (lambda (n) ((' (lambda (theorem) (if (= nil theo\n rem) (loop (+ n 1)) (if (= stop theorem) fas-has-s\n topped (if (= is-elegant (car theorem)) (if (> (di\n splay (size (car (cdr theorem)))) (display (+ 356 \n (size fas)))) (eval (car (cdr theorem))) (loop (+ \n n 1))) (loop (+ n 1))))))) (display (fas n))))))))\n (' (lambda (n) (if (= n 1) (' (is-elegant x)) (if\n (= n 2) nil (if (= n 3) (' (is-elegant yyy)) (if \n (= n 4) (cons is-elegant (cons (^ 10 509) nil)) st\n op)))))))\n\n\n[Show that this expression knows its own size.]\n\nsize expression\n\nexpression (size expression)\nvalue 509\n\n\n[\n Run #2.\n\n Here it finds an elegant expression \n exactly one character larger than it is: \n]\n\neval expression\n\nexpression (eval expression)\ndisplay (is-elegant x)\ndisplay 1\ndisplay 509\ndisplay ()\ndisplay (is-elegant yyy)\ndisplay 3\ndisplay 509\ndisplay (is-elegant 10000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 0000000000000000000000)\ndisplay 510\ndisplay 509\nvalue 10000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 0000000000\n\n\ndefine expression [Formal Axiomatic System #3]\n let (fas n) if = n 1 '(is-elegant x)\n if = n 2 nil\n if = n 3 '(is-elegant yyy)\n if = n 4 cons is-elegant \n cons ^ 10 508 [<=====]\n nil\n [else] stop \n\n let (loop n)\n let theorem [be] display (fas n)\n if = nil theorem [then] (loop + n 1)\n if = stop theorem [then] fas-has-stopped\n if = is-elegant car theorem\n if > display size cadr theorem \n display + 356 size fas\n [return] eval cadr theorem\n [else] (loop + n 1)\n [else] (loop + n 1)\n\n (loop 1)\n\ndefine expression\nvalue ((' (lambda (fas) ((' (lambda (loop) (loop 1))) ('\n (lambda (n) ((' (lambda (theorem) (if (= nil theo\n rem) (loop (+ n 1)) (if (= stop theorem) fas-has-s\n topped (if (= is-elegant (car theorem)) (if (> (di\n splay (size (car (cdr theorem)))) (display (+ 356 \n (size fas)))) (eval (car (cdr theorem))) (loop (+ \n n 1))) (loop (+ n 1))))))) (display (fas n))))))))\n (' (lambda (n) (if (= n 1) (' (is-elegant x)) (if\n (= n 2) nil (if (= n 3) (' (is-elegant yyy)) (if \n (= n 4) (cons is-elegant (cons (^ 10 508) nil)) st\n op)))))))\n\n\n[Show that this expression knows its own size.]\n\nsize expression\n\nexpression (size expression)\nvalue 509\n\n\n[\n Run #3.\n\n Here it finds an elegant expression \n exactly the same size as it is: \n]\n\neval expression\n\nexpression (eval expression)\ndisplay (is-elegant x)\ndisplay 1\ndisplay 509\ndisplay ()\ndisplay (is-elegant yyy)\ndisplay 3\ndisplay 509\ndisplay (is-elegant 10000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 000000000000000000000)\ndisplay 509\ndisplay 509\ndisplay stop\nvalue fas-has-stopped\n\n\ndefine expression [Formal Axiomatic System #4]\n let (fas n) if = n 1 '(is-elegant x)\n if = n 2 nil\n if = n 3 '(is-elegant yyy)\n if = n 4 cons is-elegant \n cons cons \"- \n cons ^ 10 600 [<=====]\n cons 1 \n nil \n nil\n [else] stop \n\n let (loop n)\n let theorem [be] display (fas n)\n if = nil theorem [then] (loop + n 1)\n if = stop theorem [then] fas-has-stopped\n if = is-elegant car theorem\n if > display size cadr theorem \n display + 356 size fas\n [return] eval cadr theorem\n [else] (loop + n 1)\n [else] (loop + n 1)\n\n (loop 1)\n\ndefine expression\nvalue ((' (lambda (fas) ((' (lambda (loop) (loop 1))) ('\n (lambda (n) ((' (lambda (theorem) (if (= nil theo\n rem) (loop (+ n 1)) (if (= stop theorem) fas-has-s\n topped (if (= is-elegant (car theorem)) (if (> (di\n splay (size (car (cdr theorem)))) (display (+ 356 \n (size fas)))) (eval (car (cdr theorem))) (loop (+ \n n 1))) (loop (+ n 1))))))) (display (fas n))))))))\n (' (lambda (n) (if (= n 1) (' (is-elegant x)) (if\n (= n 2) nil (if (= n 3) (' (is-elegant yyy)) (if \n (= n 4) (cons is-elegant (cons (cons - (cons (^ 10\n 600) (cons 1 nil))) nil)) stop)))))))\n\n\n[Show that this expression knows its own size.]\n\nsize expression\n\nexpression (size expression)\nvalue 538\n\n\n[\n Run #4.\n\n Here it finds an elegant expression \n much larger than it is, and evaluates it: \n]\n\neval expression\n\nexpression (eval expression)\ndisplay (is-elegant x)\ndisplay 1\ndisplay 538\ndisplay ()\ndisplay (is-elegant yyy)\ndisplay 3\ndisplay 538\ndisplay (is-elegant (- 10000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 00000000000000000000000000000000000000000000000000\n 0000000000000000 1))\ndisplay 607\ndisplay 538\nvalue 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n 99999999999999999999999999999999999999999999999999\n\nEnd of LISP Run\n\nElapsed time is 0 seconds.\n", "meta": {"hexsha": "eabb03e60b318712e0f20ff0e9fa784f5103d1ab", "size": 11682, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/chaitin.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/chaitin.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/chaitin.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 33.6657060519, "max_line_length": 62, "alphanum_fraction": 0.5857729841, "num_tokens": 3322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4764368262830333}} {"text": "#######################################################################################################\n# Parameter estimation using R's optim function\n# Minimal error checking is done. You should run is.marssMLE() before calling this.\n# Q and R are not allowed to be time-varying\n# Likelihood computation is via Kalman filter\n#######################################################################################################\nMARSSoptim <- function(MLEobj) {\n # This function does not check if user specified a legal MLE object.\n ##\n # Define needed negLogLik function with chol transformed variances\n #\n neglogLik <- function(x, MLEobj = NULL) { # NULL assignment needed for optim call syntax\n # MLEobj is tmp.MLEobj so has altered free and fixed\n # x is the paramvector\n\n # update the MLEobj by putting the estimated pars from optim in\n MLEobj <- MARSSvectorizeparam(MLEobj, x)\n free <- MLEobj$marss$free\n pars <- MLEobj$par\n par.dims <- attr(MLEobj[[\"marss\"]], \"model.dims\")\n for (elem in c(\"Q\", \"R\", \"V0\")) {\n if (!is.fixed(free[[elem]])) # recompute par if needed since par in parlist is transformed\n {\n d <- sub3D(free[[elem]], t = 1) # this will be the one with the upper tri zero-ed out\n par.dim <- par.dims[[elem]][1:2]\n # t=1 since D not allowed to be time-varying; since code 4 lines down won't work otherwise\n L <- unvec(d %*% pars[[elem]], dim = par.dim) # this by def will have 0 row/col at the fixed values\n the.par <- tcrossprod(L) # L%*%t(L)\n # from f+Dm=M and if f!=0, D==0 so can leave off f\n MLEobj$par[[elem]] <- solve(crossprod(d)) %*% t(d) %*% vec(the.par)\n # solve(t(d)%*%d)%*%t(d)%*%vec(the.par)\n }\n } # end for over elem\n # This function is passed a special MLEobj with a marss.original element\n MLEobj$marss$fixed <- MLEobj$fixed.original\n MLEobj$marss$free <- MLEobj$free.original\n\n # kfsel selects the Kalman filter / smoother function based on MLEobj$fun.kf\n negLL <- MARSSkf(MLEobj, only.logLik = TRUE, return.lag.one = FALSE)$logLik\n\n -1 * negLL\n }\n\n if (!inherits(MLEobj, \"marssMLE\")) {\n stop(\"Stopped in MARSSoptim(). Object of class marssMLE is required.\\n\", call. = FALSE)\n }\n for (elem in c(\"Q\", \"R\")) {\n if (dim(MLEobj$model$free[[elem]])[3] > 1) {\n stop(paste(\"Stopped in MARSSoptim() because this function does not allow estimated part of \", elem, \" to be time-varying.\\n\", sep = \"\"), call. = FALSE)\n }\n }\n # the is.marssMODEL call is.validvarcov() which tests that the blocks are diagonal or unconstrained in the varcov matrices\n\n ## attach would be risky here since user might have one of these variables in their workspace\n MODELobj <- MLEobj[[\"marss\"]]\n y <- MODELobj$data # must have time going across columns\n free <- MODELobj$free\n fixed <- MODELobj$fixed\n tmp.inits <- MLEobj$start\n control <- MLEobj$control\n par.dims <- attr(MODELobj, \"model.dims\")\n m <- par.dims[[\"x\"]][1]\n n <- par.dims[[\"y\"]][1]\n\n ## Set up the control list for optim; only pass in optim control elements\n control.names <- c(\"trace\", \"fnscale\", \"parscale\", \"ndeps\", \"maxit\", \"abstol\", \"reltol\", \"alpha\", \"beta\", \"gamma\", \"REPORT\", \"type\", \"lmm\", \"factr\", \"pgtol\", \"temp\", \"tmax\")\n optim.control <- list()\n for (elem in control.names) {\n if (!is.null(control[[elem]])) optim.control[[elem]] <- control[[elem]]\n }\n if (is.null(control[[\"lower\"]])) {\n lower <- -Inf\n } else {\n lower <- control[[\"lower\"]]\n }\n if (is.null(control[[\"upper\"]])) {\n upper <- Inf\n } else {\n upper <- control$upper\n }\n if (control$trace == -1) optim.control$trace <- 0\n\n # The code is used to set things up to use MARSSvectorizeparam to just select inits for the estimated parameters\n # Q=t(chol(Q)%*%chol(Q)); t(chol(Q)) has 0 in upper triangle\n tmp.MLEobj <- MLEobj\n # This is needed for the likelihood calculation\n tmp.MLEobj$fixed.original <- tmp.MLEobj$marss$fixed\n tmp.MLEobj$free.original <- tmp.MLEobj$marss$free\n\n tmp.MLEobj$par <- tmp.inits # set initial conditions for estimated parameters\n for (elem in c(\"Q\", \"R\", \"V0\")) { # need the chol for these\n d <- sub3D(free[[elem]], t = 1) # free[[elem]] is required to be time constant\n f <- sub3D(fixed[[elem]], t = 1) # placeholder. Need structure not actual values\n the.par <- unvec(f + d %*% tmp.inits[[elem]], dim = par.dims[[elem]][1:2])\n is.zero <- diag(the.par) == 0 # where the 0s on diagonal are\n if (any(is.zero)) diag(the.par)[is.zero] <- 1 # so the chol doesn't fail if there are zeros on the diagonal\n the.par <- t(chol(the.par)) # convert to transpose of chol\n if (any(is.zero)) diag(the.par)[is.zero] <- 0 # set back to 0\n if (!is.fixed(free[[elem]])) {\n # from f+Dm=M so m = solve(crossprod(d))%*%t(d)%*%(vec(the.par)-f)\n # but if d!=0,then f==0. if f!-0, then d==0.\n # Thus crossprod(d))%*%t(d) has 0 cols where fs appear in the.par and f is not needed\n tmp.MLEobj$par[[elem]] <- solve(crossprod(d)) %*% t(d) %*% vec(the.par)\n } else {\n tmp.MLEobj$par[[elem]] <- matrix(0, 0, 1)\n }\n # when being passed to optim, pars for var-cov mat is the chol, so need to reset free so we can get the L=t(chol) matrix\n # we don't need to reset fixed because it won't be used;\n # step 1, compute the D matrix corresponding to upper.tri=0 in t(chol)\n # note this only works because it is required that\n # a) if f!=0, d=0. so 1+a never appears in var-cov mat b) a+b never appears in a var-cov mat, c) for BFGS, var-cov mat is time-invariant\n tmp.list.mat <- fixed.free.to.formula(f, d, par.dims[[elem]][1:2])\n tmp.list.mat[upper.tri(tmp.list.mat)] <- 0 # set upper tri to zero\n tmp.MLEobj$marss$free[[elem]] <- convert.model.mat(tmp.list.mat)$free\n }\n # will return the inits only for the estimated parameters\n pars <- MARSSvectorizeparam(tmp.MLEobj)\n\n if (substr(tmp.MLEobj$method, 1, 4) == \"BFGS\") {\n optim.method <- \"BFGS\"\n } else {\n optim.method <- \"something wrong\"\n }\n\n kf.function <- MLEobj$fun.kf # used for printing\n optim.output <- try(optim(pars, neglogLik, MLEobj = tmp.MLEobj, method = optim.method, lower = lower, upper = upper, control = optim.control, hessian = FALSE), silent = TRUE)\n\n if (inherits(optim.output, \"try-error\")) { # try MARSSkfss if the user did not use it\n if (MLEobj$fun.kf != \"MARSSkfss\") { # if user did not request MARSSkf\n cat(\"MARSSkfas returned error. Trying MARSSkfss.\\n\")\n tmp.MLEobj$fun.kf <- \"MARSSkfss\"\n kf.function <- \"MARSSkfss\" # used for printing\n optim.output <- try(optim(pars, neglogLik, MLEobj = tmp.MLEobj, method = optim.method, lower = lower, upper = upper, control = optim.control, hessian = FALSE), silent = TRUE)\n }\n }\n\n # error returned\n if (inherits(optim.output, \"try-error\")) {\n optim.output <- list(convergence = 53, message = c(\"MARSSkfas and MARSSkfss tried to compute log likelihood and encountered numerical problems.\\n\", sep = \"\"))\n }\n\n\n MLEobj.return <- MLEobj\n MLEobj.return$iter.record <- optim.output$message\n # MLEobj.return$control=MLEobj$control\n # MLEobj.return$model=MLEobj$model\n MLEobj.return$start <- tmp.inits # set to what was used here\n MLEobj.return$convergence <- optim.output$convergence\n if (optim.output$convergence %in% c(1, 0)) {\n if ((!control$silent || control$silent == 2) && optim.output$convergence == 0) cat(paste(\"Success! Converged in \", optim.output$counts[1], \" iterations.\\n\", \"Function \", kf.function, \" used for likelihood calculation.\\n\", sep = \"\"))\n if ((!control$silent || control$silent == 2) && optim.output$convergence == 1) cat(paste(\"Warning! Max iterations of \", control$maxit, \" reached before convergence.\\n\", \"Function \", kf.function, \" used for likelihood calculation.\\n\", sep = \"\"))\n\n tmp.MLEobj <- MARSSvectorizeparam(tmp.MLEobj, optim.output$par)\n # par has the fixed and estimated values using t chol of Q and R\n\n # back transform Q, R and V0 if needed from chol form to usual form\n for (elem in c(\"Q\", \"R\", \"V0\")) { # this works because by def fixed and free blocks of var-cov mats are independent\n if (!is.fixed(MODELobj$free[[elem]])) # get a new par if needed\n {\n d <- sub3D(tmp.MLEobj$marss$free[[elem]], t = 1) # this will be the one with the upper tri zero-ed out but ok since symmetric\n par.dim <- par.dims[[elem]][1:2]\n L <- unvec(tmp.MLEobj$marss$free[[elem]][, , 1] %*% tmp.MLEobj$par[[elem]], dim = par.dim) # this by def will have 0 row/col at the fixed values\n the.par <- tcrossprod(L) # L%*%t(L)\n tmp.MLEobj$par[[elem]] <- solve(crossprod(d)) %*% t(d) %*% vec(the.par)\n }\n } # end for\n\n pars <- MARSSvectorizeparam(tmp.MLEobj) # now the pars values have been adjusted back to normal scaling\n # now put the estimated values back into the original MLEobj; fixed and free matrices as in original\n MLEobj.return <- MARSSvectorizeparam(MLEobj.return, pars)\n kf.out <- try(MARSSkf(MLEobj.return), silent = TRUE)\n\n if (inherits(kf.out, \"try-error\")) {\n MLEobj.return$numIter <- optim.output$counts[1]\n MLEobj.return$logLik <- -1 * optim.output$value\n MLEobj.return$errors <- c(paste0(\"\\nWARNING: optim() successfully fit the model but \", kf.function, \" returned an error with the fitted model. Try MARSSinfo('optimerror54') for insight.\", sep = \"\"), \"\\nError: \", kf.out[1])\n MLEobj.return$convergence <- 54\n MLEobj.return <- MARSSaic(MLEobj.return)\n kf.out <- NULL\n }\n } else {\n if (optim.output$convergence == 10) optim.output$message <- c(\"degeneracy of the Nelder-Mead simplex\\n\", paste(\"Function \", kf.function, \" used for likelihood calculation.\\n\", sep = \"\"), optim.output$message)\n optim.output$counts <- NULL\n if (!control$silent) cat(\"MARSSoptim() stopped with errors. No parameter estimates returned.\\n\")\n if (control$silent == 2) cat(\"MARSSoptim() stopped with errors. No parameter estimates returned. See $errors in output for details.\\n\")\n\n MLEobj.return$par <- NULL\n MLEobj.return$errors <- optim.output$message\n kf.out <- NULL\n }\n\n if (!is.null(kf.out)) {\n if (control$trace > 0) MLEobj.return$kf <- kf.out\n MLEobj.return$states <- kf.out$xtT\n MLEobj.return$numIter <- optim.output$counts[1]\n MLEobj.return$logLik <- kf.out$logLik\n }\n MLEobj.return$method <- MLEobj$method\n\n ## Add AIC and AICc to the object\n if (!is.null(kf.out)) MLEobj.return <- MARSSaic(MLEobj.return)\n\n return(MLEobj.return)\n}\n", "meta": {"hexsha": "61a21140c932f2f463f4b3136f88eab78ca1fe47", "size": 10530, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MARSSoptim.r", "max_stars_repo_name": "ashaffer/MARSS", "max_stars_repo_head_hexsha": "62c874483d58a4ffeb354888b606e4d3cf355838", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2018-03-07T11:58:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T22:19:40.000Z", "max_issues_repo_path": "R/MARSSoptim.r", "max_issues_repo_name": "ashaffer/MARSS", "max_issues_repo_head_hexsha": "62c874483d58a4ffeb354888b606e4d3cf355838", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 126, "max_issues_repo_issues_event_min_datetime": "2018-03-15T16:05:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T02:25:30.000Z", "max_forks_repo_path": "R/MARSSoptim.r", "max_forks_repo_name": "ashaffer/MARSS", "max_forks_repo_head_hexsha": "62c874483d58a4ffeb354888b606e4d3cf355838", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2018-04-14T06:01:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T07:48:53.000Z", "avg_line_length": 51.3658536585, "max_line_length": 248, "alphanum_fraction": 0.6377018044, "num_tokens": 3124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4755442978577455}} {"text": "#' brms model for estimating variant transmissibility\n#' \n#' @description Fit an additive mixture of a baseline and variant reproduction\n#' number (Rt) to estimated non-parametric Rt values. The variant Rt is\n#' described by a multiplication of the baseline Rt. The baseline Rt is\n#' described by any covariate combination supported by `brms`. \n#' \n#' Uncertainty is included in the observed Rt estimates by assuming that they\n#' have student T distribution with standard deviation derived as a combination\n#' of a modelled estimate and the observed standard error of the estimates.\n#' Uncertainty is also included by modelling variant samples (`positive_prop`) as a\n#' latent variable informed by the number of overall samples available and the\n#' number of samples which are postive for the variant of interest.\n#' \n#' @param log_rt Formula describing the covariates predicting the log of the\n#' baseline variants time-varying reproduction number.\n#' @param data Data frame that must contain the responses: `rt_mean`,\n#' `rt_sd`, `positive_samples`, `samples` and a dummy variable `positive_prop` which \n#' is `NA_real`. If wanting to not model uncertainty in the variant proportion\n#' fill this variable with the point estimate of the proportion.\n#' @param brm_fn Function from `brms` to apply. Common options are\n#' `brm()` for model fitting,`get_prior()` to see the priors (not may not\n#' be accurate in all cases), and `make_stancode()` to see the generated\n#' stan code.\n#' @param ... Additional arguments to pass to `brm_fn`.\n#' @import brms\nvariant_rt <- function(log_rt = ~ 1, data, brm_fn = brm, ...) {\n\n # define Rt variant mixture\n rt_model <-\n bf(rt_mean | se(rt_sd, sigma = TRUE) ~ (1 + var) * exp(logRt),\n nl = TRUE) +\n lf(var ~ 0 + mi(positive_prop)) +\n lf(as.formula(paste0(\"logRt \", paste(log_rt, collapse = \" \")))) +\n student()\n\n # define samples observation model\n samples_obs_model <- bf(positive_samples | trials(samples) ~ 0 + mi(positive_prop)) +\n binomial(link = \"identity\")\n\n # define model for latent variant proportion\n variant_model <- bf(positive_prop | mi() ~ 1, family = \"beta\")\n\n # set weak priors\n # set positive proportion to be latent and observed directly with no modifier\n priors <- c(\n prior(student_t(3, 0, 0.5), nlpar = \"var\", resp = \"rtmean\"),\n prior(student_t(3, 0, 0.5), nlpar = \"logRt\", resp = \"rtmean\"),\n prior(constant(1), class = \"phi\", resp = \"positive_samples\"),\n prior(constant(1), class = \"Intercept\", resp = \"positive_samples\"),\n prior(constant(1), resp = \"positivesamples\")\n )\n\n# fit model\nbrm_out <- do.call(brm_fn, c(\n list(\n mvbf(samples_obs_model, variant_model, rt_model, rescor = FALSE),\n data = data,\n prior = priors),\n ...)\n)\n\nreturn(brm_out)\n}\n", "meta": {"hexsha": "c943a4203fb94e0401c2fa723e42962ed9620b14", "size": 2767, "ext": "r", "lang": "R", "max_stars_repo_path": "R/variant_rt.r", "max_stars_repo_name": "epiforecasts/covid19.sgene.utla.rt", "max_stars_repo_head_hexsha": "d1e05510729f0e0cf9ed8e84fb7c4eb309a06edc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-01-08T16:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T01:49:36.000Z", "max_issues_repo_path": "R/variant_rt.r", "max_issues_repo_name": "epiforecasts/covid19.sgene.utla.rt", "max_issues_repo_head_hexsha": "d1e05510729f0e0cf9ed8e84fb7c4eb309a06edc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-01-08T16:09:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T11:09:23.000Z", "max_forks_repo_path": "R/variant_rt.r", "max_forks_repo_name": "epiforecasts/covid19.sgene.utla.rt", "max_forks_repo_head_hexsha": "d1e05510729f0e0cf9ed8e84fb7c4eb309a06edc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-10T08:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T17:56:39.000Z", "avg_line_length": 42.5692307692, "max_line_length": 87, "alphanum_fraction": 0.7054571738, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4753897778574637}} {"text": "cat(\"insert number \")\na <- scan(nmax=1, quiet=TRUE)\ncat(\"insert number \")\nb <- scan(nmax=1, quiet=TRUE)\nprint(paste('a+b=', a+b))\nprint(paste('a-b=', a-b))\nprint(paste('a*b=', a*b))\nprint(paste('a%/%b=', a%/%b))\nprint(paste('a%%b=', a%%b))\nprint(paste('a^b=', a^b))\n", "meta": {"hexsha": "656028fc5a487261c06e850fad269fc526f8f802", "size": 266, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Arithmetic-Integer/R/arithmetic-integer.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Arithmetic-Integer/R/arithmetic-integer.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Arithmetic-Integer/R/arithmetic-integer.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 24.1818181818, "max_line_length": 29, "alphanum_fraction": 0.5714285714, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.47487223484486507}} {"text": "#' Create a bias-corrected distribution model\n#' \n#' This function implements a bayesLand model\n#' @param x SpatialPolygonsDataFrame\n#' @param effort Character, name of field in \\code{x} indicating collection effort.\n#' @param detect Character, name of field in \\code{x} indicating number of detections of focal species.\n#' @param stateProv Character, name of field with state/province.\n#' @param county Character, name of field with county.\n#' @param qGivenDetect Either \\code{NULL} (default) or logical. If \\code{TRUE} or \\code{FALSE} then the model will try to estimate the rate of false detection (mistaken positive identifications). If \\code{NULL}, then the model will not. If \\code{TRUE}, false detection rate \\emph{q} reflects the probability of all collections in a location being of mistaken identification. If \\code{FALSE} (default), then \\emph{q} reflects the probability that for a county where the species does not truly occur, similar species (which could be mistaken for the focal species) do occur (and may or may not have been sampled and mis-identified).\n#' @param covariate Either \\code{NULL} (default) or a character or character vector. If not \\code{NULL}, these are the name(s) field(s) with covariates.\n#' @param niter Positive integer, number of MCMC iterations (including burn-in). The default is 2000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nburnin Positive integer, number of burn-in samples (less than \\code{niter}). The default is 1000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nchains Positive integer, number of MCMC chains (default is 4).\n#' @param thin Positive integer, number of MCMC samples by which to thin the results (default is 1; i.e., no thinning). To reduce memory requirements, you can use \\code{thin} while increasing \\code{niter} and/or \\code{nburnin}.\n#' @param na.rm Logical, if \\code{TRUE} (default), then remove rows in \\code{x} that have \\code{NA} in any input field. If this is \\code{FALSE} and \\code{NA}s occur in any fields then an error may occur.\n#' @param verbose Logical, if \\code{TRUE} (default) display progress.\n#' @param ... Arguments to pass to \\code{\\link[nimble]{configureMCMC}} and \\code{\\link[nimble]{runMCMC}}.\n#' @return A list object with three elements, one with the MCMC chains, a second with the object \\code{x} with model output appended to the data portion of the object, and a third with model information. The new columns in \\code{x} represent:\n#' \\itemize{\n#' \t\t\\item{\\code{cvScale}} (only if \\code{covariate} is not \\code{NULL}): Value of centered and scaled covariate\n#' \t\t\\item{\\code{psi}} Probability of occurrence\n#' \t\t\\item{\\code{psi95CI}} 95% credibility interval for probability of occurrence\n#' \t\t\\item{\\code{p}} Probability of detecting the focal species assuming it is present\n#' \t\t\\item{\\code{p95CI}} 95% credibility interval for probability of detection\n#' }\n#' @examples\n#' @export\n\ntrainBayesODM <- function(\n\tx,\n\teffort,\n\tdetect,\n\tstateProv,\n\tcounty,\n\tqGivenDetect = NULL,\n\tcovariate = NULL,\n\tniter = 2000,\n\tnburnin = 1000,\n\tnchains = 4,\n\tthin = 1,\n\tna.rm=TRUE,\n\tverbose=TRUE,\n\t...\n) {\n\n\t### prepare data\n\t################\n\t\n\t\tif (verbose) omnibus::say('Preparing data...')\n\t\t\n\t\t# remove missings\n\t\tif (na.rm) {\n\t\t\tok <- complete.cases(x@data[ , c(effort, detect, stateProv, county, covariate)])\n\t\t\tx <- x[ok, ]\n\t\t}\n\t\t\t\n\t\t### CAR setup for counties\n\t\t##########################\n\t\t\n\t\t\tneighs <- spdep::poly2nb(x, queen=TRUE)\n\t\t\t\n\t\t\thasNeighs <- !sapply(neighs, function(x) { length(x == 1) && (x == 0) })\n\t\t\t\n\t\t\tneighsList <- spdep::nb2WB(neighs)\n\t\t\tcarAdjCounty <- neighsList$adj\n\t\t\tcarWeightCounty <- neighsList$weights\n\t\t\tcarNumCounty <- neighsList$num\n\n\t\t### inputs\n\t\t##########\n\t\t\n\t\t\t### data\n\t\t\tdata <- list(\n\t\t\t\ty = x@data[ , detect],\n\t\t\t\tN = x@data[ , effort],\n\t\t\t\tcarAdjCounty = carAdjCounty,\n\t\t\t\tcarWeightCounty = carWeightCounty,\n\t\t\t\tcarNumCounty = carNumCounty\n\t\t\t)\n\t\t\t\n\t\t\t# add covariates\n\t\t\tif (!is.null(covariate)) {\n\t\t\t\tpredVals <- as.numeric(scale(x@data[ , covariate]))\n\t\t\t\tpredList <- list(predVals)\n\t\t\t\tnames(predList) <- 'predictor'\n\t\t\t\tdata <- c(data, predList)\n\t\t\t}\n\n\t\t\t### constants\n\t\t\tconstants <- list(\n\t\t\t\tnumCounties = nrow(x),\n\t\t\t\tnumStates = length(unique(x@data[ , stateProv])),\n\t\t\t\tstate = as.numeric(as.factor(x@data[ , stateProv])),\n\t\t\t\tlengthAdjCounties = length(carAdjCounty),\n\t\t\t\tisOcc = as.numeric(data$y > 0)\n\t\t\t)\n\t\t\t\n\t\t\t### initializations\n\t\t\tinits <- list(\n\n\t\t\t\tz = as.numeric(data$y > 0),\n\t\t\t\n\t\t\t\tq = 0.01,\n\t\t\t\n\t\t\t\tp = runif(constants$numCounties, 0.1, 0.3),\n\t\t\t\tlogit_p = logit(p),\n\t\t\t\tp_stateMean = rnorm(constants$numStates, 0, 0.5),\n\t\t\t\t\n\t\t\t\tpsi = runif(constants$numCounties, 0.4, 0.6),\n\n\t\t\t\tpsi_island = rnorm(constants$numCounties, 0, 0.1),\n\t\t\t\tpsi_islandMean = -0.1,\n\t\t\t\t\n\t\t\t\tpsi_tau = 0.1,\n\t\t\t\tpsi_car = rnorm(constants$numCounties)\n\t\t\t\t\n\t\t\t)\n\n\t\t\tif (!is.null(covariate)) {\n\n\t\t\t\tinits <- c(\n\t\t\t\t\tinits,\n\t\t\t\t\tlist(psi_beta = 0.1)\n\t\t\t\t)\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t### monitors\n\t\t\tmonitors <- names(inits)\n\t\t\tmonitors <- monitors[!(monitors %in% c('logit_p'))]\n\t\t\tmonitors <- monitors[!(monitors %in% c('z'))]\n\t\n\t### model setup\n\t###############\n\t\n\t\tif (verbose) omnibus::say('Model setup...')\n\t\t\n\t\t### model specification\n\t\tif (is.null(covariate)) {\n\t\t\t\n\t\t\t### WITHOUT covariate\n\t\t\tcode <- nimble::nimbleCode({\n\t\t\t\t\n\t\t\t\t## likelihood\n\t\t\t\tfor (i in 1:numCounties) {\n\n\t\t\t\t\t# detection\n\t\t\t\t\ty[i] ~ dbin(pstar[i], N[i])\n\t\t\t\t\tpstar[i] <- psi[i] * p[i] + (1 - psi[i]) * isOcc[i] * (p[i] * q) # viable but gives large q if isOcc is {0, 1}\n\t\t\t\t\tlogit(p[i]) ~ dnorm(p_stateMean[state[i]], tau=0.001)\n\n\t\t\t\t\t# occupancy\n\t\t\t\t\tlogit(psi[i]) <- hasNeighs[i] * psi_car[i] + (1 - hasNeighs[i]) * psi_island[i]\n\t\t\t\t\tpsi_island[i] ~ dnorm(psi_islandMean, tau=0.001)\n\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\t## priors\n\t\t\t\tq ~ dbeta(10, 1)\n\t\t\t\t\n\t\t\t\t# state effects\n\t\t\t\tfor (j in 1:numStates) {\n\t\t\t\t\tp_stateMean[j] ~ dnorm(0, tau=0.001)\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpsi_islandMean ~ dnorm(0, tau=0.001)\n\t\t\t\t\n\t\t\t\t# county occupancy CAR\n\t\t\t\tpsi_tau ~ dgamma(0.001, 0.001)\n\t\t\t\tpsi_car[1:numCounties] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numCounties], tau=psi_tau, c=3, zero_mean=0)\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\t### WITH covariate\n\t\t\tcode <- nimble::nimbleCode({\n\t\t\t\t\n\t\t\t\t## likelihood\n\t\t\t\tfor (i in 1:numCounties) {\n\n\t\t\t\t\t# detection\n\t\t\t\t\ty[i] ~ dbin(pstar[i], N[i])\n\t\t\t\t\tpstar[i] <- psi[i] * p[i] + (1 - psi[i]) * isOcc[i] * (p[i] * q) # viable but gives large q if isOcc is {0, 1}\n\t\t\t\t\tlogit(p[i]) ~ dnorm(p_stateMean[state[i]], tau=0.001)\n\n\t\t\t\t\t# occupancy\n\t\t\t\t\tlogit(psi[i]) <- hasNeighs[i] * psi_car[i] + (1 - hasNeighs[i]) * psi_island[i] + psi_beta * predictor[i]\n\t\t\t\t\tpsi_island[i] ~ dnorm(psi_islandMean, tau=0.001)\n\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\t## priors\n\t\t\t\tq ~ dbeta(10, 1)\n\t\t\t\t\n\t\t\t\t# state effects\n\t\t\t\tfor (j in 1:numStates) {\n\t\t\t\t\tp_stateMean[j] ~ dnorm(0, tau=0.001)\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpsi_islandMean ~ dnorm(0, tau=0.001)\n\t\t\t\t\n\t\t\t\tbeta ~ dnorm(0, tau=0.001)\n\t\t\t\t\n\t\t\t\t# county occupancy CAR\n\t\t\t\tpsi_tau ~ dgamma(0.001, 0.001)\n\t\t\t\tpsi_car[1:numCounties] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numCounties], tau=psi_tau, c=3, zero_mean=0)\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t} # if covariate\n\t\t\n\t\t\n\t\t### construct and compile model\n\t\tmodel <- nimble::nimbleModel(code=code, constants=constants, data=data, inits=inits, check=TRUE)\n\t\tflush.console()\n\t\t\n\t\t# conf <- nimble::configureMCMC(model, monitors = monitors, thin = thin, print = verbose, ...)\n\t\tconf <- nimble::configureMCMC(model, monitors = monitors, thin = thin, print = verbose)\n\t\tflush.console()\n\t\t\n\t\t## modify samplers\n\t\tconf$removeSamplers('psi_tau')\n\t\tconf$addSampler(target='psi_tau', type='slice')\n\t\t\n\t\tconf$removeSamplers('q')\n\t\tconf$addSampler(target='q', type='slice')\n\n\t\tif (!is.null(covariate)) {\n\t\t\tconf$removeSamplers('psi_beta')\n\t\t\tconf$addSampler(target='psi_beta', type='slice')\n\t\t}\n\n\t\tfor (i in 1:constants$numCounties) {\n\t\t\tconf$removeSamplers(paste0('logit_p[', i, ']'))\n\t\t\tconf$addSampler(target=paste0('logit_p[', i, ']'), type='slice')\n\t\t\n\t\t}\n\t\t\n\t\tfor (i in 1:constants$numCounties) {\n\t\t\tconf$removeSamplers(paste0('psi_island[', i, ']'))\n\t\t\tconf$addSampler(target=paste0('psi_island[', i, ']'), type='slice')\n\t\t\n\t\t}\n\n\t\tconfBuild <- nimble::buildMCMC(conf)\n\t\tflush.console()\n\t\tcompiled <- nimble::compileNimble(model, confBuild)\n\t\tflush.console()\n\n\t### MCMC\n\t########\n\t\t\n\t\tif (verbose) omnibus::say('Modeling...')\n\t\t# mcmc <- runMCMC(compiled$confBuild, niter = niter, nburnin = nburnin, nchains = nchains, inits = inits, progressBar = verbose, samplesAsCodaMCMC = TRUE, summary = FALSE, ...)\n\t\tmcmc <- runMCMC(compiled$confBuild, niter = niter, nburnin = nburnin, nchains = nchains, inits = inits, progressBar = verbose, samplesAsCodaMCMC = TRUE, summary = FALSE)\n\t\tflush.console()\n\n\t\t# rm(model, compiled, confBuild)\n\t\t# gc()\n\t\t\n\t### process model output\n\t########################\n\t\n\t\tomnibus::say('Processing model output...')\n\n\t\t### remove unneeded stuff\n\t\t#########################\n\n\t\t\tmcmc <- list(samples = mcmc)\n\n\t\t\t# remove unneeded\n\t\t\tignores <- c('logit_p[[]', 'z[[]')\n\t\t\tfor (ignore in ignores) {\n\t\t\t\tbads <- grepl(colnames(mcmc$samples$chain1), pattern=ignore)\n\t\t\t\tif (any(bads)) {\n\t\t\t\t\tfor (chain in 1:nchains) {\n\t\t\t\t\t\tmcmc$samples[[chain]] <- mcmc$samples[[chain]][ , !bads]\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t\t# remove island coefficients for non-islands and CAR coefficients for islands\n\t\t\tif (any(!hasNeighs)) {\n\t\t\t\n\t\t\t\t# psi_car for islands\n\t\t\t\tindex <- which(!hasNeighs)\n\t\t\t\tbads <- paste0('psi_car[', index, ']')\n\t\t\t\tfor (chain in 1:nchains) {\n\t\t\t\t\tremove <- which(colnames(mcmc$samples[[chain]]) %in% bads)\n\t\t\t\t\tmcmc$samples[[chain]] <- mcmc$samples[[chain]][ , -remove]\n\t\t\t\t}\n\t\t\t\n\t\t\t\t# psi_island for non-islands\n\t\t\t\tindex <- which(hasNeighs)\n\t\t\t\tbads <- paste0('psi_island[', index, ']')\n\t\t\t\tfor (chain in 1:nchains) {\n\t\t\t\t\tremove <- which(colnames(mcmc$samples[[chain]]) %in% bads)\n\t\t\t\t\tmcmc$samples[[chain]] <- mcmc$samples[[chain]][ , -remove]\n\t\t\t\t}\n\t\t\t\t\n\t\t\t# no islands\n\t\t\t} else {\n\t\t\t\n\t\t\t\t# remove psi_island and psi_islandMean for all\n\t\t\t\tindex <- which(hasNeighs)\n\t\t\t\tbads <- c(paste0('psi_island[', index, ']'), 'psi_islandMean')\n\t\t\t\tfor (chain in 1:nchains) {\n\t\t\t\t\tremove <- which(colnames(mcmc$samples[[chain]]) %in% bads)\n\t\t\t\t\tmcmc$samples[[chain]] <- mcmc$samples[[chain]][ , -remove]\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\n\t\t\t\t\t\t# conv <- rhatStats(mcmc$samples, rhatThresh=1.1, minConv=minUnconverged)\n\t\t\t\t\t\t# print(str(conv))\n\t\t\t\t\t\t# w <- as.Bwiqid(mcmc$samples)\n\n\t\t\t\t\t\t# caterplot(mcmc$samples, regex='p[[]')\n\t\t\t\t\t\t# caterplot(mcmc$samples, regex='psi[[]')\n\n\t\t\t\t\t\t# diagPlot(w, params='p')\n\t\t\t\t\t\t# diagPlot(w, params='psi')\n\t\t\t\t\t\t# diagPlot(w, params='q')\n\t\t\t\t\t\t# diagPlot(w, params='psi_tau')\n\t\t\t\n\t\t### calculate summary\n\t\t#####################\n\t\t\n\t\t\tmcmc$summary$all.chains <- matrix(NA, nrow=ncol(mcmc$samples[[1]]), ncol=6)\n\t\t\trownames(mcmc$summary$all.chains) <- colnames(mcmc$samples[[1]])\n\t\t\tcolnames(mcmc$summary$all.chains) <- c('Mean', 'Median', 'St.Dev', '95%CI_low', '95%CI_upp', 'rhat')\n\t\t\t\n\t\t\tsamps <- mcmc$samples[[1]]\n\t\t\tif (nchains > 1) {\n\t\t\t\tfor (chain in 2:nchains) {\n\t\t\t\t\tsamps <- rbind(samps, mcmc$samples[[chain]])\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmcmc$summary$all.chains[ , 'Mean'] <- colMeans(samps)\n\t\t\tmcmc$summary$all.chains[ , 'Median'] <- apply(samps, 2, median)\n\t\t\tmcmc$summary$all.chains[ , 'St.Dev'] <- apply(samps, 2, sd)\n\t\t\tmcmc$summary$all.chains[ , '95%CI_low'] <- apply(samps, 2, quantile, probs=0.025)\n\t\t\tmcmc$summary$all.chains[ , '95%CI_upp'] <- apply(samps, 2, quantile, probs=0.975)\n\t\t\tmcmc$summary$all.chains[ , 'rhat'] <- wiqid::simpleRhat(mcmc$samples, n.chains=nchains)\n\n\t\t\trm(samps); gc()\n\n\t\t### update shapefile\n\t\t####################\n\n\t\t\tpsi <- mcmc$summary$all.chains[grepl(rownames(mcmc$summary$all.chains), pattern='psi[[]'), 'Mean']\n\t\t\tp <- mcmc$summary$all.chains[grepl(rownames(mcmc$summary$all.chains), pattern='p[[]'), 'Mean']\n\t\t\t\n\t\t\tuncer <- mcmc$summary$all.chains[ , '95%CI_upp'] - mcmc$summary$all.chains[ , '95%CI_low']\n\t\t\tnames(uncer) <- rownames(mcmc$summary$all.chains)\n\t\t\toccUncer <- uncer[grepl(names(uncer), pattern='psi[[]')]\n\t\t\tpUncer <- uncer[grepl(names(uncer), pattern='p[[]')]\n\n\t\t\tx@data$psi <- psi\n\t\t\tx@data$occUncer <- occUncer\n\t\t\tx@data$p <- p\n\t\t\tx@data$pUncer <- pUncer\n\t\t\t\n\t\t\tnames(x@data)[(ncol(x@data) - 3):ncol(x@data)] <- c('psi', 'psi95CI', 'p', 'p95CI')\n\t\t\t\n\t\t### collate\n\t\t###########\n\t\t\n\t\t\tmeta <- list(\n\t\t\t\tniter=niter,\n\t\t\t\tnburnin=nburnin,\n\t\t\t\tnchains=nchains,\n\t\t\t\tthin=thin,\n\t\t\t\teffort=effort,\n\t\t\t\tdetect=detect,\n\t\t\t\tstateProv=stateProv,\n\t\t\t\tcounty=county,\n\t\t\t\tcovariate=covariate,\n\t\t\t\thasIslands=any(!hasNeighs),\n\t\t\t\tqGivenDetect=qGivenDetect,\n\t\t\t\tna.rm=na.rm\n\t\t\t)\n\t\t\t\n\t\t\tattr(x, 'meta') <- meta\n\t\t\t\t\n\t### output\n\tlist(mcmc=mcmc, code=code, shape=x, meta=meta)\n\n}\n", "meta": {"hexsha": "3d0cd70252967453ee27825f3efacb18b312388b", "size": 12866, "ext": "r", "lang": "R", "max_stars_repo_path": "code/trainBayesODM.r", "max_stars_repo_name": "adamlilith/tropicosMassModeling", "max_stars_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/trainBayesODM.r", "max_issues_repo_name": "adamlilith/tropicosMassModeling", "max_issues_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-10T23:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T23:54:10.000Z", "max_forks_repo_path": "code/trainBayesODM.r", "max_forks_repo_name": "adamlilith/tropicosMassModeling", "max_forks_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8214285714, "max_line_length": 631, "alphanum_fraction": 0.6290999534, "num_tokens": 4188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6261241772283033, "lm_q1q2_score": 0.4744733772225737}} {"text": "# Glossary ----\n\n# n.b. the following employs a mix of snake_case and camelCase that is sure to\n# vex some, but represents the author's best attempt to balance to the competing\n# aims of clarity & brevity.\n\n# Y: observed outcome\n# nY: number of observed outcomes\n# X: predictor/contrast matrix\n# nX: number of predictors (columns in the contrast matrix)\n# rX: number of rows in the contrast matrix X\n# (i)ndividual: a unit of observation within which correlated measurements may take place\n# (c)ondition: a labelled set of observations within an individual that share some feature/predictor or conjunction of features/predictors\n# Xc: condition-level contrast matrix\n# nXc: number of predictors in the condition-level contrast matrix\n# rXc: number of rows in the condition-level contrast matrix\n# yXc: for each observation in y, an index indicating the associated row in Xc corresponding to that observation's individual/condition combo\n# (g)roup: a collection of individuals that share some feature/predictor\n# Xg: group-level contrast matrix\n# nXg: number of predictors in the group-level contrast matrix\n# rXg: number of rows in the group-level contrast matrix\n# Z: matrix of coefficient row-vectors to be dot-product'd with a contrast matrix\n# iZc: matrix of coefficient row-vectors associated with each individual\n\n# Preamble (options, installs, imports & custom functions) ----\n\noptions(warn=1) # really should be default in R\n`%!in%` = Negate(`%in%`) # should be in base R!\n\n# specify the packages used:\nrequired_packages = c(\n\t'github.com/rmcelreath/rethinking' # for rlkjcorr & rmvrnom2\n\t, 'github.com/stan-dev/cmdstanr' # for Stan stuff\n\t, 'github.com/mike-lawrence/aria/aria' # for aria\n\t, 'tidyverse' # for all that is good and holy\n)\n\n# load the helper functions:\nfor(file in fs::dir_ls('r')){\n\tcat('Loading function: ',fs::path_ext_remove(fs::path_file(file)),'()\\n',sep='')\n\tsource(file)\n}\n\n# install any required packages not already present\ninstall_if_missing(required_packages)\n\n# load tidyverse & aria\nlibrary(tidyverse)\nlibrary(aria)\n\n# Simulate data ----\nset.seed(1) # change this to make different data\n\n# setting the data simulation parameters\n\n# parameters you can play with\nnG_vars = 1 # number of 2-level variables manipulated as crossed and across individuals, must be an integer >0\nnC_vars = 2 # number of 2-level variables manipulated as crossed and within each individual, must be an integer >0\nnI_per_group = 3 # number of individuals, must be an integer >1\nnY_per_ic = 4 # number of observations per individual/condition combo, must be an integer >1\n# the latter two combine to determine whether centered or non-centered will sample better\n\n\n# the rest of these you shouldn't touch\nnXc = 2^(nC_vars)\nnXg = 2^(nG_vars)\nZ = matrix(rnorm(nXg*nXc),nrow=nXg,ncol=nXc)\niZc_sd = rweibull(nXc,2,1)\niZc_r_mat = rethinking::rlkjcorr(1,nXc,eta=1)\nY_sd = rweibull(1,2,1)\niZc_r_vec = iZc_r_mat[lower.tri(iZc_r_mat)]\n\n\n# compute Xg\nXg = sim_contrasts(nG_vars,'G')\n\n# compute gZc\ngZc = matrix(NA,nrow=nXg,ncol=nXc)\nfor(this_nXc in 1:nXc){\n\tfor(this_nXg in 1:nXg){\n\t\tgZc[this_nXg,this_nXc] = Xg[this_nXg,] %*% Z[,this_nXc]\n\t}\n}\n\n# compute iZc\n(\n\t1:nXg\n\t%>% map_dfr(\n\t\t.f = function(this_nXg){(\n\t\t\trethinking::rmvnorm2(\n\t\t\t\tn = nI_per_group\n\t\t\t\t, Mu = gZc[this_nXg,]\n\t\t\t\t, sigma = iZc_sd\n\t\t\t\t, Rho = iZc_r_mat\n\t\t\t)\n\t\t\t%>% as_tibble(\n\t\t\t\t.name_repair = function(x) paste0('iZc[.,',1:length(x),']')\n\t\t\t)\n\t\t\t%>% mutate(\n\t\t\t\tg = this_nXg\n\t\t\t\t, individual = paste(g,1:n(),sep='_') # important that individuals have unique identifiers across groups\n\t\t\t)\n\t\t)}\n\t)\n) ->\n\tiZc\n\n# compute Xc\nuXc = sim_contrasts(nC_vars,'C')\n\n# compute iZc_dot_Xc\n(\n\tiZc\n\t%>% group_by(g,individual)\n\t%>% summarise(\n\t\t{function(x){\n\t\t\tx = t(as.matrix(select(x,starts_with('iZc')),))\n\t\t\tthis_dot = rep(NA,nXc)\n\t\t\tfor(this_nXc in 1:nXc){\n\t\t\t\tthis_dot[this_nXc] = uXc[this_nXc,] %*% x\n\t\t\t}\n\t\t\ttibble(c=1:nXc,value=this_dot)\n\t\t}}(cur_data())\n\t\t, .groups = 'keep'\n\t)\n) ->\n\tiZc_dot_Xc\n\n# compute Y\n(\n\tiZc_dot_Xc\n\t%>% group_by(c,.add=T)\n\t%>% summarise(\n\t\tvalue = rnorm(nY_per_ic,value,Y_sd)\n\t\t, .groups = 'keep'\n\t)\n) ->\n\tY\n\n# join with group & condition columns\n(\n\tY\n\t%>% left_join((\n\t\tattr(Xg,'data')\n\t\t%>% mutate(g=1:n())\n\t))\n\t%>% left_join((\n\t\tattr(uXc,'data')\n\t\t%>% mutate(c=1:n())\n\t))\n\t%>% ungroup()\n\t%>% select(everything(),-g,-c,-value,value)\n) ->\n\tdat\n\n# dat is now what one would typically have as collected data\ndat\n\n# if there's no missing data (as in this synthetic example), we could proceed with modelling,\n# but to demonstrate how to handle missing data, we'll do a bit of extra work:\n\n# Uncomment next section to induce data-missingness (causes some Ss to be missing whole conditions)\n# (\n# \tdat\n# \t# select all but value\n# \t%>% select(-value)\n# \t# get distinct rows (no more individual trials)\n# \t%>% distinct()\n# \t# group by individual\n# \t%>% group_by(individual)\n# \t# toss one condition\n# \t%>% slice_sample(n=(nXc-1))\n# \t# semi-join to keep all in dat that have been kept above\n# \t%>% semi_join(\n# \t\tx = dat\n# \t\t, y = .\n# \t)\n# ) ->\n# \tdat\n\nnrow(dat)\n\n# Compute inputs to Stan model ----\n\n# Some data prep\n(\n\tdat\n\t# ungroup (necessary)\n\t%>% ungroup()\n\t# ensure individual is a sequential numeric\n\t%>% mutate(\n\t\tindividual = as.numeric(factor(individual))\n\t)\n\t# arrange rows by individual\n\t%>% arrange(individual)\n) ->\n\tdat\n\n# compute Xg from distinct combinations of groups\n(\n\tdat\n\t# select down to any G vars\n\t%>% select(starts_with('G'))\n\t# collapse to distinct set of rows (combinations of grouping variables)\n\t%>% distinct()\n\t# arrange (not really necessary, but why not)\n\t%>% arrange()\n\t# add the contrast matrix columns\n\t%>% mutate(\n\t\tcontrasts = get_contrast_matrix_rows_as_list(\n\t\t\tdata = .\n\t\t\t# the following complicated specification of the formula is a by-product of making this example\n\t\t\t# work for any number of variables = normally you would do something like this\n\t\t\t# (for 2 variables for example):\n\t\t\t# formula = ~ G1*G2\n\t\t\t, formula = as.formula(paste0('~',paste0('G',1:nG_vars,collapse='*')))\n\t\t\t# half-sum contrasts are nice for 2-level variables bc they yield parameters whose value\n\t\t\t# is the difference between conditions\n\t\t\t, contrast_kind = halfsum_contrasts\n\t\t)\n\t)\n) ->\n\tXg_with_vars\n\n# show contrasts\n(\n\tXg_with_vars\n\t%>% unnest(contrasts)\n)\n\n# join Xg with dat to label individuals with corresponding row from Xg\n(\n\tXg_with_vars\n\t# add row identifier\n\t%>% mutate(Xg_row=1:n())\n\t# join with dat, collapsed to 1-row per individual with their group info\n\t%>% right_join((# right-join to apply the row order from dat\n\t\tdat\n\t\t%>% select(individual,starts_with('G'))\n\t\t%>% distinct()\n\n\t))\n\t%>% arrange(individual)\n\t%>% pull(Xg_row)\n) ->\n\tiXg\n\n# compute complete_Xc from distinct combinations of individuals & conditions\n(\n\tdat\n\t# select individual & any condition-defining columns\n\t%>% select(individual,starts_with('C'))\n\t# collapse down to distinct rows (1 per individual/conditions combo)\n\t%>% distinct()\n\t# expand (in case there's any missing data; doesn't hurt if not)\n\t# %>% exec(expand_grid,!!!.) #should work, but doesn't, so need the next three instead\n\t%>% as.list()\n\t%>% map(unique)\n\t%>% cross_df()\n\t# arrange (not really necessary, but why not)\n\t%>% arrange()\n\t# add the contrast matrix columns\n\t%>% mutate(\n\t\tcontrasts = get_contrast_matrix_rows_as_list(\n\t\t\tdata = .\n\t\t\t# the following complicated specification of the formula is a by-product of making this example\n\t\t\t# work for any number of variables = normally you would do something like this\n\t\t\t# (for 2 variables for example):\n\t\t\t# formula = ~ C1*C2\n\t\t\t, formula = as.formula(paste0('~',paste0('C',1:nC_vars,collapse='*')))\n\t\t\t# half-sum contrasts are nice for 2-level variables bc they yield parameters whose value\n\t\t\t# is the difference between conditions\n\t\t\t, contrast_kind = halfsum_contrasts\n\t\t)\n\t)\n) ->\n\tcomplete_Xc_with_vars\n\n# show the unique contrasts\n(\n\tcomplete_Xc_with_vars\n\t%>% select(-individual)\n\t%>% distinct()\n\t%>% unnest(contrasts)\n)\n\n# subset down to just those individual-condition combos actually present in the data\n# it's ok if there's no missing data and nrow(complete_Xc_with_vars)==nrow(Xc_with_vars)\n(\n\tcomplete_Xc_with_vars\n\t%>% semi_join(dat)\n) ->\n\tXc_with_vars\n\n\n# join Xc with dat to label observations with corresponding row from Xc\n(\n\tXc_with_vars\n\t# add row identifier\n\t%>% mutate(Xc_row=1:n())\n\t# right-join with dat to preserve dat's row order\n\t%>% right_join(\n\t\tmutate(dat,dat_row=1:n())\n\t)\n\t%>% arrange(dat_row)\n\t# pull the Xc row identifier\n\t%>% pull(Xc_row)\n) ->\n\tyXc\n\n\n# package for stan & sample ----\n\ndata_for_stan = lst( # lst permits later entries to refer to earlier entries\n\n\t# # # #\n\t# Entries we need to specify ourselves\n\t# # # #\n\n\n\t# Xg: group-level predictor matrix\n\tXg = (\n\t\tXg_with_vars\n\t\t%>% select(contrasts)\n\t\t%>% unnest(contrasts)\n\t\t%>% as.matrix()\n\t)\n\n\t# iXg: which group each individual is associated with\n\t, iXg = iXg\n\n\t# Xc: condition-level predictor matrix\n\t, Xc = (\n\t\tXc_with_vars\n\t\t%>% select(contrasts)\n\t\t%>% unnest(contrasts)\n\t\t%>% as.matrix()\n\t)\n\n\t# iXc: which individual is associated with each row in Xc\n\t, iXc = as.numeric(factor(Xc_with_vars$individual))\n\n\t# Y: observations\n\t, Y = dat$value\n\n\t# yXc: which row in Xc is associated with each observation in Y\n\t, yXc = yXc\n\n\t# # # #\n\t# Entries computable from the above\n\t# # # #\n\n\t# nXg: number of cols in the group-level predictor matrix\n\t, nXg = ncol(Xg)\n\n\t# rXg: number of rows in the group-level predictor matrix\n\t, rXg = nrow(Xg)\n\n\t# nI: number of individuals\n\t, nI = max(iXc)\n\n\t# nXc: number of cols in the condition-level predictor matrix\n\t, nXc = ncol(Xc)\n\n\t# rXc: number of rows in the condition-level predictor matrix\n\t, rXc = nrow(Xc)\n\n\t# nY: num entries in the observation vectors\n\t, nY = length(Y)\n\n)\n\n# double-check:\nglimpse(data_for_stan)\n\n# set the model path (automated bc in this repo there's only one)\nmod_path = fs::dir_ls(\n\tpath = 'stan'\n\t, glob = '*.stan'\n)\n\n# set the model centered/non-centeredness\n# generally, if *either* nI_per_group *or* num_Y_per_ic is small, non-centered will sample better than centered\ndata_for_stan$centered = F\n\n# conversion to 1/0 for stan\ndata_for_stan$centered = as.numeric(data_for_stan$centered)\n\n# set the posterior path (automated but you could do your own if you had multiple models)\n(\n\tmod_path\n\t%>% fs::path_file()\n\t%>% fs::path_ext_remove()\n\t%>% paste0(\n\t\tifelse(data_for_stan$centered,'_c','_nc')\n\t)\n\t%>% fs::path(\n\t\t'posteriors'\n\t\t, .\n\t\t, ext = 'netcdf4'\n\t)\n) -> post_path\n\n# ensure model is compiled\naria:::check_and_compile(mod_path,block=T)\n\n# compose\naria::compose(\n\tdata = data_for_stan\n\t, code_path = mod_path\n\t, out_path = post_path\n\t, overwrite = T\n\t, block = T\n)\n\n# how long did it take?\naria::marginalia()$time\n\n\n# check posterior diagnostics ----\npost = aria::coda(post_path)\n\n# Check treedepth, divergences, & rebfmi\n(\n\tpost$draws(group='sample_stats')\n\t%>% posterior::as_draws_df()\n\t%>% group_by(.chain)\n\t%>% summarise(\n\t\tmax_treedepth = max(treedepth)\n\t\t, num_divergent = sum(divergent)\n\t\t, rebfmi = var(energy)/(sum(diff(energy)^2)/n()) # n.b. reciprocal of typical EBFMI, so bigger=bad, like rhat\n\t)\n)\n\n# gather summary for core parameters (inc. r̂ & ess)\n(\n\tpost$draws(group='parameters')\n\t%>% posterior::summarise_draws(.cores=parallel::detectCores())\n) ->\n\tpar_summary\n\n# show the ranges of r̂/ess's\n(\n\tpar_summary\n\t%>% select(rhat,contains('ess'))\n\t%>% summary()\n)\n\n# View those with suspect r̂\n(\n\tpar_summary\n\t%>% filter(rhat>1.01)\n\t%>% (function(suspects){\n\t\tif(nrow(suspects)>1){\n\t\t\tView(suspects)\n\t\t}\n\t\treturn(paste('# suspect parameters:',nrow(suspects)))\n\t})()\n)\n\n# Viz recovery of non-correlation parameters ----\n(\n\tpost$draws(variables=c('Y_sd','Z','iZc_sd'))\n\t%>% posterior::as_draws_df()\n\t%>% select(-.draw)\n\t%>% pivot_longer(\n\t\tcols = -c(.chain,.iteration)\n\t\t, names_to = 'variable'\n\t)\n\t%>% group_by(variable)\n\t%>% arrange(variable,.chain,.iteration)\n\t%>% summarise(\n\t\trhat = 1.01posterior::ess_bulk(matrix(value,ncol=length(unique(.chain))))\n\t\t, ess_tail = 100>posterior::ess_tail(matrix(value,ncol=length(unique(.chain))))\n\t\t, as_tibble(t(posterior::quantile2(value,c(.05,.25,.5,.75,.95))))\n\t)\n\t#add true values\n\t%>% left_join(\n\t\tbind_rows(\n\t\t\ttibble(\n\t\t\t\ttrue = Y_sd\n\t\t\t\t, variable = 'Y_sd'\n\t\t\t)\n\t\t\t, tibble(\n\t\t\t\ttrue = as.vector(Z)\n\t\t\t\t, variable = paste0(\n\t\t\t\t\t'Z['\n\t\t\t\t\t,rep(1:nXg,times=nXc)\n\t\t\t\t\t,','\n\t\t\t\t\t,rep(1:nXc,each=nXg)\n\t\t\t\t\t,']'\n\t\t\t\t)\n\t\t\t)\n\t\t\t, tibble(\n\t\t\t\ttrue = iZc_sd\n\t\t\t\t, variable = paste0('iZc_sd[',1:length(true),']')\n\t\t\t)\n\t\t)\n\t)\n\t%>% ggplot()\n\t+ geom_hline(yintercept = 0)\n\t+ geom_linerange(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, ymin = q5\n\t\t\t, ymax = q95\n\t\t\t, colour = ess_tail\n\t\t)\n\t\t, alpha = .5\n\t)\n\t+ geom_linerange(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, ymin = q25\n\t\t\t, ymax = q75\n\t\t\t, colour = ess_bulk\n\t\t)\n\t\t, size = 3\n\t\t, alpha = .5\n\t)\n\t+ geom_point(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, y = q50\n\t\t\t, fill = rhat\n\t\t)\n\t\t, shape = 21\n\t\t, size = 3\n\t)\n\t+ geom_point(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, y = true\n\t\t)\n\t\t, size = 4\n\t\t, shape = 4\n\t\t, colour = 'blue'\n\t)\n\t+ coord_flip()\n\t+ scale_color_manual(\n\t\tvalues = lst(`TRUE`='red',`FALSE`='black')\n\t\t, labels = lst(`TRUE`='<100',`FALSE`='>=100')\n\t)\n\t+ scale_fill_manual(\n\t\tvalues = lst(`TRUE`='red',`FALSE`='white')\n\t\t, labels = lst(`TRUE`='>1.01',`FALSE`='<=1.01')\n\t)\n\t+ labs(\n\t\ty = 'True & Posterior Value'\n\t\t, x = 'Variable'\n\t\t, colour = 'ESS'\n\t\t, fill = 'Rhat'\n\t)\n)\n\n\n\n# Viz recovery of correlations ----\n(\n\tpost$draws(variables='iZc_r_vec')\n\t%>% posterior::as_draws_df()\n\t%>% select(-.draw)\n\t%>% pivot_longer(\n\t\tcols = -c(.chain,.iteration)\n\t\t, names_to = 'variable'\n\t)\n\t%>% group_by(variable)\n\t%>% arrange(variable,.chain,.iteration)\n\t%>% summarise(\n\t\trhat = 1.01posterior::ess_bulk(matrix(value,ncol=length(unique(.chain))))\n\t\t, ess_tail = 100>posterior::ess_tail(matrix(value,ncol=length(unique(.chain))))\n\t\t, as_tibble(t(posterior::quantile2(value,c(.05,.25,.5,.75,.95))))\n\t)\n\t#add true values\n\t%>% left_join(\n\t\ttibble(\n\t\t\ttrue = iZc_r_vec\n\t\t\t, variable = case_when(\n\t\t\t\tlength(true)==1 ~ 'r'\n\t\t\t\t, T ~ paste0('iZc_r_vec[',1:length(true),']')\n\t\t\t)\n\t\t)\n\t)\n\t%>% mutate(variable = factor_1d(variable))\n\t%>% ggplot()\n\t+ geom_hline(yintercept = 0)\n\t+ geom_linerange(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, ymin = q5\n\t\t\t, ymax = q95\n\t\t\t, colour = ess_tail\n\t\t)\n\t\t, alpha = .5\n\t)\n\t+ geom_linerange(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, ymin = q25\n\t\t\t, ymax = q75\n\t\t\t, colour = ess_bulk\n\t\t)\n\t\t, size = 3\n\t\t, alpha = .5\n\t)\n\t+ geom_point(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, y = q50\n\t\t\t, fill = rhat\n\t\t)\n\t\t, shape = 21\n\t\t, size = 3\n\t)\n\t+ geom_point(\n\t\tmapping = aes(\n\t\t\tx = variable\n\t\t\t, y = true\n\t\t)\n\t\t, size = 4\n\t\t, shape = 4\n\t\t, colour = 'blue'\n\t)\n\t+ coord_flip()\n\t+ scale_color_manual(\n\t\tvalues = lst(`TRUE`='red',`FALSE`='black')\n\t\t, labels = lst(`TRUE`='<100',`FALSE`='>=100')\n\t)\n\t+ scale_fill_manual(\n\t\tvalues = lst(`TRUE`='red',`FALSE`='white')\n\t\t, labels = lst(`TRUE`='>1.01',`FALSE`='<=1.01')\n\t)\n\t+ labs(\n\t\ty = 'True & Posterior Value'\n\t\t, x = 'Variable'\n\t\t, colour = 'ESS'\n\t\t, fill = 'Rhat'\n\t)\n)\n\n# fit with brms to compare sampling speed ----\nlibrary(brms)\nbrms_data = mutate(dat,id = factor(individual))\nbrms_formula = bf(\n\tformula = value ~ G1*G2*C1*C2 + ( C1*C2 | id )\n\t, family = gaussian()\n)\nbrms_prior = c(\n\tprior(normal(0, 1), class = 'Intercept')\n\t, prior(normal(0, 1), class = 'b')\n\t, prior(weibull(2, 1), class = 'sigma')\n\t, prior(lkj(1), class = 'cor')\n\t, prior(normal(0, 1), class = 'sd')\n)\nbrms_standata = make_standata(\n\tdata = brms_data\n\t, formula = brms_formula\n)\nattr(brms_standata,'class') = NULL\nbrms_stancode = make_stancode(\n\tdata = brms_data\n\t, formula = brms_formula\n\t, prior = brms_prior\n\t, normalize = F\n)\nbrms_code_path = 'brms/brms_hmg.stan'\n# write( brms_stancode, file = brms_code_path ) #commented-out bc after initial write I edited the file a bit\n\n# ensure model is compiled\naria:::check_and_compile(\n\tbrms_code_path\n\t, compile_debug = F\n\t, run_debug = F\n\t, block = T\n)\n\n# compose\nbrms_post_path = 'posteriors/brms.netcdf4'\naria::compose(\n\tdata = brms_standata\n\t, code_path = brms_code_path\n\t, out_path = brms_post_path\n\t, overwrite = T\n\t, block = T\n)\n\n# how long did it take?\naria::marginalia()$time\n\n\n# check posterior diagnostics ----\npost = aria::coda(brms_post_path)\n\n# Check treedepth, divergences, & rebfmi\n(\n\tpost$draws(group='sample_stats')\n\t%>% posterior::as_draws_df()\n\t%>% group_by(.chain)\n\t%>% summarise(\n\t\tmax_treedepth = max(treedepth)\n\t\t, num_divergent = sum(divergent)\n\t\t, rebfmi = var(energy)/(sum(diff(energy)^2)/n()) # n.b. reciprocal of typical EBFMI, so bigger=bad, like rhat\n\t)\n)\n\n# gather summary for core parameters (inc. r̂ & ess)\n(\n\tpost$draws(group='parameters')\n\t%>% posterior::summarise_draws(.cores=parallel::detectCores())\n) ->\n\tpar_summary\n\n# show the ranges of r̂/ess's\n(\n\tpar_summary\n\t%>% select(rhat,contains('ess'))\n\t%>% summary()\n)\n\n# View those with suspect r̂\n(\n\tpar_summary\n\t%>% filter(rhat>1.01)\n\t%>% (function(suspects){\n\t\tif(nrow(suspects)>1){\n\t\t\tView(suspects)\n\t\t}\n\t\treturn(paste('# suspect parameters:',nrow(suspects)))\n\t})()\n)\n\n", "meta": {"hexsha": "40a9239b966561211a865194f29341bf38443019", "size": 17170, "ext": "r", "lang": "R", "max_stars_repo_path": "models/hmg/generate_and_fit_demo.r", "max_stars_repo_name": "mike-lawrence/benchmark_stan_models", "max_stars_repo_head_hexsha": "27f0241538cb36e7ec651ad76771bc4a9fad7651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-02T11:35:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T11:35:03.000Z", "max_issues_repo_path": "models/hmg/generate_and_fit_demo.r", "max_issues_repo_name": "mike-lawrence/benchmark_stan_models", "max_issues_repo_head_hexsha": "27f0241538cb36e7ec651ad76771bc4a9fad7651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/hmg/generate_and_fit_demo.r", "max_forks_repo_name": "mike-lawrence/benchmark_stan_models", "max_forks_repo_head_hexsha": "27f0241538cb36e7ec651ad76771bc4a9fad7651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3923705722, "max_line_length": 141, "alphanum_fraction": 0.6660454281, "num_tokens": 5636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47427284522719104}} {"text": "### Function to simulate traits with causative markers for GWAS \n\n# need genomic data . A sample of 22k random SNPs from the Arabidopsis 1001G Projekt is available as example for Arabidopsis traits \n# a file with the Information of all 2029 accessions for which genotype data exist is also provided (lat_long_2029.csv). This information has been downloaded from the AraPheno database \n\n#A<-read.csv('~/git/GWAS/data/lat_long_2029.csv')\n#If you use own data ensure that the id should be in a column called 'accession_id'\n#load('~/git/GWAS/data/X_Mix.rda')\n#rownames(X) needs to be the ids of the accessions\n# for models with multiple causative markers, it is recommended to have them orderd by the amount of variance explained (ve)\n\n# the simulation create random, but reproducible (seed) phenotypes.\n# to simulate only in specific accession provide an integer of accessions ids in sp_acc (length need to be >1). \n# to siumulate distinct markers, the script can be modified manually.\n\nsim_Y<-function(n=100,acc=A,sp_acc=0,no_acc=200,fix_acc=TRUE,SNPs=X,no_snps=1,ve=.1,mac=5,h2=0.7,seed=42) {\n stopifnot(no_snps>0)\n stopifnot(length(ve)==no_snps)\n set.seed(seed)\n \n Sim<-list()\n Caus<-list()\nif (length(sp_acc)>1){\n a<-sp_acc\n no_acc=length(a)\n}else {\na<-sample(acc$accession_id,no_acc) }\n \nX_<-SNPs[rownames(SNPs)%in%a,]\n\naf<-apply(X_,2,sum)\nX_ok<-X_[,which(af>mac&af<(no_acc-mac))]\n\nu<-1\n# set the seed \nset.seed(seed+u)\n \ncaus<-X_ok[,sample(1:ncol(X_ok),(no_snps+1))]\n\n#generating polygenic background\n\nX3<-X_ok[,!colnames(X_ok)%in%colnames(caus)]\n\nback<-X3[,sample(1:ncol(X3),1000)]\n\nbetas<-rnorm(1000,mean=0,sd=0.1)\nfirst<- back %*% betas\n### adding genetic background to data\nsim<-data.frame(ecot_id=as.integer(rownames(back)),value=first)\n### set heritability \ndat<-var(sim[,2])\n\nh_2<-dat/h2-dat\nfix1<-rnorm(nrow(back),0,sqrt(h_2))\nsim_<-data.frame(ecot_id=as.integer(rownames(back)),value=first+fix1)\n\n\nfor ( t in 1:length(ve)) {\nbeta<-sqrt((ve[t]/(1-ve[t]))*(var(sim_[,2])/var(caus[,t])))\n\ncand<-beta*caus[,t]\nsim_$value<-sim_$value+cand\n\n}\nSim[[u]]<-sim_\nCaus[[u]]<-colnames(caus)[1:t]\n\nif (fix_acc==FALSE) {\n for ( u in 2:n ) {\n set.seed(seed+u)\n a<-sample(A$accession_id,no_acc)\n X_<-subset(X,rownames(X)%in%a)\n \n af<-apply(X_,2,sum)\n X_ok<-X_[,which(af>mac&af<(no_acc-mac))]\n \n\n caus<-X_ok[,sample(1:ncol(X_ok),(no_snps+1))]\n \n #generating polygenic background\n \n X3<-X_ok[,!colnames(X_ok)%in%colnames(caus)]\n \n back<-X3[,sample(1:ncol(X3),1000)]\n \n betas<-rnorm(1000,mean=0,sd=0.1)\n first<- back %*% betas\n ### adding genetic background to data\n sim<-data.frame(ecot_id=as.integer(rownames(back)),value=first)\n ### set heritability \n dat<-var(sim[,2])\n \n h_2<-dat/h2-dat\n fix1<-rnorm(nrow(back),0,sqrt(h_2))\n sim_<-data.frame(ecot_id=as.integer(rownames(back)),value=first+fix1)\n \n \n for ( t in 1:length(ve)) {\n beta<-sqrt((ve[t]/(1-ve[t]))*(var(sim_[,2])/var(caus[,t])))\n \n cand<-beta*caus[,t]\n sim_$value<-sim_$value+cand\n \n }\n Sim[[u]]<-sim_\n Caus[[u]]<-colnames(caus)[1:t]\n}\n }else {\n for ( u in 2:n ) {\n set.seed(seed+u)\n \n caus<-X_ok[,sample(1:ncol(X_ok),(no_snps+1))]\n \n #generating polygenic background\n \n X3<-X_ok[,!colnames(X_ok)%in%colnames(caus)]\n \n back<-X3[,sample(1:ncol(X3),1000)]\n \n betas<-rnorm(1000,mean=0,sd=0.1)\n first<- back %*% betas\n ### adding genetic background to data\n sim<-data.frame(ecot_id=as.integer(rownames(back)),value=first)\n ### set heritability \n dat<-var(sim[,2])\n \n h_2<-dat/h2-dat\n fix1<-rnorm(nrow(back),0,sqrt(h_2))\n sim_<-data.frame(ecot_id=as.integer(rownames(back)),value=first+fix1)\n \n \n for ( t in 1:length(ve)) {\n beta<-sqrt((ve[t]/(1-ve[t]))*(var(sim_[,2])/var(caus[,t])))\n \n cand<-beta*caus[,t]\n sim_$value<-sim_$value+cand\n \n }\n Sim[[u]]<-sim_\n Caus[[u]]<-colnames(caus)[1:t]\n}\n}\n\nreturn(list(Y=Sim,Caus=Caus))\n}\n", "meta": {"hexsha": "34af644036934f391a99299e0c8a7ca76adcb02e", "size": 3881, "ext": "r", "lang": "R", "max_stars_repo_path": "sim_Y.r", "max_stars_repo_name": "kevinfrsartori/GWAS", "max_stars_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sim_Y.r", "max_issues_repo_name": "kevinfrsartori/GWAS", "max_issues_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sim_Y.r", "max_forks_repo_name": "kevinfrsartori/GWAS", "max_forks_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5821917808, "max_line_length": 185, "alphanum_fraction": 0.6694150992, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.474272845227191}} {"text": "#' ms2knots\n#'\n#' Conversion speed meter per second in knot per second.\n#'\n#' @param numeric ms Speed in meter per second [m/s].\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords ms2knots \n#' \n#' @export\n#'\n#'\n#'\n#'\n\nms2knots<-function(ms)\n{\n return(ms * 1.94384);\n}", "meta": {"hexsha": "2b4b7824e925ca7f8b8a0a50b4219823c469e0e2", "size": 353, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ms2knots.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/ms2knots.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ms2knots.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8095238095, "max_line_length": 101, "alphanum_fraction": 0.6458923513, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47356631789161235}} {"text": "\nrm(list = ls())\ngc()\nset.seed(1954)\n\n# Adjust to your settings.\n.libPaths(\"~/Rlib/\")\nsetwd(\"~/Code/ising_model/scripts/\")\n\nlibrary(ggplot2)\nlibrary(posterior)\nsource(\"tools.r\")\nsource(\"algorithms.r\")\nsource(\"algorithms_potts.r\")\n\n## Tuning parameters for experiments\n# For Potts model with q = 4.\nn_states <- 4\n# beta_range <- c(0.25, 0.45, 0.5493062, 0.65, 0.85) # grid graph\n# beta_range <- c(1.35, 1.55, 1.647918, 1.75, 1.95) # complete graph (q = 4)\n# beta_range <- c(0.5, 0.8, 1, 1.2, 2) # gaussian graph\n# beta_range <- c(0.25, 0.44, 0.63)\n# beta_range <- c(0.5, 1, 1.5) # complete graph for q = 2\nbeta_range <- rep(1, 14) # hopfield model\n\nn_beta <- length(beta_range)\n# Options for graph types: \"complete\", \"grid\", \"gaussian\", \"hopfield\"\n# m_hopfield parameter is only relevant for Hopfield model\nm_hopfield <- c(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 256)\n # c(1) # c(150, 200) # c(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)\ngraph_types <- rep(\"hopfield\", n_beta)\nanti_corr <- FALSE\ngraph_sizes <- rep(256, n_beta)\nanti_corr <- rep(FALSE, n_beta)\n\nn_iter <- 1e4\nn_chains <- 4 # need multiple chains for diagnostics\ntotal_sample <- n_iter * n_chains\n\n# For Gaussian graphs, Wolff and SW cannot be used.\n# algo_names <- c(\"AG_potts\", \"HB\", \"Wolff\", \"SW\", \"AG_potts_lowrank\") # complete\n# algo_names <- c(\"AG_potts\", \"HB\") # Gaussian\nalgo_names <- c(\"AG_potts\", \"HB\", \"AG_potts_lowrank\")\n# algo_names <- c(\"AG_potts\", \"HB\", \"Wolff\", \"SW\", \"AG_potts_lowrank\")\nn_algorithms <- length(algo_names)\n\n# Number of generated quantities, based on samples\n# (for now only do one)\nn_gen_quant <- 2\nn_gen_sample <- n_iter / 2\n\nburn_in <- 1e3\n\nlength_graph_size <- length(graph_sizes)\nif (FALSE) {\n beta_range[1] <- 1.60\n length_graph_size <- 1 # only run one loop.\n}\n\nfor (k in 1:length_graph_size) {\n graph <- graph_types[k]\n n_part <- graph_sizes[k]\n beta <- beta_range[k]\n print(paste0(\"graph size: \", n_part, \", type: \", graph_types[k],\n \", beta: \", beta_range[k], \", anti_corr: \", anti_corr[k]))\n \n # Build adjacency graph\n A <- adjacency_graph(n_part, type = graph, anti_corr = anti_corr[k],\n m_hopfield = m_hopfield[k])\n \n init <- matrix(NA, nrow = n_chains, ncol = n_part)\n for (c in 1:n_chains) init[c, ] <- sample(1:n_states, n_part, replace = T)\n \n samples <- array(NA, c(n_iter, n_part, n_algorithms, n_chains))\n time <- rep(NA, n_algorithms)\n \n print(\"Doing AG sampling\")\n time[1] <- system.time(\n for (c in 1:n_chains) {\n samples[, , 1, c] <- ag_potts_simple(A = A, beta = beta, init = init[c, ],\n n_iter = n_iter, n_states = n_states)\n })[3]\n\n print(\"Doing HB sampling\")\n time[2] <- system.time(\n for (c in 1:n_chains) {\n samples[, , 2, c] <- hb_sampler(A = A, beta = beta, init = init[c, ],\n n_iter = n_iter, is_potts = TRUE, \n n_states = n_states,\n sub_sample = ceiling(n_part / 10))\n })[3]\n\n if (graph != \"gaussian\" & graph != \"hopfield\") {\n print(\"Doing Wolff sampling\")\n time[3] <- system.time(\n for (c in 1:n_chains) {\n samples[, , 3, c] <- wolff_sampler(A = A, beta = beta, init = init[c, ],\n n_iter = n_iter, is_potts = TRUE,\n n_states = n_states)\n })[3]\n\n print(\"Doing SW sampling\")\n time[4] <- system.time(\n for (c in 1:n_chains) {\n samples[, , 4, c] <- sw_sampler(A = A, beta = beta, init = init[c, ],\n n_iter = n_iter, is_potts = TRUE,\n n_states = n_states)\n })[3]\n }\n\n if (graph == \"complete\" || graph == \"hopfield\") {\n print(\"Doing AG lowrank sampling\")\n if (graph == \"complete\") index = 5\n if (graph == \"hopfield\") index = 3\n \n # REMARK: default epsilon = 1e-12 doesn't remove approximatively 0 eigenvalues.\n time[index] <- system.time(\n for (c in 1:n_chains) {\n samples[, , index, c] <- ag_potts_lowrank(A = A, beta = beta, init = init[c, ],\n n_states = n_states, n_iter = n_iter,\n alpha_modif = 0,\n epsilon = 1e-5)\n })[3]\n }\n\n all_samples <- array(NA, dim = c(total_sample, n_part, n_algorithms))\n for (c in 1:n_chains) {\n iteration_index <- ((c - 1) * n_iter + 1):(c * n_iter)\n all_samples[iteration_index, , ] <- samples[, , , c]\n }\n \n gen_quant <- array(NA, c(n_gen_sample, n_algorithms, n_chains, n_gen_quant))\n index_start <- n_iter - n_gen_sample + 1\n print(\"Computing generated quantities.\")\n for (j in 1:n_algorithms) {\n for (c in 1:n_chains) {\n for (i in 1:n_gen_sample) {\n gen_quant[i, j, c, 1] <- potts_log_kernel(beta, A, \n samples[index_start - 1 + i, , j, c])\n gen_quant[i, j, c, 2] <- gen_quant[i, j, c, 1]\n }\n }\n }\n\n # Compute the effective samples size and results\n mean <- array(NA, dim = c(n_gen_quant, n_algorithms))\n mcse <- array(NA, dim = c(n_gen_quant, n_algorithms))\n rhat <- array(NA, dim = c(n_gen_quant, n_algorithms))\n ess <- array(NA, dim = c(n_gen_quant, n_algorithms))\n eff <- array(NA, dim = c(n_gen_quant, n_algorithms))\n\n for (j in 1:n_algorithms) {\n draws_formatted <- as_draws_df(gen_quant[, j, , ])\n names(draws_formatted)[1] <- c(\"log_kernel\")\n summary <- summarize_draws(draws_formatted,\n measure = c(\"mean\", \"mcse_mean\", \"ess_bulk\", \"rhat\"))\n names(summary) <- c(\"variable\", \"mean\", \"mcse_mean\", \"ess_bulk\", \"rhat\")\n mean[, j] <- summary$mean\n mcse[, j] <- summary$mcse_mean\n rhat[, j] <- summary$rhat\n ess[, j] <- summary$ess_bulk # / total_sample * 1e3\n eff[, j] <- ess[, j] / time[j] # (time[j] * 1e3 / total_sample)\n # Note: returns ESS / time, and corrects for the fact ess is the number\n # of effectively independent samples per 1000 iterations.\n }\n\n eff_data <- data.frame(cbind(mean, mcse, rhat, ess, eff))\n names(eff_data) <- c(paste0(\"mean_\", algo_names), paste0(\"mcse_\", algo_names),\n paste0(\"rhat_\", algo_names),\n paste0(\"ess_\", algo_names), paste0(\"eff_\", algo_names))\n\n output_name <- paste0(\"deliv/measurements/potts/\", n_part, graph,\n \"_\", beta, \"_\", n_states, \"_\", m_hopfield[k], \"_efficiency\")\n write.csv(eff_data, paste0(output_name, \".csv\"))\n}\n", "meta": {"hexsha": "0847f263a55664916926ede64eb751a7024b2b92", "size": 6594, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/performance_potts_test.r", "max_stars_repo_name": "charlesm93/potts_simulation", "max_stars_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-21T16:25:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T16:25:09.000Z", "max_issues_repo_path": "scripts/performance_potts_test.r", "max_issues_repo_name": "charlesm93/potts_simulation", "max_issues_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/performance_potts_test.r", "max_forks_repo_name": "charlesm93/potts_simulation", "max_forks_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4659090909, "max_line_length": 87, "alphanum_fraction": 0.5708219594, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4734209172011089}} {"text": "#!/usr/bin/Rscript\n\n# friedman.post.hoc.simple(t(amg2$mean))$ranks\n# friedman.post.hoc.simple(t(r$succRatio[1:4,]),minFlag=F)\n# friedman.post.hoc.simple(t(r$mean[1:4,]))\n\n#\" \n#Useful commands:\n#source(\"friedman.r\"); r <- friedman.post.hoc.meth.bench(\"intsp.csv\", minFlag=FALSE)\n#source(\"friedman.r\"); r <- friedman.post.hoc.meth.bench(\"strp.csv\", minFlag=FALSE)\n#sort(r$ranks)\n#r$p.value\n#r$cmp.matrix\n#r$cmp.p.values\n#r$cmp.p.values\n#r$p.value\n#r$cmp.matrix\n#\"\n\n\n\n\n\nfriedman.post.hoc.meth.bench <- function(fname, minFlag=TRUE)\n{\n# KK\n# reads a csv file of the form: methods x benchmarks\n# transforms a table into format expected by friedman.post and calls friedman.post\n# set minFlag to true if the variable is minimized, otherwise to false\n\n options(width=10000) # prevent the wrapping of output\n #options(width=300)\n\n options(digits=2)\n\t b <- read.csv(file=fname, header=TRUE, sep=\";\", row.names=1, check.names=FALSE)\n b <- b[rownames(b) != \"All\", ]\n b <- t(b)\n\tprint(summary(b))\n\tr <- friedman.post.hoc.simple(b,minFlag)\n print(sort(r$ranks))\n r #sort(r.ranks)\n}\n\n## Does Friedman from dataframe\nfriedman.post.hoc.simple <- function(df, minFlag=T,...) {\n\tres <- data.frame(var=rep(NA, 0), alg=rep(\"\", 0), \n\t\tblock=rep(\"\", 0), stringsAsFactors=FALSE, check.names=FALSE)\n i = 1\n print(df)\n\tfor(r in 1:nrow(df))\n\t\tfor(c in 1:ncol(df))\n\t\t{\n\t\t\tres[i,1] = df[r,c]\n\t\t\tres[i,2] = row.names(df)[r]\n\t\t\tres[i,3] = colnames(df)[c]\n\t\t\ti=i+1\t\t\t\n\t\t}\n\tfriedman.post.hoc (var ~ alg | block, data=res,minimize=minFlag, ...)\n}\n\nfriedman.post.hoc <- function(formu, data, minimize=TRUE, p.signif=0.05, post.signif=p.signif, ctrl=NULL, method=NULL)\n{\n\t# \n\t# formu is a formula of the shape: \tY ~ X | block i.e.: Value ~ Algorithm | Problemf\n\t# data is a long data.frame with three columns:\t[[ Y (numeric), X (factor), block (factor) ]]\n\n\t# get the names out of the formula\n\tformu.names <- all.vars(formu)\n\tY.name <- formu.names[1]\n\tX.name <- formu.names[2]\n\tblock.name <- formu.names[3]\n\t\n\tX <- factor(data[,X.name ])\n\tY <- data[,Y.name]\n\tblock <- factor(data[,block.name ])\n\t\t\t\n\tn <- nlevels(block)\n\tk <- nlevels(X)\n\t\n\tif(sum(is.na(Y)) > 0) stop(\"Function stopped: This function doesn't handle NA's. In case of NA in Y in one of the blocks, then that entire block should be removed.\")\n\tif(k == 2) { warning(paste(\"'\",X.name,\"'\", \"has only two levels. Consider using paired wilcox.test instead of friedman test\"))}\n\n\t# convert data.frame to matrix\n\tvalues <- matrix(nrow=n, ncol=k, dimnames=list(levels(block), levels(X)))\n\tvalues[cbind(block, X)] <- Y\n\t\n\tranks.in.blocks <- t(apply(if (minimize) values else -values, 1, rank))\n\trmean <- mean(ranks.in.blocks)\n\tranks <- apply(ranks.in.blocks, 2, mean)\n\t\n\tFf <- n*(k-1)*(n*sum((ranks-rmean)^2))/(sum((ranks.in.blocks-rmean)^2))\n\tp.value <- pchisq(Ff, k-1, lower.tail=F)\n\t\n\tif (p.value < p.signif)\n\t{\n\t\tif (is.null(ctrl)) {\n\t\t\t# NxN\n\t\t\t#stop(\"NxN posthoc not implemented yet\")\n\t\t\tmethod <- match.arg(method, c('shaffer', p.adjust.methods))\n\t\t\t\n\t\t\t#z <- outer(1:k,1:k, function(a,b) abs(ranks[a]-ranks[b]) / sqrt((k*(k+1))/(6*n)))\n\t\t\trowidx <- unlist(lapply(2:k, function(x) x:k))\n\t\t\tcolidx <- rep(1:(k-1), (k-1):1)\n\t\t\tz <- abs(ranks[rowidx] - ranks[colidx]) / sqrt((k*(k+1))/(6*n))\t\t\t\n\t\t\tp <- 2*pnorm(-z)\n\t\t\n\t\t\tcmp.p.values <- switch(method,\n\t\t\t\t\tshaffer = {\n\t\t\t\t\t\tShafferH <- function(k) {\n\t\t\t\t\t\t\tif (k <= 1) return(0)\n\t\t\t\t\t\t\tS <- vector(\"list\", k)\n\t\t\t\t\t\t\tS[[1]] <- 0\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (i in 2:k) {\n\t\t\t\t\t\t\t\tres <- choose(i, 2)\n\t\t\t\t\t\t\t\tfor (j in (i-1):1) res <- union(res, choose(j, 2) + S[[i-j]])\n\t\t\t\t\t\t\t\tS[[i]] <- res\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn(sort(S[[k]]))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\ti <- seq_len(length(p))\n\t\t\t\t\t\to <- order(p)\n\t\t\t\t\t\tro <- order(o)\n\t\t\t\t\t\tm <- k*(k-1)/2\n\t\t\t\t\t\t\n\t\t\t\t\t\tval <- matrix(nrow=k,ncol=k)\n\t\t\t\t\t\t#val[lower.tri(val)] <- p.adjust(p) # Homel\n\t\t\t\t\t\t#val[lower.tri(val)] <- pmin(1, cummax( (m - i + 1L) * p[o] ))[ro] # Homel\n\t\t\t\t\t\t\n\t\t\t\t\t\tH <- ShafferH(k)\n\t\t\t\t\t\tval[lower.tri(val)] <- pmin(1, cummax( unlist(lapply(0:(m-1), function(x) max(H[H<=(m-x)]))) * p[o] ))[ro] # Shaffer's static S1\n\t\t\t\t\t\tval\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tval <- matrix(nrow=k,ncol=k)\n\t\t\t\t\t\tval[lower.tri(val)] <- p.adjust(p)\n\t\t\t\t\t\tval\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t\n\t\t\tcmp.p.values[upper.tri(cmp.p.values)] <- t(cmp.p.values)[upper.tri(cmp.p.values)]\n\t\t\tcmp.matrix <- matrix(ifelse(cmp.p.values < p.signif, outer(1:k,1:k, function(a,b) sign(ranks[b]-ranks[a])), 0), nrow=k,ncol=k)\n\t\t\tdimnames(cmp.p.values) <- dimnames(cmp.matrix) <- list(levels(X), levels(X))\t\t\t\n\t\t} else {\n\t\t\t# 1xN\n\t\t\tif (is.character(ctrl))\n\t\t\t\tctrl <- match(ctrl, names(ranks))\n\t\t\tz <- abs(ranks[ctrl]-ranks[-ctrl]) / sqrt((k*(k+1))/(6*n))\n\t\t\tp <- 2*pnorm(-z)\n\t\t\t\n\t\t\tif (is.null(method)) method <- 'holm';\n\t\t\tcmp.p.values <- matrix(p.adjust(p, method=method), nrow=1, dimnames=list(names(ranks)[ctrl], names(p)))\n\t\t\tcmp.matrix <- ifelse(cmp.p.values < p.signif, sign(ranks[-ctrl] - ranks[ctrl]), 0)\n\t\t\t\n\t\t}\n\t\t\n\t\treturn(list(statistic=Ff, parameter=k-1, p.value=p.value, ranks=ranks, cmp.p.values=cmp.p.values, cmp.matrix=cmp.matrix, cmp.method=method))\n\t} else return(list(statistic=Ff, parameter=k-1, p.value=p.value, ranks=ranks))\n}\n# friedman.post.hoc(successes ~ method | problem, sstab, minimize=FALSE, ctrl=c('X_A0.2','X_A0.3'))\n# \n# friedman.post.hoc(successes ~ method | problem, sstab, minimize=FALSE)\n# \n# friedman.post.hoc(successes ~ method | problem, sstab, minimize=FALSE, ctrl='X_A0.2')\n# \n# friedman.post.hoc(successes ~ method | problem, sstab, minimize=FALSE, ctrl=c('X_A0.2','X_A0.3'))\n# \n# friedman.post.hoc(successes ~ method | problem, sstab)\n\n\n#################################\n\nargs <- commandArgs(trailingOnly = TRUE)\nfriedman.post.hoc.meth.bench(args[1], minFlag=args[2])\n\n#friedman.post.hoc.meth.bench(\"tmp.csv\", minFlag=FALSE)\n\n#r <- friedman.post.hoc.meth.bench(\"table-success-small.csv\", minFlag=FALSE)\n#sort(r$ranks)\n#r$p.value\n#r$cmp.matrix\n#r$cmp.p.values\n#source(\"friedman.r\"); r <- friedman.post.hoc.meth.bench(\"strp.csv\", minFlag=FALSE)\n\n", "meta": {"hexsha": "8650d61b808b6561a13250ec8df4120cf25a46ca", "size": 6011, "ext": "r", "lang": "R", "max_stars_repo_path": "evoplotter/stats/friedman_kk.r", "max_stars_repo_name": "iwob/evoplotter", "max_stars_repo_head_hexsha": "816f1b19bf6656c1ac35bc9dbe8c090a6325f5a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-03T07:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-03T07:44:06.000Z", "max_issues_repo_path": "evoplotter/stats/friedman_kk.r", "max_issues_repo_name": "iwob/evoplotter", "max_issues_repo_head_hexsha": "816f1b19bf6656c1ac35bc9dbe8c090a6325f5a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evoplotter/stats/friedman_kk.r", "max_forks_repo_name": "iwob/evoplotter", "max_forks_repo_head_hexsha": "816f1b19bf6656c1ac35bc9dbe8c090a6325f5a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1443850267, "max_line_length": 166, "alphanum_fraction": 0.6070537348, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.47313510630522454}} {"text": "#!/usr/bin/env Rscript\n\n# ypar\n# reference for main analysis: https://github.com/chr1swallace/coloc\n\n\nargs = commandArgs(trailingOnly=TRUE)\nprint(args)\n\nlibrary(dplyr)\nlibrary(data.table)\nlibrary(coloc)\n\nVar.data <- function(f, N) {\n 1 / (2 * N * f * (1 - f))\n}\n\nVar.data.cc <- function(f, N, s) {\n 1 / (2 * N * f * (1 - f) * s * (1 - s))\n}\n\nlogsum <- function(x) {\n my.max <- max(x) ##take out the maximum value in log form\n my.res <- my.max + log(sum(exp(x - my.max )))\n return(my.res)\n}\n\nlogdiff <- function(x,y) {\n my.max <- max(x,y) ##take out the maximum value in log form\n my.res <- my.max + log(exp(x - my.max ) - exp(y-my.max))\n return(my.res)\n}\n\napprox.bf.p <- function(p,f,type, N, s, suffix=NULL) {\n if(type==\"quant\") {\n sd.prior <- 0.15\n V <- Var.data(f, N)\n } else {\n sd.prior <- 0.2\n V <- Var.data.cc(f, N, s)\n }\n z <- qnorm(0.5 * p, lower.tail = FALSE)\n ## Shrinkage factor: ratio of the prior variance to the total variance\n r <- sd.prior^2 / (sd.prior^2 + V)\n ## Approximate BF # I want ln scale to compare in log natural scale with LR diff\n lABF = 0.5 * (log(1-r) + (r * z^2))\n ret <- data.frame(V,z,r,lABF)\n if(!is.null(suffix))\n colnames(ret) <- paste(colnames(ret), suffix, sep=\".\")\n return(ret)\n}\n\napprox.bf.estimates <- function (z, V, type, suffix=NULL, sdY=1) {\n sd.prior <- if (type == \"quant\") { 0.15*sdY } else { 0.2 }\n r <- sd.prior^2/(sd.prior^2 + V)\n lABF = 0.5 * (log(1 - r) + (r * z^2))\n ret <- data.frame(V, z, r, lABF)\n if(!is.null(suffix))\n colnames(ret) <- paste(colnames(ret), suffix, sep = \".\")\n return(ret)\n}\n\ncombine.abf <- function(l1, l2, p1, p2, p12) {\n lsum <- l1 + l2\n lH0.abf <- 0\n lH1.abf <- log(p1) + logsum(l1)\n lH2.abf <- log(p2) + logsum(l2)\n lH3.abf <- log(p1) + log(p2) + logdiff(logsum(l1) + logsum(l2), logsum(lsum))\n lH4.abf <- log(p12) + logsum(lsum)\n\n all.abf <- c(lH0.abf, lH1.abf, lH2.abf, lH3.abf, lH4.abf)\n my.denom.log.abf <- logsum(all.abf)\n pp.abf <- exp(all.abf - my.denom.log.abf)\n names(pp.abf) <- paste(\"PP.H\", (1:length(pp.abf)) - 1, \".abf\", sep = \"\")\n print(signif(pp.abf,3))\n print(paste(\"PP abf for shared variant: \", signif(pp.abf[\"PP.H4.abf\"],3)*100 , '%', sep=''))\n return(pp.abf)\n}\n\nsdY.est <- function(vbeta, maf, n) {\n warning(\"estimating sdY from maf and varbeta, please directly supply sdY if known\")\n oneover <- 1/vbeta\n nvx <- 2 * n * maf * (1-maf)\n m <- lm(nvx ~ oneover - 1)\n cf <- coef(m)[['oneover']]\n if(cf < 0)\n stop(\"estimated sdY is negative - this can happen with small datasets, or those with errors. A reasonable estimate of sdY is required to continue.\")\n return(sqrt(cf))\n}\n\nprocess.dataset <- function(d, suffix) {\n #message('Processing dataset')\n\n nd <- names(d)\n if (! 'type' %in% nd)\n stop(\"dataset \",suffix,\": \",'The variable type must be set, otherwise the Bayes factors cannot be computed')\n\n if(!(d$type %in% c(\"quant\",\"cc\")))\n stop(\"dataset \",suffix,\": \",\"type must be quant or cc\")\n\n if(d$type==\"cc\") {\n if(! \"s\" %in% nd)\n stop(\"dataset \",suffix,\": \",\"please give s, proportion of samples who are cases\")\n if(\"pvalues\" %in% nd && !( \"MAF\" %in% nd))\n stop(\"dataset \",suffix,\": \",\"please give MAF if using p values\")\n if(d$s<=0 || d$s>=1)\n stop(\"dataset \",suffix,\": \",\"s must be between 0 and 1\")\n }\n\n if(d$type==\"quant\") {\n if(!(\"sdY\" %in% nd || (\"MAF\" %in% nd && \"N\" %in% nd )))\n stop(\"dataset \",suffix,\": \",\"must give sdY for type quant, or, if sdY unknown, MAF and N so it can be estimated\")\n }\n\n if(\"beta\" %in% nd && \"varbeta\" %in% nd) { ## use beta/varbeta. sdY should be estimated by now for quant\n if(length(d$beta) != length(d$varbeta))\n stop(\"dataset \",suffix,\": \",\"Length of the beta vectors and variance vectors must match\")\n if(!(\"snp\" %in% nd))\n d$snp <- sprintf(\"SNP.%s\",1:length(d$beta))\n if(length(d$snp) != length(d$beta))\n stop(\"dataset \",suffix,\": \",\"Length of snp names and beta vectors must match\")\n\n if(d$type==\"quant\" && !('sdY' %in% nd))\n d$sdY <- sdY.est(d$varbeta, d$MAF, d$N)\n df <- approx.bf.estimates(z=d$beta/sqrt(d$varbeta),\n V=d$varbeta, type=d$type, suffix=suffix, sdY=d$sdY)\n df$snp <- as.character(d$snp)\n return(df)\n }\n\n if(\"pvalues\" %in% nd & \"MAF\" %in% nd & \"N\" %in% nd) { ## no beta/varbeta: use p value / MAF approximation\n if (length(d$pvalues) != length(d$MAF))\n stop('Length of the P-value vectors and MAF vector must match')\n if(!(\"snp\" %in% nd))\n d$snp <- sprintf(\"SNP.%s\",1:length(d$pvalues))\n df <- data.frame(pvalues = d$pvalues,\n MAF = d$MAF,\n snp=as.character(d$snp))\n colnames(df)[-3] <- paste(colnames(df)[-3], suffix, sep=\".\")\n df <- subset(df, df$MAF>0 & df$pvalues>0) # all p values and MAF > 0\n abf <- approx.bf.p(p=df$pvalues, f=df$MAF, type=d$type, N=d$N, s=d$s, suffix=suffix)\n df <- cbind(df, abf)\n return(df)\n }\n\n stop(\"Must give, as a minimum, one of:\\n(beta, varbeta, type, sdY)\\n(beta, varbeta, type, MAF)\\n(pvalues, MAF, N, type)\")\n}\n\ncoloc.abf <- function(dataset1, dataset2, MAF=NULL,\n p1=1e-4, p2=1e-4, p12=1e-5) {\n\n if(!is.list(dataset1) || !is.list(dataset2))\n stop(\"dataset1 and dataset2 must be lists.\")\n if(!(\"MAF\" %in% names(dataset1)) & !is.null(MAF))\n dataset1$MAF <- MAF\n if(!(\"MAF\" %in% names(dataset2)) & !is.null(MAF))\n dataset2$MAF <- MAF\n\n df1 <- process.dataset(d=dataset1, suffix=\"df1\")\n df2 <- process.dataset(d=dataset2, suffix=\"df2\")\n # the na.omit is the fix here:\n merged.df <- na.omit(merge(df1,df2))\n\n if(!nrow(merged.df))\n stop(\"dataset1 and dataset2 should contain the same snps in the same order, or should contain snp names through which the common snps can be identified\")\n\n merged.df$internal.sum.lABF <- with(merged.df, lABF.df1 + lABF.df2)\n ## add SNP.PP.H4 - post prob that each SNP is THE causal variant for a shared signal\n my.denom.log.abf <- logsum(merged.df$internal.sum.lABF)\n merged.df$SNP.PP.H4 <- exp(merged.df$internal.sum.lABF - my.denom.log.abf)\n\n pp.abf <- combine.abf(merged.df$lABF.df1, merged.df$lABF.df2, p1, p2, p12)\n common.snps <- nrow(merged.df)\n results <- c(nsnps=common.snps, pp.abf)\n\n output<-list(summary=results, results=merged.df)\n return(output)\n}\n\n############################## above here are general coloc package functions\n\n\n# example file\n# due to constraints in the computing environment,\n# individual genes were tested first before parallelization\n\n# head -2 input_per_gene/Whole_Blood/Coronary_Artery_Disease/ENSG00000000457.13_for_coloc.txt\n# gene_id\teqtl_variant_id\ttss_distance\teqtl_ma_samples\teqtl_ma_count\teqtl_maf\teqtl_pval_nominal\teqtl_slope\teqtl_slope_se\ttissue\teqtl_sample_size\tgwas_variant_id\tchromosome\tposition\teqtl_effect_allele\teqtl_non_effect_allele\tcurrent_build\tfrequency\tgwas_sample_size\tgwas_zscore\tgwas_pvalue\tgwas_effect_size\tgwas_standard_error\tgwas_imputation_status\tgwas_n_cases\ttrait\n# ENSG00000000457.13\tchr1_168894411_A_T_b38\t-999856\t30\t30\t0.0223881\t0.4447680000000001\t0.0509097\t0.0665773\tWhole_Blood\t670\trs114383479\tchr1\t168894411\tT\tA\thg38\t0.023088023088023088\t184305\t1.3586797714233398\t0.17424808484624\tNA\tNA\timputed\t60801\tCoronary_Artery_Disease\n\n# this script assumes input files contains per-gene or per-ldblock variants only\n\n# inputfile = 'ENSG00000000457.13_for_coloc.txt'\ninputfile = args[1]\ntissueid = args[2]\ntraitid = args[3]\n\nworkdir = '/project/chrbrolab/gtex/coloc_v8/'\n# inputdir = paste(workdir, 'input_per_gene/', sep='')\noutputdir = paste(workdir, 'output_per_gene_eur/', tissueid, '/', traitid, '/', sep='')\n# file names are changed to reflect new pheno labels\npriorsfile = 'ypark_enloc_enrichment_and_prior_estimation_results.txt'\n\ngeneid = unlist(strsplit(inputfile, '_for_'))[1]\n\nprint(c(tissueid, traitid, geneid))\n\n# before organizing\n# inputdir = paste(workdir, 'input_per_gene/', sep='')\n# after organizing\ninputdir = paste(workdir, 'input_per_gene_eur/', tissueid, '/', traitid, '/', sep='')\noutfile = paste(outputdir, geneid, '_coloc_output_file.txt', sep='')\noutput = c()\n\ninputdata = tbl_df(fread(paste(inputdir, inputfile, sep='')))\ninputdata = inputdata[inputdata$frequency > 0,]\ninputdata$gwas_varbeta = 1\n\ninputdata = inputdata %>% filter(complete.cases(gwas_zscore)) %>% mutate(max_gwas_zscore = max(abs(gwas_zscore)))\ninputdata = inputdata %>% arrange(desc(abs(gwas_zscore)))\n\npriors = tbl_df(fread(paste(workdir, priorsfile, sep='')))\npriorsused = priors %>% filter(trait == traitid & tissue == tissueid)\np1used = priorsused$p1_trait_prior\np2used = priorsused$p2_tissue_prior\np12used = priorsused$p12\n\n# eqtlinput = list(beta = inputdata$eqtl_slope, varbeta = (inputdata$eqtl_slope_se)**2, N = inputdata$eqtl_sample_size, type = 'quant', snp = inputdata$eqtl_variant_id, MAF = inputdata$eqtl_maf)\neqtlinput = list(pvalues = inputdata$eqtl_pval_nominal, N = inputdata$eqtl_sample_size, type = 'quant', snp = inputdata$eqtl_variant_id, MAF = inputdata$frequency)\n\n\ncaseproportion = inputdata$gwas_n_cases/inputdata$gwas_sample_size\ndatatype = ifelse(is.na(caseproportion[1]), 'quant', 'cc')\n\nif(datatype == 'quant') {\n gwasinput = list(beta = inputdata$gwas_zscore, varbeta = inputdata$gwas_varbeta, N = inputdata$gwas_sample_size, type = datatype, snp = inputdata$eqtl_variant_id, MAF = inputdata$frequency)\n} else {\n gwasinput = list(beta = inputdata$gwas_zscore, varbeta = inputdata$gwas_varbeta, N = inputdata$gwas_sample_size, type = datatype, snp = inputdata$eqtl_variant_id, MAF = inputdata$frequency, s = caseproportion)\n}\n\n# if(datatype == 'quant') {\n# gwasinput = list(pvalues = inputdata$gwas_pvalue, N = inputdata$gwas_sample_size, type = datatype, snp = inputdata$eqtl_variant_id, MAF = inputdata$frequency)\n# } else {\n# gwasinput = list(pvalues = inputdata$gwas_pvalue, N = inputdata$gwas_sample_size, type = datatype, snp = inputdata$eqtl_variant_id, MAF = inputdata$frequency, s = caseproportion)\n# }\n\n# priors were stored in a table like this:\n# tissue\ttrait\tp1_trait_prior\tp2_tissue_prior\tp12\tpm1\tpm2\tenloc_enrich_intercept_effect(inteffect)\tinteffect_95ci_lower\tinteffect_95ci_upper\tenloc_enrich_log_odds_ratio_effect(logor)\tlogor_95ci_lower\tlogor_95ci_upper\n# Adipose_Subcutaneous\tAdiponectin\t7.31680E-06\t3.32503E-03\t3.05385E-08\t7.34734E-06\t3.32506E-03\t-11.822\t-11.849\t-11.795\t0.224\t-2.384\t2.832\n# Adipose_Subcutaneous\tAlzheimers_Disease\t1.32258E-05\t3.32490E-03\t1.60605E-07\t1.33864E-05\t3.32506E-03\t-11.230\t-11.409\t-11.052\t1.292\t-2.956\t5.540\n\nruncoloc = coloc.abf(gwasinput, eqtlinput, p1=p1used, p2=p2used, p12=p12used)\noutput = rbind(output, c(unlist(inputdata[1,]), runcoloc$summary))\noutput = as.data.table(output)\n\noutput = mutate(output, PP.H1.abf = ifelse(PP.H0.abf == 1, 0, PP.H1.abf))\noutput = mutate(output, PP.H2.abf = ifelse(PP.H0.abf == 1, 0, PP.H2.abf))\noutput = mutate(output, PP.H3.abf = ifelse(PP.H0.abf == 1, 0, PP.H3.abf))\noutput = mutate(output, PP.H4.abf = ifelse(PP.H0.abf == 1, 0, PP.H4.abf))\n\noutputdata = tbl_df(as.data.frame(output)) %>% mutate(PP.H4.abf = as.numeric(as.character(PP.H4.abf))) %>% arrange(desc(PP.H4.abf))\nwrite.table(outputdata, file=outfile, quote=F, col.names=T, row.names=F, sep='\\t')\n\n\n\n\n", "meta": {"hexsha": "6933dffc62ea8843ac4c44f89840efe58f466413", "size": 11289, "ext": "r", "lang": "R", "max_stars_repo_path": "coloc-stuff/run_coloc_crossinput_eurpairs.r", "max_stars_repo_name": "ypar/gwas-qtl-stuff", "max_stars_repo_head_hexsha": "f0466fd406b0ce04f251052672b7d49ad8fdc146", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coloc-stuff/run_coloc_crossinput_eurpairs.r", "max_issues_repo_name": "ypar/gwas-qtl-stuff", "max_issues_repo_head_hexsha": "f0466fd406b0ce04f251052672b7d49ad8fdc146", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coloc-stuff/run_coloc_crossinput_eurpairs.r", "max_forks_repo_name": "ypar/gwas-qtl-stuff", "max_forks_repo_head_hexsha": "f0466fd406b0ce04f251052672b7d49ad8fdc146", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2808988764, "max_line_length": 366, "alphanum_fraction": 0.6646292851, "num_tokens": 3798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4730586380008109}} {"text": "###############################################################################\n# Copyright (C) 1994 - 2009, Performance Dynamics Company #\n# #\n# This software is licensed as described in the file COPYING, which #\n# you should have received as part of this distribution. The terms #\n# are also available at http://www.perfdynamics.com/Tools/copyright.html. #\n# #\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell #\n# copies of the Software, and permit persons to whom the Software is #\n# furnished to do so, under the terms of the COPYING file. #\n# #\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY #\n# KIND, either express or implied. #\n###############################################################################\n\n# Load the library\nlibrary(\"pdq\")\n#\n# T/put bounds for closed tandem QNM with increasing Z\n# Created by NJG on Fri Feb 27, 2009\n#\nclients = 300\nthinkZ = 800 * 10^(-3) # ms as seconds\nstime = 20 * 10^(-3) # ms as seconds\nnode1 = \"n1\"\nnode2 = \"n2\"\nnode3 = \"n3\"\nwork = \"w\"\nfor(z in 1:3) {\n xc<-0 # prudent to reset these\n yc<-0\n for (i in 1:clients) {\n Init(\"\")\n if (z==1) {think<-thinkZ * 0}\n if (z==2) {think<-thinkZ * 2}\n if (z==3) {think<-thinkZ * 4}\n CreateClosed(work, TERM, as.double(i), think) \n CreateNode(node1, CEN, FCFS)\n CreateNode(node2, CEN, FCFS)\n CreateNode(node3, CEN, FCFS)\n SetDemand(node1, work, stime)\n SetDemand(node2, work, stime)\n SetDemand(node3, work, stime) \n Solve(APPROX)\n xc[i]<-as.double(i)\n yc[i]<-GetThruput(TERM, work)\n nopt<-(3*stime + think)/stime\n }\n if (z==1) {\n \t# establish plot frame and first curve\n plot(xc, yc, type=\"l\", ylim=c(0,1/stime), lwd=2, xlab=\"N Clients\", \n ylab=\"Throughput X(N)\")\n title(\"Increasing Z Values\")\n \tabline(0, 1/(nopt*stime), lty=\"dashed\", col = \"blue\")\n \tabline(1/stime, 0, lty=\"dashed\", col = \"red\")\n \tabline(v=nopt, lty=\"dashed\", col=\"gray50\")\n text(20+nopt, 35, paste(\"Z=\", as.numeric(think)))\n \ttext(3+nopt, 6, paste(\"N*=\", as.numeric(nopt)))\n } else {\n \t# add the other curves\n \tpoints(xc, yc, type=\"l\", lwd=2)\n \tabline(0, 1/(nopt*stime), lty=\"dashed\", col = \"blue\")\n \tabline(v=nopt, lty=\"dashed\", col=\"gray50\")\n \tformat(think, scientific = TRUE)\n \ttext(4+nopt, 35, paste(\"Z=\", as.numeric(think)))\n \ttext(3+nopt, 6, paste(\"N*=\", as.numeric(nopt)))\n }\n}\n\n\n", "meta": {"hexsha": "849a41c6d668340e38be54ff6be46c5967df12a1", "size": 2848, "ext": "r", "lang": "R", "max_stars_repo_path": "R/morez.r", "max_stars_repo_name": "peterlharding/PDQ", "max_stars_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:22:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T05:57:35.000Z", "max_issues_repo_path": "R/morez.r", "max_issues_repo_name": "peterlharding/PDQ", "max_issues_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/morez.r", "max_forks_repo_name": "peterlharding/PDQ", "max_forks_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-03-12T12:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-05T05:57:44.000Z", "avg_line_length": 40.1126760563, "max_line_length": 79, "alphanum_fraction": 0.4926264045, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4726705355631468}} {"text": "# Consensus Mechanism\n# Paul Sztorc\n# Written in R (v 3.1.1) using Rstudio (v 0.98.1028)\n\n# This is the mechanism that, theoretically,\n # 1] allows the software to determine the state of Decisions truthfully, and\n # 2] only allows an efficient number of most-traded-upon-Decisions.\n\n\n# To my knowledge, R does not feature 'automatic working directories' unless it is being run as a script\n# try(setwd(\"~/GitHub/Truthcoin/lib/consensus\"))\nsource(\"CustomMath.r\")\n\n## Functions:\n\nDemocracyRep <- function(X) {\n # Run this if no Reputations were given...gives everyone an equal share and equal vote.\n \n Dem_Rep <- ReWeight(rep(1,nrow(X)))\n return( Dem_Rep )\n}\n\n\nBinaryScales <- function(X, IndexOnly=FALSE) {\n # Run this if no Scales were provided..assumes none were Scaled, all are Binary (0 or 1).\n \n Bin_Scales <- matrix( c( rep(FALSE,ncol(X)),\n rep(0,ncol(X)),\n rep(1,ncol(X))), 3, byrow=TRUE, dimnames=list(c(\"Scaled\",\"Min\",\"Max\"),colnames(X)) )\n \n if(IndexOnly) return( as.logical( Bin_Scales[\"Scaled\",] ) )\n return( Bin_Scales )\n}\n\n\nGetDecisionOutcomes <- function(Mtemp, Rep = DemocracyRep(Mtemp), ScaledIndex = BinaryScales(Mtemp, TRUE), Verbose=FALSE) {\n # Determines the (raw) Outcomes of Decisions based on the provided reputation (weighted vote)\n \n if(Verbose) { print(\"****************************************************\") ; print(\"Begin 'GetDecisionOutcomes'\")}\n \n DecisionOutcomes.Raw <- 1:ncol(Mtemp) # Declare this (filled below)\n \n for(i in 1:ncol(Mtemp)) { \n #For each column: \n Row <- ReWeight(Rep[!is.na(Mtemp[,i])]) # The Reputation of the row-players who DID provide judgements, rescaled to sum to 1.\n Col <- Mtemp[!is.na(Mtemp[,i]),i] # The relevant Decision with NAs removed. (\"What these row-players had to say about the Decisions they DID judge.\")\n \n #Discriminate Based on Contract Type\n if(!ScaledIndex[i]) DecisionOutcomes.Raw[i] <- Row %*% Col # Our Current best-guess for this Binary Decision (weighted average) \n if(ScaledIndex[i]) DecisionOutcomes.Raw[i] <- weighted.median(w=Row, x=Col) # Our Current best-guess for this Scaled Decision (weighted median)\n \n if(Verbose) { print(\"** **\"); print(\"Column:\"); print(i); print(AsMatrix(Row)); print(Col); print(\"Consensus:\"); print(DecisionOutcomes.Raw[i]) }\n }\n \n #Output\n return(DecisionOutcomes.Raw)\n}\n\n# M <- matrix( data=c(\n# 1, 1, 0, 0, 0.5356322, 6.689658e-01,\n# 1, 0, 0, 0, 0.4574713, NA,\n# 1, 1, 0, 0, 0.5356322, 6.689658e-01,\n# 1, 1, 1, 0, 0.5747126, NA,\n# 0, 0, 1, 1, 1.0000000, 8.333333e-05,\n# 0, 0, 1, 1, 1.0000000, 9.999167e-01),\n# nrow=6,byrow=TRUE)\n\n# > GetDecisionOutcomes(Mtemp=M, ScaledIndex=c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE))\n# [1] 0.6666667 0.5000000 0.5000000 0.3333333 0.5551724 0.6689658\n# > GetDecisionOutcomes(Mtemp=M, ScaledIndex=c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE))\n# [1] 0.6666667 0.5000000 0.5000000 0.3333333 0.6839080 0.6689658\n# > GetDecisionOutcomes(Mtemp=M, ScaledIndex=c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE), Rep=c(.2,.2,.1,.4,.04,.06))\n# [1] 1.0000000 0.7000000 0.5000000 0.1000000 0.5820690 0.6517202\n\n\n\nGetRewardWeights <- function(M, Rep=DemocracyRep(M), ScaledIndex = BinaryScales(M, TRUE), alpha=.1, Tol=.2, Verbose=FALSE, RBCR=6) {\n # Calculates the new reputations using WPCA\n \n if(Verbose) {\n print(\"****************************************************\")\n print(\"Begin 'GetRewardWeights'\")\n print(\"Inputs...\")\n print(\"Matrix:\")\n print(M)\n print(\"\")\n print(\"Reputation:\")\n print(AsMatrix(Rep))\n print(\"\")\n }\n\n Results <- WeightedPrinComp(M,Rep)\n \n FirstLoading <- Results$Loadings #The first loading is designed to indicate which Decisions were more 'agreed-upon' than others. \n FirstScore <- Results$Scores #The scores show loadings on consensus (to what extent does this observation represent consensus?)\n \n if(Verbose) { print(\"First Loading:\"); print(FirstLoading); print(\"First Score:\"); print(AsMatrix(FirstScore)) }\n \n\n # Skip all of this if there is pefect consensus (ie, all people agree).\n \n # Declared here, filled below (unless there was a perfect consensus).\n NewRep <- Rep # By default, reputations don't change if everyone agrees.\n \n if( ! sum(abs(FirstScore))==0 ) {\n \n ## Choosing Among Two Score-Persepectives\n \n # Now we have some work to do on the FirstScore.\n \n # PCA, being an abstract factorization, is incapable of determining anything absolute.\n # Therefore the results of the entire procedure would theoretically be reversed if the average state of Decisions changed from TRUE to FALSE.\n # Because the average state of Decisions is a function both of randomness and the way the Decisions are worded, I check to see which of the\n # two possible 'new' reputation vectors had more opinion in common with the original 'old' reputation.\n \n \n \n # The two options:\n Option1 <- FirstScore + abs( min(FirstScore) )\n Option2 <- abs( FirstScore - max(FirstScore) )\n \n # For each option:\n \n Score_Reflect <- function( Component, Previous_Reputation ) {\n # Takes an adjusted score, and breaks it at a median point.\n \n # Only if there actually is a median point.\n if( length( unique(Component) ) <= 2 ) return(Component)\n \n # If the Reps are calculated directly, there is an exploit in generating \"sacrificial variance\" and passing it to a teammate.\n # Although initially the sac-var is zero-sum (pointless), after reweighting it can become helpful to attackers.\n \n # Instead, a simple adjustment:\n MedianFactor <- weighted.median(Component, w = Previous_Reputation) # Which component is in the center?\n # This central value will be the next maximum, NOT the value opposite the most-deviant.\n \n # By how much does the component exceed the Median?\n Reflection <- Component - MedianFactor \n # Where does the Component exceed the Median?\n Excessive <- ( Reflection > 0 )\n \n # Declare and Fill Answer\n AdjPrinComp <- Component\n AdjPrinComp[ Excessive ] <- Component[ Excessive ] - ( Reflection[ Excessive ] * 0.5 ) # Mixes in some of the old method.\n # Check: max(Component) == MedianFactor # TRUE\n \n return(AdjPrinComp)\n }\n \n \n NewScore_1 <- Score_Reflect(Option1, Rep)\n NewScore_2 <- Score_Reflect(Option2, Rep)\n \n # Now, by what criteria do we compare the options?\n # (This should be easy, because one option will be the opposite of truth, but it deserves some thought nonetheless.)\n \n Method <- RBCR # All of these work very well, but I'm pretty sure that Method 6 is the best.\n \n if( Method == 1 ) {\n # Statistics Method\n # \"Which set would produce more representative results?\"\n \n New1 <- GetWeight(Set1) %*% M # reweight to the reputation units first, then calculate what outcomes would resolve to using this Rep\n New2 <- GetWeight(Set2) %*% M \n \n RefInd <- sum( (New1-Old)^2 ) - sum( (New2-Old)^2 ) # squared errors\n \n }\n \n if( Method == 2 ) {\n # Mathematics Method\n # \"Which set moves the results the shortest distance?\"\n \n New1 <- Set1 %*% M # Do not change units at all (only shift one observation to zero, and remove negatives).\n New2 <- Set2 %*% M # Notice that Set1 and Set2 already have the same max and min.\n \n RefInd <- sum( abs(New1-Old)) - sum( abs(New2-Old)) # Raw errors, no squaring.\n \n }\n \n if( Method == 3 ) {\n # Rank Method\n # \"Which set moves the direction the least?\"\n \n rOld <- rank(Old)\n \n # Same as method 2, but focusing only on rank order. The logic being that we are focusing on the measurement of a single direction here.\n New1 <- rank( (GetWeight(Set1) %*% M) + 0.01*Old ) # I add Old because rank will erase data if final values are non-unique values\n New2 <- rank( (GetWeight(Set2) %*% M) + 0.01*Old )\n \n RefInd <- sum( abs(New1-rOld) ) - sum( abs(New2-rOld) ) # Raw errors, no squaring.\n \n if(RefInd==0) { # If the ranks are a tie, go back to Method 1\n \n New1 <- GetWeight(Set1) %*% M\n New2 <- GetWeight(Set2) %*% M\n \n RefInd <- sum( (New1-Old)^2 ) - sum( (New2-Old)^2 ) # squared errors\n }\n }\n \n if( Method == 4 ) {\n # Norm Method - Operating Logic Unknown\n \n # Caluclate Potential Outcomes\n New1 <- GetDecisionOutcomes(M, GetWeight(Set1), ScaledIndex)\n New2 <- GetDecisionOutcomes(M, GetWeight(Set2), ScaledIndex) \n \n # Absolute Differences in Outcome\n Choice1 <- abs( New1 - Old )\n Choice2 <- abs( New2 - Old )\n \n # Absolute Relevance of Dissagreement\n Dissent <- abs(FirstLoading)\n \n RefInd <- (Choice1 %*% Dissent) - (Choice2 %*% Dissent)\n }\n \n if( Method == 5 | Method == 6 ) {\n # Use Old Reputation to calculate outcomes.\n # Examine each voter's agreement with these outcomes.\n # Collapse this agreement using this period's Loading.\n \n # Old Outcomes\n Old_raw <- GetDecisionOutcomes(M, Rep, ScaledIndex) # Outcomes under the previous period's reputation\n # Bin non-scaled modes into < 0, .5, 1 > using Catch()\n Old_c <- vapply(Old_raw, FUN = Catch, Tolerance = Tol, FUN.VALUE = 1)\n Old_f <- Old_c ; Old_f[ScaledIndex] <- Old_raw[ScaledIndex]\n \n # Build distance matrix: absolute value of difference between \"Group Outcomes (using Old)\" and \"Individual Outcomes\"\n Distance <- abs( M - ( array(1, dim(M)) %*% diag(Old_f) ) )\n \n # Separately, build index of question-cohesion\n Dissent <- abs(FirstLoading) # FirstLoading is higher when people disagree, lower when people agree, zero for perfect agreement.\n Dissent[Dissent==0] <- NA # Remove Zeros (zeros are irrelevant, not infinitely important), avoid division-by-zero problems\n Mainstream <- ReWeight( 1/Dissent )\n \n # Integrate the Two\n NonCompliance <- Distance %*% t(t(Mainstream))\n Compliance <- ReWeight( abs( NonCompliance - max(NonCompliance) ) )\n \n # Compare - Which score has more error when it is matched up against compliance?\n Choice1 <- sum( (GetWeight(NewScore_1) - Compliance)^2 ) # Reweight is absolutely required here, as the components will always sum to different values.\n Choice2 <- sum( (GetWeight(NewScore_2) - Compliance)^2 ) \n \n # When RefInd becomes positive, switch to Set2.\n RefInd <- Choice1 - Choice2 # When Choice1 has greater error, this will be positive.\n \n }\n \n # Rep/mean(Rep) is a correction ensuring Reputation is additive. Therefore, nothing can be gained by splitting/combining Reputation into single/multiple accounts.\n Rep1 <- GetWeight( (NewScore_1 * Rep/mean(Rep)) )\n Rep2 <- GetWeight( (NewScore_2 * Rep/mean(Rep)) )\n \n # The Reference Index is a measurement of error, if >0, then New1 had higher errors (use New2), and conversely if <0 use 1.\n if(RefInd < 0 ) NewRep <- Rep1\n if(RefInd >= 0 ) NewRep <- Rep2\n \n }\n \n\n if(Verbose) {\n \n print(\"\")\n print(paste(\" %% Reference Index %% :\",RefInd))\n print(\"Estimations using: Previous Rep, Option 1, Option 2\")\n print( cbind( AsMatrix(Old_f), AsMatrix( GetDecisionOutcomes(M, Rep1, ScaledIndex) ), AsMatrix( GetDecisionOutcomes(M, Rep2, ScaledIndex) ) ) )\n print(\"\")\n print(\"Previous period reputations, Option 1, Option 2, Raw1, Raw2, Selection\")\n print( cbind( AsMatrix(Rep), AsMatrix(Rep1), AsMatrix(Rep2), AsMatrix(NewScore_1), AsMatrix(NewScore_2), AsMatrix(NewRep) ) )\n \n }\n \n \n # Freshly-Calculated Reward (Reputation) - Exponential Smoothing\n # New Reward: NewRep\n # Old Reward: Rep\n SmoothedR <- alpha*(NewRep) + (1-alpha)*Rep\n \n if(Verbose) {\n print(\"\")\n print(\"Corrected for Additivity , Smoothed _1 period\")\n print( cbind( AsMatrix(NewRep), AsMatrix(SmoothedR)) )\n }\n \n # Return Data\n Out <- list(\"FirstL\"=FirstLoading,\"OldRep\"=Rep,\"ThisRep\"=NewRep,\"SmoothRep\"=SmoothedR) # Keep the factors and time information along for the ride, they are interesting.\n return(Out)\n}\n\n# M <- matrix(nrow=3,byrow=TRUE,data=c(1,0,1,0,\n# 1,0,1,0,\n# 1,0,0,1))\n# \n# M2 <- matrix(nrow=3,byrow=TRUE,data=c(.80, .1, .72, 0,\n# .80, .1, .62, 0,\n# .43, .1, .00, 1))\n# \n# > GetRewardWeights(M)\n# $FirstL\n# [1] 0.0000000 0.0000000 -0.7071068 0.7071068\n# $OldRep\n# [1] 0.3333333 0.3333333 0.3333333\n# $ThisRep\n# [1] 0.5 0.5 0.0\n# $SmoothRep\n# [1] 0.35 0.35 0.30\n# \n# > GetRewardWeights(M, Rep=c(.2,.2,.6), Tol = .1)\n# $FirstL\n# [1] 0.0000000 0.0000000 -0.7071068 0.7071068\n# $OldRep\n# [1] 0.2 0.2 0.6\n# $ThisRep\n# [1] 0 0 1\n# $SmoothRep\n# [1] 0.18 0.18 0.64\n# \n# > GetRewardWeights(M2)\n# $FirstL\n# [1] -0.2934226 0.0000000 -0.5338542 0.7930340\n# $OldRep\n# [1] 0.3333333 0.3333333 0.3333333\n# $ThisRep\n# [1] 0.505356 0.494644 0.000000\n# $SmoothRep\n# [1] 0.3505356 0.3494644 0.3000000\n# \n# > GetRewardWeights(M2, Rep=c(.2,.2,.6), alpha=.5, Verbose = TRUE)\n# [1] \"****************************************************\"\n# [1] \"Begin 'GetRewardWeights'\"\n# [1] \"Inputs...\"\n# [1] \"Matrix:\"\n# [,1] [,2] [,3] [,4]\n# [1,] 0.80 0.1 0.72 0\n# [2,] 0.80 0.1 0.62 0\n# [3,] 0.43 0.1 0.00 1\n# [1] \"\"\n# [1] \"Reputation:\"\n# [,1]\n# [1,] 0.2\n# [2,] 0.2\n# [3,] 0.6\n# [1] \"\"\n# [1] \"First Loading:\"\n# [1] -0.2935984 0.0000000 -0.5330507 0.7935092\n# [1] \"First \n# [1] \"Previous period reputations, Option 1, Option 2, Raw1, Raw2, Selection\"\n# [,1] [,2] [,3] [,4] [,5] [,6]\n# [1,] 0.2 0.00000000 0.5105824 0.00000000 0.6429686 0.00000000\n# [2,] 0.2 0.01362912 0.4894176 0.05330507 0.6163160 0.01362912\n# [3,] 0.6 0.98637088 0.0000000 1.28593716 0.0000000 0.98637088\n# [1] \"\"\n# [1] \"Corrected for Additivity , Smoothed _1 period\"\n# [,1] [,2]\n# [1,] 0.00000000 0.1000000\n# [2,] 0.01362912 0.1068146\n# [3,] 0.98637088 0.7931854\n# $FirstL\n# [1] -0.2935984 0.0000000 -0.5330507 0.7935092\n# \n# $OldRep\n# [1] 0.2 0.2 0.6\n# \n# $ThisRep\n# [1] 0.00000000 0.01362912 0.98637088\n# \n# $SmoothRep\n# [1] 0.1000000 0.1068146 0.7931854\n\n\n# Score:\"\n# [,1]\n# [1,] -0.7822233\n# [2,] -0.7289182\n# [3,] 0.5037139\n# [1] \"\"\n# [1] \" %% Reference Index %% : -1.26355970920342\"\n# [1] \"Estimations using: Previous Rep, Option 1, Option 2\"\n# [,1] [,2] [,3]\n# [1,] 0.5 0.435042774 0.8000000\n# [2,] 0.0 0.100000000 0.1000000\n# [3,] 0.0 0.008450054 0.6710582\n# [4,] 0.5 0.986370881 0.0000000\n# [1] \"\"\n\nFillNa <- function(Mna, Rep = DemocracyRep(Mna), ScaledIndex = BinaryScales(Mna), CatchP=.1, Verbose=FALSE) { \n # Uses exisiting data and reputations to fill missing observations.\n # Essentially a weighted average using all availiable non-NA data.\n # How much should slackers who arent voting suffer? I decided this would depend on the global percentage of slacking.\n \n Mnew <- Mna # Declare (in case no Missing values, Mnew, MnewC, and Mna will be the same)\n MnewC <- Mna\n \n if(sum(is.na(Mna))>0) {\n #Of course, only do this process if there ARE missing values.\n \n if(Verbose) print(\"Missing Values Detected. Beginning presolve using availiable values.\")\n \n #Decision Outcome - Our best guess for the Decision state (FALSE=0, Ambiguous=.5, TRUE=1) so far (ie, using the present, non-missing, values).\n DecisionOutcomes.Raw <- GetDecisionOutcomes(Mna,Rep,ScaledIndex,Verbose)\n \n #Fill in the predictions to the original M\n NAmat <- is.na(Mna) #Defines the slice of the matrix which needs to be edited.\n Mnew[NAmat] <- 0 #Erase the NA's\n \n #Slightly complicated:\n NAsToFill <- ( NAmat%*%diag(as.vector(DecisionOutcomes.Raw)) )\n # This builds a matrix whose columns j:\n # NAmat was false (the observation wasn't missing) ... have a value of Zero\n # NAmat was true (the observation was missing) ... have a value of the jth element of DecisionOutcomes.Raw (the 'current best guess') \n Mnew <- Mnew + NAsToFill\n #This replaces the NAs, which were zeros, with the predicted Decision outcome.\n \n \n if(Verbose) { print(\"Missing Values:\"); print(NAmat) ; print(\"Imputed Values:\"); print(NAsToFill)}\n \n #Declare Output\n MnewC <- Mnew\n ## Discriminate based on contract type\n #Fill ONLY Binary contracts by appropriately forcing predictions into their discrete (0,.5,1) slot. (reveals .5 coordination, continuous variables are more gameable).\n MnewC[,!ScaledIndex] <- apply(Mnew[,!ScaledIndex], c(1,2), function(x) Catch(x,Tolerance = CatchP) )\n #\n \n \n }\n \n if(Verbose) { print(\"Raw Results:\"); print(Mnew) ; print(\"Binned:\"); print(MnewC) ; print(\"*** ** Missing Values Filled ** ***\") }\n \n return(MnewC)\n}\n\n# M <- matrix( data=c(\n# 1, 1, 0, 0, 0.5356322, 6.689658e-01,\n# 1, 0, NA, NA, 0.4574713, NA,\n# 1, NA, 0, NA, 0.5356322, 6.689658e-01,\n# 1, 1, 1, NA, 0.5747126, NA,\n# 0, NA, 1, NA, 1.0000000, 8.333333e-05,\n# 0, 0, 1, 1, NA, 9.999167e-01),\n# nrow=6,byrow=TRUE)\n\n# > FillNa(M,ScaledIndex=c(FALSE,FALSE,FALSE,FALSE,TRUE,TRUE))\n# [,1] [,2] [,3] [,4] [,5] [,6]\n# [1,] 1 1.0 0 0.0 0.5356322 6.689658e-01\n# [2,] 1 0.0 1 0.5 0.4574713 6.689658e-01\n# [3,] 1 0.5 0 0.5 0.5356322 6.689658e-01\n# [4,] 1 1.0 1 0.5 0.5747126 6.689658e-01\n# [5,] 0 0.5 1 0.5 1.0000000 8.333333e-05\n# [6,] 0 0.0 1 1.0 0.5356322 9.999167e-01\n# > FillNa(M,ScaledIndex=c(FALSE,FALSE,FALSE,FALSE,FALSE,FALSE))\n# [,1] [,2] [,3] [,4] [,5] [,6]\n# [1,] 1 1.0 0 0.0 0.5 1\n# [2,] 1 0.0 1 0.5 0.5 1\n# [3,] 1 0.5 0 0.5 0.5 1\n# [4,] 1 1.0 1 0.5 1.0 1\n# [5,] 0 0.5 1 0.5 1.0 0\n# [6,] 0 0.0 1 1.0 1.0 1\n\n\n\n#Putting it all together:\nFactory <- function(M0, Scales = BinaryScales(M0), Rep = DemocracyRep(M0), CatchP=.2, MaxRow=5000, Verbose=FALSE, RBCR = 6) {\n # Main Routine\n\n ScaledIndex=as.logical( Scales[\"Scaled\",] )\n MScaled <- Rescale(M0, Scales)\n \n #Handle Missing Values \n Filled <- FillNa(MScaled, Rep, ScaledIndex, CatchP, Verbose)\n\n ## Consensus - Row Players \n # New Consensus Reward\n PlayerInfo <- GetRewardWeights(M = Filled, Rep, ScaledIndex, alpha = .1, Tol = CatchP, Verbose, RBCR)\n AdjLoadings <- PlayerInfo$FirstL\n \n ## Column Players (The Decision Creators)\n # Calculation of Reward for Decision Authors\n # Consensus - \"Who won?\" Decision Outcome \n DecisionOutcomes.Raw <- PlayerInfo$SmoothRep %*% Filled # Declare (all binary), Simple matrix multiplication ... highest information density at RowBonus, but need DecisionOutcomes.Raw to get to that\n for(i in 1:ncol(Filled)) { # slow implementation.. 'for loop' bad on R, much faster on python\n # Discriminate Based on Contract Type\n if(ScaledIndex[i]) DecisionOutcomes.Raw[i] <- weighted.median(Filled[,i], w=PlayerInfo$SmoothRep) #Our Current best-guess for this Scaled Decision (weighted median)\n }\n \n # The Outcome Itself\n # Discriminate Based on Contract Type\n DecisionOutcome.Adj <- mapply(Catch,DecisionOutcomes.Raw,Tolerance=CatchP) # Declare first (assumes all binary) \n DecisionOutcome.Adj[ScaledIndex] <- DecisionOutcomes.Raw[ScaledIndex] # Replace Scaled with raw (weighted-median)\n DecisionOutcome.Final <- t( Scales[\"Max\",] - Scales[\"Min\",] ) %*% diag( DecisionOutcome.Adj ) # Rescale these back up.\n DecisionOutcome.Final <- DecisionOutcome.Final + Scales[\"Min\",] # Recenter these back up.\n \n \n # Quality of Outcomes - is there confusion?\n \n Certainty <- vector(\"numeric\",ncol(Filled))\n # For each Decision\n for(i in 1:ncol(Filled)) { \n # Sum of, the reputations which, met the condition that they voted for the outcome which was selected for this Decision.\n Certainty[i] <- sum( PlayerInfo$SmoothRep [ DecisionOutcome.Final[i] == Filled[,i] ] )\n }\n Avg.Certainty <- mean(Certainty) # How well did beliefs converge?\n \n # Stability of Voter Reports is not the same as \"Clear Instructions\" (one can be 'certain' that something was 'unclear' if you all agree it was).\n # Want to discourage .5's\n Resolveable <- Filled!=.5\n MaxClairity <- Rep %*% Resolveable # All of the answers for .5 are an instant-veto on Clairity. If 30% said 'unclear' can't do better than 70%.\n Clarity <- MaxClairity * Certainty\n \n ConReward <- GetWeight(Clarity) # Grading Authors on a curve. -not necessarily the best idea?\n\n \n if(Verbose) {\n print(\"*Decision Outcomes Sucessfully Calculated*\")\n Temp <- rbind(DecisionOutcomes.Raw, Certainty, ConReward)\n row.names(Temp) <- c(\"Raw Outcomes\", \"Certainty\", \"AuthorPayoutFactor\")\n print(Temp)\n }\n \n \n ## Participation\n \n #Information about missing values\n NAmat <- M0*0 \n NAmat[is.na(NAmat)] <- 1 #indicator matrix for missing\n \n #Participation Within Decisions (Columns) \n # % of reputation that answered each Decision\n ParticipationC <- 1-(PlayerInfo$SmoothRep%*%NAmat)\n \n #Participation Within Agents (Rows) \n # Many options\n \n # 1- Democracy Option - all Decisions treated equally.\n ParticipationR <- 1-( apply(NAmat,1,sum)/ncol(M0) )\n \n #General Participation\n PercentNA <- 1-mean(ParticipationC)\n #(Possibly integrate two functions of participation?) Chicken and egg problem...\n \n if(Verbose) {\n print(\"*Participation Information*\")\n print(\"Voter Turnout by question\"); print( ParticipationC )\n print(\"Voter Turnout across questions\"); print ( ParticipationR )\n }\n \n ## Combine Information\n # Row\n NAbonusR <- GetWeight(ParticipationR)\n RowBonus <- (NAbonusR*(PercentNA))+(PlayerInfo$SmoothR*(1-PercentNA))\n \n # Column\n NAbonusC <- GetWeight(ParticipationC)\n ColBonus <- (NAbonusC*(PercentNA))+(ConReward*(1-PercentNA)) \n \n # Present Results\n Output <- vector(\"list\",6) #Declare\n names(Output) <- c(\"Original\",\"Filled\",\"Agents\",\"Decisions\",\"Participation\",\"Certainty\")\n \n Output[[1]] <- M0\n Output[[2]] <- Filled\n Output[[3]] <- cbind(PlayerInfo$OldRep, PlayerInfo$ThisRep,PlayerInfo$SmoothRep,apply(NAmat,1,sum),ParticipationR,NAbonusR,RowBonus)\n colnames(Output[[3]]) <- c(\"OldRep\", \"ThisRep\", \"SmoothRep\", \"NArow\", \"ParticipationR\",\"RelativePart\",\"RowBonus\") \n Output[[4]] <- rbind(AdjLoadings,DecisionOutcomes.Raw,ConReward,Certainty,apply(NAmat,2,sum),ParticipationC,ColBonus,DecisionOutcome.Final)\n rownames(Output[[4]]) <- c(\"First Loading\",\"DecisionOutcomes.Raw\",\"Consensus Reward\",\"Certainty\",\"NAs Filled\",\"ParticipationC\",\"Author Bonus\",\"DecisionOutcome.Final\")\n Output[[5]] <- (1-PercentNA) # Using this to set inclusion fees.\n Output[[6]] <- Avg.Certainty # Using this to set Catch Parameter\n \n return(Output)\n}\n\n\n# M1 <- rbind(\n# c(1,1,0,0),\n# c(1,0,0,0),\n# c(1,1,0,0),\n# c(1,1,1,0),\n# c(0,0,1,1),\n# c(0,0,1,1))\n# \n# row.names(M1) <- c(\"True\", \"Distort 1\", \"True\", \"Distort 2\", \"Liar\", \"Liar\")\n# colnames(M1) <- c(\"D1.1\",\"D2.1\",\"D3.0\",\"D4.0\")\n# \n# > Factory(M1)\n# $Original\n# D1.1 D2.1 D3.0 D4.0\n# True 1 1 0 0\n# Distort 1 1 0 0 0\n# True 1 1 0 0\n# Distort 2 1 1 1 0\n# Liar 0 0 1 1\n# Liar 0 0 1 1\n# \n# $Filled\n# D1.1 D2.1 D3.0 D4.0\n# True 1 1 0 0\n# Distort 1 1 0 0 0\n# True 1 1 0 0\n# Distort 2 1 1 1 0\n# Liar 0 0 1 1\n# Liar 0 0 1 1\n# \n# $Agents\n# OldRep ThisRep SmoothRep NArow ParticipationR RelativePart RowBonus\n# True 0.1666667 0.2823757 0.1782376 0 1 0.1666667 0.1782376\n# Distort 1 0.1666667 0.2176243 0.1717624 0 1 0.1666667 0.1717624\n# True 0.1666667 0.2823757 0.1782376 0 1 0.1666667 0.1782376\n# Distort 2 0.1666667 0.2176243 0.1717624 0 1 0.1666667 0.1717624\n# Liar 0.1666667 0.0000000 0.1500000 0 1 0.1666667 0.1500000\n# Liar 0.1666667 0.0000000 0.1500000 0 1 0.1666667 0.1500000\n# \n# $Decisions\n# D1.1 D2.1 D3.0 D4.0\n# First Loading -0.5395366 -0.4570561 0.4570561 0.5395366\n# DecisionOutcomes.Raw 0.7000000 0.5282376 0.4717624 0.3000000\n# Consensus Reward 0.5000000 0.0000000 0.0000000 0.5000000\n# Certainty 0.7000000 0.0000000 0.0000000 0.7000000\n# NAs Filled 0.0000000 0.0000000 0.0000000 0.0000000\n# ParticipationC 1.0000000 1.0000000 1.0000000 1.0000000\n# Author Bonus 0.5000000 0.0000000 0.0000000 0.5000000\n# DecisionOutcome.Final 1.0000000 0.5000000 0.5000000 0.0000000\n# \n# $Participation\n# [1] 1\n# \n# $Certainty\n# [1] 0.35\n# \n# \n# \n# MS <- matrix( data=c(\n# 1, 1, 0, 0, 233, 16027.59,\n# 1, 0, 0, 0, 199, NA,\n# 1, 1, 0, 0, 233, 16027.59,\n# 1, 1, 1, 0, 250, NA,\n# 0, 0, 1, 1, 435, 8001.00,\n# 0, 0, 1, 1, 435, 19999.00),\n# nrow=6,byrow=TRUE, dimnames=list( rownames(M1), paste(\"D\",1:6,sep=\".\")))\n# \n# \n# Scales <- matrix( data=c(\n# 0, 0, 0, 0, 1, 1,\n# 0, 0, 0, 0, 0, 8000,\n# 1, 1, 1, 1, 435, 20000), \n# nrow=3, byrow=TRUE, dimnames=list( c(\"Scaled\",\"Min\",\"Max\"), colnames(MS)) )\n# \n# \n# > Factory(M0=MS,Scales=Scales)\n# $Original\n# D.1 D.2 D.3 D.4 D.5 D.6\n# True 1 1 0 0 233 16027.59\n# Distort 1 1 0 0 0 199 NA\n# True 1 1 0 0 233 16027.59\n# Distort 2 1 1 1 0 250 NA\n# Liar 0 0 1 1 435 8001.00\n# Liar 0 0 1 1 435 19999.00\n# \n# $Filled\n# D.1 D.2 D.3 D.4 D.5 D.6\n# True 1 1 0 0 0.5356322 6.689658e-01\n# Distort 1 1 0 0 0 0.4574713 6.689658e-01\n# True 1 1 0 0 0.5356322 6.689658e-01\n# Distort 2 1 1 1 0 0.5747126 6.689658e-01\n# Liar 0 0 1 1 1.0000000 8.333333e-05\n# Liar 0 0 1 1 1.0000000 9.999167e-01\n# \n# $Agents\n# OldRep ThisRep SmoothRep NArow ParticipationR RelativePart RowBonus\n# True 0.1666667 0.27512698 0.1775127 0 1.0000000 0.1764706 0.1774530\n# Distort 1 0.1666667 0.22080941 0.1720809 1 0.8333333 0.1470588 0.1706477\n# True 0.1666667 0.27512698 0.1775127 0 1.0000000 0.1764706 0.1774530\n# Distort 2 0.1666667 0.21600171 0.1716002 1 0.8333333 0.1470588 0.1701944\n# Liar 0.1666667 0.00000000 0.1500000 0 1.0000000 0.1764706 0.1515162\n# Liar 0.1666667 0.01293492 0.1512935 0 1.0000000 0.1764706 0.1527356\n# \n# $Decisions\n# D.1 D.2 D.3 D.4 D.5 D.6\n# First Loading -0.5223889 -0.43411264 0.44195128 0.5223889 0.2463368 -9.880889e-02\n# DecisionOutcomes.Raw 0.6987065 0.52662557 0.47289366 0.3012935 0.5356322 6.689658e-01\n# Consensus Reward 0.2850531 0.00000000 0.00000000 0.2850531 0.1448406 2.850531e-01\n# Certainty 0.6987065 0.00000000 0.00000000 0.6987065 0.3550254 6.987065e-01\n# NAs Filled 0.0000000 0.00000000 0.00000000 0.0000000 0.0000000 2.000000e+00\n# ParticipationC 1.0000000 1.00000000 1.00000000 1.0000000 1.0000000 6.563189e-01\n# Author Bonus 0.2788520 0.01012676 0.01012676 0.2788520 0.1466709 2.753716e-01\n# DecisionOutcome.Final 1.0000000 0.50000000 0.50000000 0.0000000 233.0000000 1.602759e+04\n# \n# $Participation\n# [1] 0.9427198\n# \n# $Certainty\n# [1] 0.4085242\n# \n# > Factory(M0=MS,Scales=Scales,Rep=c(.05,.05,.05,.05,.10,.70))\n# $Original\n# D.1 D.2 D.3 D.4 D.5 D.6\n# True 1 1 0 0 233 16027.59\n# Distort 1 1 0 0 0 199 NA\n# True 1 1 0 0 233 16027.59\n# Distort 2 1 1 1 0 250 NA\n# Liar 0 0 1 1 435 8001.00\n# Liar 0 0 1 1 435 19999.00\n# \n# $Filled\n# D.1 D.2 D.3 D.4 D.5 D.6\n# True 1 1 0 0 0.5356322 6.689658e-01\n# Distort 1 1 0 0 0 0.4574713 9.999167e-01\n# True 1 1 0 0 0.5356322 6.689658e-01\n# Distort 2 1 1 1 0 0.5747126 9.999167e-01\n# Liar 0 0 1 1 1.0000000 8.333333e-05\n# Liar 0 0 1 1 1.0000000 9.999167e-01\n# \n# $Agents\n# OldRep ThisRep SmoothRep NArow ParticipationR RelativePart RowBonus\n# True 0.05 0.00000000 0.04500000 0 1.0000000 0.1764706 0.04702833\n# Distort 1 0.05 0.01235137 0.04623514 1 0.8333333 0.1470588 0.04779064\n# True 0.05 0.00000000 0.04500000 0 1.0000000 0.1764706 0.04702833\n# Distort 2 0.05 0.01332745 0.04633275 1 0.8333333 0.1470588 0.04788674\n# Liar 0.10 0.11962886 0.10196289 0 1.0000000 0.1764706 0.10311239\n# Liar 0.70 0.85469232 0.71546923 0 1.0000000 0.1764706 0.70715357\n# \n# $Decisions\n# D.1 D.2 D.3 D.4 D.5 D.6\n# First Loading -0.5369880 -0.4210132 0.4240200 0.5369880 0.2540098 4.149213e-02\n# DecisionOutcomes.Raw 0.1825679 0.1363327 0.8637649 0.8174321 1.0000000 9.999167e-01\n# Consensus Reward 0.1638874 0.1731571 0.1731767 0.1638874 0.1638874 1.620038e-01\n# Certainty 0.8174321 0.8636673 0.8637649 0.8174321 0.8174321 8.080371e-01\n# NAs Filled 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 2.000000e+00\n# ParticipationC 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000 9.074321e-01\n# Author Bonus 0.1639706 0.1730973 0.1731166 0.1639706 0.1639706 1.618743e-01\n# DecisionOutcome.Final 0.0000000 0.0000000 1.0000000 1.0000000 435.0000000 1.999900e+04\n# \n# $Participation\n# [1] 0.984572\n# \n# $Certainty\n# [1] 0.8312943\n\n\n\n\n# Double-Factory (more reliable)\n\nDoubleFactory <- function(X, Scales = BinaryScales(X), Rep = DemocracyRep(X), CatchP=.1, MaxRow=5000, Phi=.65, Verbose=FALSE) {\n # see http://forum.truthcoin.info/index.php/topic,102.msg289.html#msg289\n \n WaveOne <- Factory(X,Scales,Rep,CatchP,MaxRow,Verbose)\n \n Safe <- ( WaveOne$Decisions[\"Certainty\",] ) >= Phi # all those contracts which were unanimous for a subset of proportion (\"Phi\")\n \n if(Verbose) {\n print(\" Wave One Complete.\")\n print( sum(Safe)/ncol(X) )\n }\n \n WaveTwo <- Factory( X[,Safe] ,\n Scales[,Safe],\n Rep,CatchP,MaxRow,Verbose)\n \n return(WaveTwo)\n}\n\n\n# M1 is defined above\n\n# > DoubleFactory(M1)\n# $Original\n# D1.1 D4.0\n# True 1 0\n# Distort 1 1 0\n# True 1 0\n# Distort 2 1 0\n# Liar 0 1\n# Liar 0 1\n# \n# $Filled\n# D1.1 D4.0\n# True 1 0\n# Distort 1 1 0\n# True 1 0\n# Distort 2 1 0\n# Liar 0 1\n# Liar 0 1\n# \n# $Agents\n# OldRep ThisRep SmoothRep NArow ParticipationR RelativePart RowBonus\n# True 0.1666667 0.25 0.175 0 1 0.1666667 0.175\n# Distort 1 0.1666667 0.25 0.175 0 1 0.1666667 0.175\n# True 0.1666667 0.25 0.175 0 1 0.1666667 0.175\n# Distort 2 0.1666667 0.25 0.175 0 1 0.1666667 0.175\n# Liar 0.1666667 0.00 0.150 0 1 0.1666667 0.150\n# Liar 0.1666667 0.00 0.150 0 1 0.1666667 0.150\n# \n# $Decisions\n# D1.1 D4.0\n# First Loading -0.7071068 0.7071068\n# DecisionOutcomes.Raw 0.7000000 0.3000000\n# Consensus Reward 0.5000000 0.5000000\n# Certainty 0.7000000 0.7000000\n# NAs Filled 0.0000000 0.0000000\n# ParticipationC 1.0000000 1.0000000\n# Author Bonus 0.5000000 0.5000000\n# DecisionOutcome.Final 1.0000000 0.0000000\n# \n# $Participation\n# [1] 1\n# \n# $Certainty\n# [1] 0.7\n\n\n# M2 <- matrix( data=c(\n# c(0.5, 0.5, 1, 0),\n# c(0.5, 0.0, 1, 0),\n# c(0.5, 1.0, 1, 0),\n# c(1.0, NA, 1, NA),\n# c(0.5, 1.0, 1, 1),\n# c(0.0, 0.0, 1, 1)), nrow=6, byrow=TRUE, dimname=list(paste(\"V\",1:6,sep=\".\"), colnames(M1)) )\n# \n# > DoubleFactory(M2)\n# $Original\n# D1.1 D3.0 D4.0\n# V.1 0.5 1 0\n# V.2 0.5 1 0\n# V.3 0.5 1 0\n# V.4 1.0 1 NA\n# V.5 0.5 1 1\n# V.6 0.0 1 1\n# \n# $Filled\n# D1.1 D3.0 D4.0\n# V.1 0.5 1 0\n# V.2 0.5 1 0\n# V.3 0.5 1 0\n# V.4 1.0 1 0\n# V.5 0.5 1 1\n# V.6 0.0 1 1\n\n# $Agents\n# OldRep ThisRep SmoothRep NArow ParticipationR RelativePart RowBonus\n# V.1 0.1666667 0.22833653 0.1728337 0 1.0000000 0.1764706 0.1730484\n# V.2 0.1666667 0.22833653 0.1728337 0 1.0000000 0.1764706 0.1730484\n# V.3 0.1666667 0.22833653 0.1728337 0 1.0000000 0.1764706 0.1730484\n# V.4 0.1666667 0.27166347 0.1771663 1 0.6666667 0.1176471 0.1736514\n# V.5 0.1666667 0.04332693 0.1543327 0 1.0000000 0.1764706 0.1556401\n# V.6 0.1666667 0.00000000 0.1500000 0 1.0000000 0.1764706 0.1515632\n# \n# $Decisions\n# D1.1 D3.0 D4.0\n# First Loading -0.4241554 0.0000000 0.9055894\n# DecisionOutcomes.Raw 0.5135832 1.0000000 0.3043327\n# Consensus Reward 0.1168147 0.5208482 0.3623371\n# Certainty 0.6728337 1.0000000 0.6956673\n# NAs Filled 0.0000000 0.0000000 1.0000000\n# ParticipationC 1.0000000 1.0000000 0.8228337\n# Author Bonus 0.1308368 0.5110099 0.3581533\n# DecisionOutcome.Final 0.5000000 1.0000000 0.0000000\n# \n# $Participation\n# [1] 0.9409446\n# \n# $Certainty\n# [1] 0.7895003\n", "meta": {"hexsha": "13919755b1d29bcfd24e46b3a2592073139a1a1c", "size": 34043, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/consensus/ConsensusMechanism.r", "max_stars_repo_name": "endolith/Truthcoin", "max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 161, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z", "max_issues_repo_path": "lib/consensus/ConsensusMechanism.r", "max_issues_repo_name": "endolith/Truthcoin", "max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z", "max_forks_repo_path": "lib/consensus/ConsensusMechanism.r", "max_forks_repo_name": "endolith/Truthcoin", "max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z", "avg_line_length": 39.4930394432, "max_line_length": 200, "alphanum_fraction": 0.6034720794, "num_tokens": 12718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.47224993721154346}} {"text": "# Elvis Sun\n# 250696535\n# Feb 8th\n\n#function params\n\n\n\ndcfFunc <- function(\n currentRevenue, currentCapitalSpending, currentDepreciation, taxRateIncome,\n bookValueDebt, bookValueEquity, nolCarriedForward, publiclyTradedFlag, #8\n lastTradedPrice, numberSharesOutstanding, marketValueDebt, debtCapitalRatio,\n costEquity, betaStock, riskFreeRate, riskPremium, #16\n costDebt, growthRateStablePeriod, operatingExpenseStablePeriod, workingCapitalStablePeriod, #20\n betaStablePeriod, debtRatioStablePeriod, costDebtFlag, costDebtStablePeriod, #24\n capitalExpendituresStablePeriod, growthRateRevenueRng, #26\n operatingExpenseRng, growthRateCapitalSpendingRng, \n growthRateDepreciationRng, workingCapitalRng, #30\n excessReturnPeriods = 10, capPeriods = 5, output = 1\n){\n \n #transpose if horizontal, and raise an error \n if (nrow(growthRateRevenueRng) == 1){\n growthRateRevenueRng <- t(growthRateRevenueRng)\n }\n if (nrow(growthRateRevenueRng) != excessReturnPeriods){\n stop(\"Different Dimension Than Excess Return Periods\")\n }\n \n if (nrow(operatingExpenseRng) == 1){\n operatingExpenseRng <- t(operatingExpenseRng)\n }\n if (nrow(operatingExpenseRng) != excessReturnPeriods){\n stop(\"Different Dimension Than Excess Return Periods\")\n }\n \n \n if (nrow(growthRateCapitalSpendingRng) == 1){\n growthRateCapitalSpendingRng <- t(growthRateCapitalSpendingRng)\n }\n if (nrow(growthRateCapitalSpendingRng) != excessReturnPeriods){\n stop(\"Different Dimension Than Excess Return Periods\")\n }\n \n \n if (nrow(growthRateDepreciationRng) == 1){\n growthRateDepreciationRng <- t(growthRateDepreciationRng)\n }\n if (nrow(growthRateDepreciationRng) != excessReturnPeriods){\n stop(\"Different Dimension Than Excess Return Periods\")\n }\n \n \n if (nrow(workingCapitalRng) == 1){\n workingCapitalRng <- t(workingCapitalRng)\n }\n if (nrow(workingCapitalRng) != excessReturnPeriods){\n stop(\"Different Dimension Than Excess Return Periods\")\n }\n \n #rename variables\n growthRateRevenueVector <- growthRateRevenueRng\n operatingExpenseVector <- operatingExpenseRng\n growthRateCapitalSpendingVector <- growthRateCapitalSpendingRng\n growthRateDepreciationVector <- growthRateDepreciationRng\n workingCapitalVector <- workingCapitalRng\n \n #if else to calculate some constant\n costEquityVal <- riskFreeRate + betaStock * riskPremium\n if (costEquity != 0 ){\n costEquityVal <- costEquity\n }\n \n temp <- 1 - debtCapitalRatio\n if (debtCapitalRatio == 0){\n temp <- 1 - bookValueDebt\n }\n equityDebtRatio <- temp\n if (publiclyTradedFlag) {\n equityDebtRatio <- lastTradedPrice * numberSharesOutstanding / (marketValueDebt + lastTradedPrice * numberSharesOutstanding)\n }\n \n #calculate more constant\n afterTaxCostDebt <- costDebt * (1 - taxRateIncome)\n debtCapitalVal <- 1 - equityDebtRatio\n costCapitalVal <- costEquityVal * equityDebtRatio + afterTaxCostDebt * debtCapitalVal\n \n #make matrix\n temp <- matrix(, nrow = 33, ncol = excessReturnPeriods + 1)\n \n \n for(j in 1:excessReturnPeriods) {\n temp[1,j] <- j\n \n ifelse(j > 1, temp[2,j] <- temp[2,j-1], temp[2,j] <- currentRevenue * (1 + growthRateRevenueVector[j,1]))\n temp[3,j] <- temp[2,j] * operatingExpenseVector[j,1]\n temp[4,j] <- temp[2,j] - temp[3,j]\n \n if(j > 1) {\n temp[5,j] <- ifelse(temp[4,j] > 0, ifelse(temp[12,j-1] > temp[4,j], 0, (temp[4,j] - temp[12,j-1])) * taxRateIncome, 0)\n temp[7,j] <- temp[7,j-1] * (1 + growthRateDepreciationVector[j,1])\n temp[8,j] <- temp[8,j-1] * (1 + growthRateCapitalSpendingVector[j,1])\n temp[9,j] <- (temp[2,j] - temp [2,j-1]) * workingCapitalVector[j,1]\n temp[12,j] <- ifelse(temp[12,j-1] > temp[4,j], temp[12,j-1] - temp[4,j], 0)\n }\n else {\n temp[5,j] <- ifelse(temp[4,j] > 0, ifelse(nolCarriedForward > temp[4,j], 0, (temp[4,j] - nolCarriedForward) * taxRateIncome), 0)\n temp[7,j] <- currentDepreciation * (1 + growthRateDepreciationVector[j,1])\n temp[8,j] <- currentCapitalSpending * (1 + growthRateCapitalSpendingVector[j,1])\n temp[9,j] <- (temp[2,j] - currentRevenue) * workingCapitalVector[j,1]\n temp[12,j] <- ifelse(nolCarriedForward > 0, ifelse(nolCarriedForward < temp[2,j], 0, nolCarriedForward - temp[2,j]), 0)\n }\n \n \n temp[6,j] <- temp[4,j] - temp[5,j]\n temp[10,j] <- temp[6,j] + temp[7,j] + temp[8,j] - temp[9,j]\n temp[13,j] <- temp[5,j] / temp[4,j]\n \n if(j <= capPeriods) {\n temp[14,j] <- betaStock\n temp[17,j] <- debtCapitalVal\n }\n else {\n temp[14,j] <- ifelse(betaStablePeriod != 0, temp[14,capPeriods] - ((temp[14,capPeriods] - betaStablePeriod) / capPeriods) * (j - capPeriods), betaStock)\n temp[17,j] <- ifelse(debtRatioStablePeriod != 0, temp[17,capPeriods] - ((temp[17,capPeriods] - debtCapitalVal) / capPeriods) * (j - capPeriods), debtCapitalVal)\n }\n \n temp[15,j] <- ifelse(costEquity == 0, riskFreeRate + temp[14,j] * riskPremium, costEquity)\n temp[16,j] <- costDebtStablePeriod * (1 - taxRateIncome)\n temp[18,j] <- temp[15,j] * (1 - temp[17,j]) + temp[16,j] * temp[17,j]\n ifelse(j > 1, temp[19,j] <- temp[19,j-1] * (1 + temp[18,j]), temp[19,j] <- 1 + temp[18,j])\n temp[11,j] <- temp[10,j] / temp[19,j]\n ifelse(is.na(temp[28,1]), temp[28,1] <- temp[11,j], temp[28,1] <- temp[28,1] + temp[11,j])\n }\n \n \n \n #temp[1,excessReturnPeriods+1] <- \"TN\"\n temp[2,excessReturnPeriods+1] <- temp[2,excessReturnPeriods] * (1+ growthRateStablePeriod)\n temp[3,excessReturnPeriods+1] <- temp[2,excessReturnPeriods+1] * operatingExpenseStablePeriod\n temp[4,excessReturnPeriods+1] <- temp[2,excessReturnPeriods+1] - temp[3,excessReturnPeriods+1]\n temp[5,excessReturnPeriods+1] <- ifelse(temp[4,excessReturnPeriods+1] > 0, ifelse(temp[12,excessReturnPeriods] > temp[4,excessReturnPeriods+1], 0, (temp[4,excessReturnPeriods+1] - temp[12,excessReturnPeriods]) * taxRateIncome), 0)\n temp[6,excessReturnPeriods+1] <- temp[4,excessReturnPeriods+1] - temp[5,excessReturnPeriods+1]\n temp[7,excessReturnPeriods+1] <- temp[7,excessReturnPeriods]\n temp[8,excessReturnPeriods+1] <- ifelse(capitalExpendituresStablePeriod == 0, temp[7,excessReturnPeriods+1], temp[7,excessReturnPeriods+1] * capitalExpendituresStablePeriod)\n temp[9,excessReturnPeriods+1] <- (temp[2,excessReturnPeriods+1] - temp[2,excessReturnPeriods]) * workingCapitalStablePeriod\n temp[10,excessReturnPeriods+1] <- temp[6,excessReturnPeriods+1] + temp[7,excessReturnPeriods+1] - temp[8,excessReturnPeriods+1] - temp[9,excessReturnPeriods+1]\n temp[13,excessReturnPeriods+1] <- temp[5,excessReturnPeriods+1] / temp[4,excessReturnPeriods+1]\n temp[14,excessReturnPeriods+1] <- temp[14,excessReturnPeriods]\n temp[15,excessReturnPeriods+1] <- ifelse(costEquity == 0, riskFreeRate + temp[14,excessReturnPeriods+1] * riskPremium, costEquity)\n temp[16,excessReturnPeriods+1] <- temp[16,excessReturnPeriods]\n temp[17,excessReturnPeriods+1] <- temp[17,excessReturnPeriods]\n temp[18,excessReturnPeriods+1] <- temp[15,excessReturnPeriods+1] * (1 - temp[17,excessReturnPeriods+1]) + temp[16,excessReturnPeriods+1] * temp[17,excessReturnPeriods+1]\n temp[20,1] <- growthRateStablePeriod\n temp[21,1] <-temp[10,excessReturnPeriods+1]\n temp[22,1] <- ifelse(betaStablePeriod == 0, riskFreeRate + betaStock * riskPremium, riskFreeRate + betaStablePeriod * riskPremium)\n temp[23,1] <- ifelse(debtRatioStablePeriod != 0, 1 - debtRatioStablePeriod, equityDebtRatio)\n temp[24,1] <- ifelse(costDebtFlag == TRUE, costDebtStablePeriod * (1 - taxRateIncome), afterTaxCostDebt)\n temp[25,1] <- 1 - temp[23,1]\n temp[26,1] <- temp[22,1] * temp[23,1] + temp[24,1] * temp[25,1]\n temp[27,1] <- temp[21,1] / (temp[26,1] - temp[20,1])\n temp[29,1] <- temp[27,1] / temp[19,excessReturnPeriods]\n temp[30,1] <- temp[28,1] + temp[29,1]\n temp[31,1] <- ifelse(publiclyTradedFlag == TRUE, marketValueDebt, bookValueDebt)\n temp[32,1] <- temp[30,1] - temp[31,1]\n temp[33,1] <- temp[32,1] / numberSharesOutstanding\n \n intrinsicValueShare <- temp[33,1]\n\n \n if(output == 0) {\n intrinsicValueShare\n }\n else if(output == 1) {\n temp\n }\n}\n\n\ndcfFunc(108249, 7696, 1814, 0.242157579,\n 0.1, 76615, 200000, TRUE, #8\n 500, 929.3, 0.1, 0, #12\n 0.07, 1, 0.02, 0.05, #16\n 0.025, 0.03, 0.8165, 0.01,#20\n 1, 0.15, TRUE, 0.08, #24\n 1.1,\n matrix(c(rep(0.06,7),rep(0.03,13)),ncol=1),\n matrix(c(rep(0.82,20)),ncol=1),\n matrix(c(0.02,rep(0.06,4),rep(0.03,15)),ncol=1),\n matrix(c(-0.07,rep(0.06,5),rep(0.03,14)),ncol=1),\n matrix(c(rep(0.05,20)),ncol=1),\n 20,5,0\n)\n", "meta": {"hexsha": "2227852a6133303acdf5c478c1b1d58046d8b97c", "size": 8599, "ext": "r", "lang": "R", "max_stars_repo_path": "app.r", "max_stars_repo_name": "elvisun/DCF-with-R", "max_stars_repo_head_hexsha": "77dddd8f4c61ad214ee6d327c6b6c320856fcf15", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app.r", "max_issues_repo_name": "elvisun/DCF-with-R", "max_issues_repo_head_hexsha": "77dddd8f4c61ad214ee6d327c6b6c320856fcf15", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app.r", "max_forks_repo_name": "elvisun/DCF-with-R", "max_forks_repo_head_hexsha": "77dddd8f4c61ad214ee6d327c6b6c320856fcf15", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.324742268, "max_line_length": 232, "alphanum_fraction": 0.6842656123, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4715812160602018}} {"text": "# Comments start with number symbols.\n\n# You can't make multi-line comments,\n# but you can stack multiple comments like so.\n\n# in Windows you can use CTRL-ENTER to execute a line.\n# on Mac it is COMMAND-ENTER\n\n\n\n#############################################################################\n# Stuff you can do without understanding anything about programming\n#############################################################################\n\n# In this section, we show off some of the cool stuff you can do in\n# R without understanding anything about programming. Do not worry\n# about understanding everything the code does. Just enjoy!\n\ndata() # browse pre-loaded data sets\ndata(rivers) # get this one: \"Lengths of Major North American Rivers\"\nls() # notice that \"rivers\" now appears in the workspace\nhead(rivers) # peek at the data set\n# 735 320 325 392 524 450\n\nlength(rivers) # how many rivers were measured?\n# 141\nsummary(rivers) # what are some summary statistics?\n# Min. 1st Qu. Median Mean 3rd Qu. Max.\n# 135.0 310.0 425.0 591.2 680.0 3710.0\n\n# make a stem-and-leaf plot (a histogram-like data visualization)\nstem(rivers)\n\n# The decimal point is 2 digit(s) to the right of the |\n#\n# 0 | 4\n# 2 | 011223334555566667778888899900001111223333344455555666688888999\n# 4 | 111222333445566779001233344567\n# 6 | 000112233578012234468\n# 8 | 045790018\n# 10 | 04507\n# 12 | 1471\n# 14 | 56\n# 16 | 7\n# 18 | 9\n# 20 |\n# 22 | 25\n# 24 | 3\n# 26 |\n# 28 |\n# 30 |\n# 32 |\n# 34 |\n# 36 | 1\n\nstem(log(rivers)) # Notice that the data are neither normal nor log-normal!\n# Take that, Bell curve fundamentalists.\n\n# The decimal point is 1 digit(s) to the left of the |\n#\n# 48 | 1\n# 50 |\n# 52 | 15578\n# 54 | 44571222466689\n# 56 | 023334677000124455789\n# 58 | 00122366666999933445777\n# 60 | 122445567800133459\n# 62 | 112666799035\n# 64 | 00011334581257889\n# 66 | 003683579\n# 68 | 0019156\n# 70 | 079357\n# 72 | 89\n# 74 | 84\n# 76 | 56\n# 78 | 4\n# 80 |\n# 82 | 2\n\n# make a histogram:\nhist(rivers, col=\"#333333\", border=\"white\", breaks=25) # play around with these parameters\nhist(log(rivers), col=\"#333333\", border=\"white\", breaks=25) # you'll do more plotting later\n\n# Here's another neat data set that comes pre-loaded. R has tons of these.\ndata(discoveries)\nplot(discoveries, col=\"#333333\", lwd=3, xlab=\"Year\",\n main=\"Number of important discoveries per year\")\nplot(discoveries, col=\"#333333\", lwd=3, type = \"h\", xlab=\"Year\",\n main=\"Number of important discoveries per year\")\n\n# Rather than leaving the default ordering (by year),\n# we could also sort to see what's typical:\nsort(discoveries)\n# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2\n# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3\n# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4\n# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12\n\nstem(discoveries, scale=2)\n#\n# The decimal point is at the |\n#\n# 0 | 000000000\n# 1 | 000000000000\n# 2 | 00000000000000000000000000\n# 3 | 00000000000000000000\n# 4 | 000000000000\n# 5 | 0000000\n# 6 | 000000\n# 7 | 0000\n# 8 | 0\n# 9 | 0\n# 10 | 0\n# 11 |\n# 12 | 0\n\nmax(discoveries)\n# 12\nsummary(discoveries)\n# Min. 1st Qu. Median Mean 3rd Qu. Max.\n# 0.0 2.0 3.0 3.1 4.0 12.0\n\n# Roll a die a few times\nround(runif(7, min=.5, max=6.5))\n# 1 4 6 1 4 6 4\n# Your numbers will differ from mine unless we set the same random.seed(31337)\n\n# Draw from a standard Gaussian 9 times\nrnorm(9)\n# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271\n# [7] -0.59975593 0.57629164 1.08455362\n\n\n\n##################################################\n# Data types and basic arithmetic\n##################################################\n\n# Now for the programming-oriented part of the tutorial.\n# In this section you will meet the important data types of R:\n# integers, numerics, characters, logicals, and factors.\n# There are others, but these are the bare minimum you need to\n# get started.\n\n# INTEGERS\n# Long-storage integers are written with L\n5L # 5\nclass(5L) # \"integer\"\n# (Try ?class for more information on the class() function.)\n# In R, every single value, like 5L, is considered a vector of length 1\nlength(5L) # 1\n# You can have an integer vector with length > 1 too:\nc(4L, 5L, 8L, 3L) # 4 5 8 3\nlength(c(4L, 5L, 8L, 3L)) # 4\nclass(c(4L, 5L, 8L, 3L)) # \"integer\"\n\n# NUMERICS\n# A \"numeric\" is a double-precision floating-point number\n5 # 5\nclass(5) # \"numeric\"\n# Again, everything in R is a vector;\n# you can make a numeric vector with more than one element\nc(3,3,3,2,2,1) # 3 3 3 2 2 1\n# You can use scientific notation too\n5e4 # 50000\n6.02e23 # Avogadro's number\n1.6e-35 # Planck length\n# You can also have infinitely large or small numbers\nclass(Inf) # \"numeric\"\nclass(-Inf) # \"numeric\"\n# You might use \"Inf\", for example, in integrate(dnorm, 3, Inf);\n# this obviates Z-score tables.\n\n# BASIC ARITHMETIC\n# You can do arithmetic with numbers\n# Doing arithmetic on a mix of integers and numerics gives you another numeric\n10L + 66L # 76 # integer plus integer gives integer\n53.2 - 4 # 49.2 # numeric minus numeric gives numeric\n2.0 * 2L # 4 # numeric times integer gives numeric\n3L / 4 # 0.75 # integer over numeric gives numeric\n3 %% 2 # 1 # the remainder of two numerics is another numeric\n# Illegal arithmetic yeilds you a \"not-a-number\":\n0 / 0 # NaN\nclass(NaN) # \"numeric\"\n# You can do arithmetic on two vectors with length greater than 1,\n# so long as the larger vector's length is an integer multiple of the smaller\nc(1,2,3) + c(1,2,3) # 2 4 6\n# Since a single number is a vector of length one, scalars are applied \n# elementwise to vectors\n(4 * c(1,2,3) - 2) / 2 # 1 3 5\n# Except for scalars, use caution when performing arithmetic on vectors with \n# different lengths. Although it can be done, \nc(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6\n# Matching lengths is better practice and easier to read\nc(1,2,3,1,2,3) * c(1,2,1,2,1,2) \n\n# CHARACTERS\n# There's no difference between strings and characters in R\n\"Horatio\" # \"Horatio\"\nclass(\"Horatio\") # \"character\"\nclass('H') # \"character\"\n# Those were both character vectors of length 1\n# Here is a longer one:\nc('alef', 'bet', 'gimmel', 'dalet', 'he')\n# =>\n# \"alef\" \"bet\" \"gimmel\" \"dalet\" \"he\"\nlength(c(\"Call\",\"me\",\"Ishmael\")) # 3\n# You can do regex operations on character vectors:\nsubstr(\"Fortuna multis dat nimis, nulli satis.\", 9, 15) # \"multis \"\ngsub('u', 'ø', \"Fortuna multis dat nimis, nulli satis.\") # \"Fortøna møltis dat nimis, nølli satis.\"\n# R has several built-in character vectors:\nletters\n# =>\n# [1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n# [20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"\nmonth.abb # \"Jan\" \"Feb\" \"Mar\" \"Apr\" \"May\" \"Jun\" \"Jul\" \"Aug\" \"Sep\" \"Oct\" \"Nov\" \"Dec\"\n\n# LOGICALS\n# In R, a \"logical\" is a boolean\nclass(TRUE) # \"logical\"\nclass(FALSE) # \"logical\"\n# Their behavior is normal\nTRUE == TRUE # TRUE\nTRUE == FALSE # FALSE\nFALSE != FALSE # FALSE\nFALSE != TRUE # TRUE\n# Missing data (NA) is logical, too\nclass(NA) # \"logical\"\n# Use | and & for logic operations.\n# OR\nTRUE | FALSE # TRUE\n# AND\nTRUE & FALSE # FALSE\n# Applying | and & to vectors returns elementwise logic operations\nc(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE\nc(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE\n# You can test if x is TRUE\nisTRUE(TRUE) # TRUE\n# Here we get a logical vector with many elements:\nc('Z', 'o', 'r', 'r', 'o') == \"Zorro\" # FALSE FALSE FALSE FALSE FALSE\nc('Z', 'o', 'r', 'r', 'o') == \"Z\" # TRUE FALSE FALSE FALSE FALSE\n\n# FACTORS\n# The factor class is for categorical data\n# Factors can be ordered (like childrens' grade levels) or unordered (like gender)\nfactor(c(\"female\", \"female\", \"male\", NA, \"female\"))\n# female female male female\n# Levels: female male\n# The \"levels\" are the values the categorical data can take\n# Note that missing data does not enter the levels\nlevels(factor(c(\"male\", \"male\", \"female\", NA, \"female\"))) # \"female\" \"male\"\n# If a factor vector has length 1, its levels will have length 1, too\nlength(factor(\"male\")) # 1\nlength(levels(factor(\"male\"))) # 1\n# Factors are commonly seen in data frames, a data structure we will cover later\ndata(infert) # \"Infertility after Spontaneous and Induced Abortion\"\nlevels(infert$education) # \"0-5yrs\" \"6-11yrs\" \"12+ yrs\"\n\n# NULL\n# \"NULL\" is a weird one; use it to \"blank out\" a vector\nclass(NULL) # NULL\nparakeet = c(\"beak\", \"feathers\", \"wings\", \"eyes\")\nparakeet\n# =>\n# [1] \"beak\" \"feathers\" \"wings\" \"eyes\"\nparakeet <- NULL\nparakeet\n# =>\n# NULL\n\n# TYPE COERCION\n# Type-coercion is when you force a value to take on a different type\nas.character(c(6, 8)) # \"6\" \"8\"\nas.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE\n# If you put elements of different types into a vector, weird coercions happen:\nc(TRUE, 4) # 1 4\nc(\"dog\", TRUE, 4) # \"dog\" \"TRUE\" \"4\"\nas.numeric(\"Bilbo\")\n# =>\n# [1] NA\n# Warning message:\n# NAs introduced by coercion\n\n# Also note: those were just the basic data types\n# There are many more data types, such as for dates, time series, etc.\n\n\n\n##################################################\n# Variables, loops, if/else\n##################################################\n\n# A variable is like a box you store a value in for later use.\n# We call this \"assigning\" the value to the variable.\n# Having variables lets us write loops, functions, and if/else statements\n\n# VARIABLES\n# Lots of way to assign stuff:\nx = 5 # this is possible\ny <- \"1\" # this is preferred\nTRUE -> z # this works but is weird\n\n# LOOPS\n# We've got for loops\nfor (i in 1:4) {\n print(i)\n}\n# We've got while loops\na <- 10\nwhile (a > 4) {\n cat(a, \"...\", sep = \"\")\n a <- a - 1\n}\n# Keep in mind that for and while loops run slowly in R\n# Operations on entire vectors (i.e. a whole row, a whole column)\n# or apply()-type functions (we'll discuss later) are preferred\n\n# IF/ELSE\n# Again, pretty standard\nif (4 > 3) {\n print(\"4 is greater than 3\")\n} else {\n print(\"4 is not greater than 3\")\n}\n# =>\n# [1] \"4 is greater than 3\"\n\n# FUNCTIONS\n# Defined like so:\njiggle <- function(x) {\n x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise\n return(x)\n}\n# Called like any other R function:\njiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043\n\n\n\n###########################################################################\n# Data structures: Vectors, matrices, data frames, and arrays\n###########################################################################\n\n# ONE-DIMENSIONAL\n\n# Let's start from the very beginning, and with something you already know: vectors.\nvec <- c(8, 9, 10, 11)\nvec # 8 9 10 11\n# We ask for specific elements by subsetting with square brackets\n# (Note that R starts counting from 1)\nvec[1] # 8\nletters[18] # \"r\"\nLETTERS[13] # \"M\"\nmonth.name[9] # \"September\"\nc(6, 8, 7, 5, 3, 0, 9)[3] # 7\n# We can also search for the indices of specific components,\nwhich(vec %% 2 == 0) # 1 3\n# grab just the first or last few entries in the vector,\nhead(vec, 1) # 8\ntail(vec, 2) # 10 11\n# or figure out if a certain value is in the vector\nany(vec == 10) # TRUE\n# If an index \"goes over\" you'll get NA:\nvec[6] # NA\n# You can find the length of your vector with length()\nlength(vec) # 4\n# You can perform operations on entire vectors or subsets of vectors\nvec * 4 # 16 20 24 28\nvec[2:3] * 5 # 25 30\nany(vec[2:3] == 8) # FALSE\n# and R has many built-in functions to summarize vectors\nmean(vec) # 9.5\nvar(vec) # 1.666667\nsd(vec) # 1.290994\nmax(vec) # 11\nmin(vec) # 8\nsum(vec) # 38\n# Some more nice built-ins:\n5:15 # 5 6 7 8 9 10 11 12 13 14 15\nseq(from=0, to=31337, by=1337)\n# =>\n# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707\n# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751\n\n# TWO-DIMENSIONAL (ALL ONE CLASS)\n\n# You can make a matrix out of entries all of the same type like so:\nmat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))\nmat\n# =>\n# [,1] [,2]\n# [1,] 1 4\n# [2,] 2 5\n# [3,] 3 6\n# Unlike a vector, the class of a matrix is \"matrix\", no matter what's in it\nclass(mat) # => \"matrix\"\n# Ask for the first row\nmat[1,] # 1 4\n# Perform operation on the first column\n3 * mat[,1] # 3 6 9\n# Ask for a specific cell\nmat[3,2] # 6\n\n# Transpose the whole matrix\nt(mat)\n# =>\n# [,1] [,2] [,3]\n# [1,] 1 2 3\n# [2,] 4 5 6\n\n# Matrix multiplication\nmat %*% t(mat)\n# =>\n# [,1] [,2] [,3]\n# [1,] 17 22 27\n# [2,] 22 29 36\n# [3,] 27 36 45\n\n# cbind() sticks vectors together column-wise to make a matrix\nmat2 <- cbind(1:4, c(\"dog\", \"cat\", \"bird\", \"dog\"))\nmat2\n# =>\n# [,1] [,2]\n# [1,] \"1\" \"dog\"\n# [2,] \"2\" \"cat\"\n# [3,] \"3\" \"bird\"\n# [4,] \"4\" \"dog\"\nclass(mat2) # matrix\n# Again, note what happened!\n# Because matrices must contain entries all of the same class,\n# everything got converted to the character class\nc(class(mat2[,1]), class(mat2[,2]))\n\n# rbind() sticks vectors together row-wise to make a matrix\nmat3 <- rbind(c(1,2,4,5), c(6,7,0,4))\nmat3\n# =>\n# [,1] [,2] [,3] [,4]\n# [1,] 1 2 4 5\n# [2,] 6 7 0 4\n# Ah, everything of the same class. No coercions. Much better.\n\n# TWO-DIMENSIONAL (DIFFERENT CLASSES)\n\n# For columns of different types, use a data frame\n# This data structure is so useful for statistical programming,\n# a version of it was added to Python in the package \"pandas\".\n\nstudents <- data.frame(c(\"Cedric\",\"Fred\",\"George\",\"Cho\",\"Draco\",\"Ginny\"),\n c(3,2,2,1,0,-1),\n c(\"H\", \"G\", \"G\", \"R\", \"S\", \"G\"))\nnames(students) <- c(\"name\", \"year\", \"house\") # name the columns\nclass(students) # \"data.frame\"\nstudents\n# =>\n# name year house\n# 1 Cedric 3 H\n# 2 Fred 2 G\n# 3 George 2 G\n# 4 Cho 1 R\n# 5 Draco 0 S\n# 6 Ginny -1 G\nclass(students$year) # \"numeric\"\nclass(students[,3]) # \"factor\"\n# find the dimensions\nnrow(students) # 6\nncol(students) # 3\ndim(students) # 6 3\n# The data.frame() function converts character vectors to factor vectors\n# by default; turn this off by setting stringsAsFactors = FALSE when\n# you create the data.frame\n?data.frame\n\n# There are many twisty ways to subset data frames, all subtly unalike\nstudents$year # 3 2 2 1 0 -1\nstudents[,2] # 3 2 2 1 0 -1\nstudents[,\"year\"] # 3 2 2 1 0 -1\n\n# An augmented version of the data.frame structure is the data.table\n# If you're working with huge or panel data, or need to merge a few data\n# sets, data.table can be a good choice. Here's a whirlwind tour:\ninstall.packages(\"data.table\") # download the package from CRAN\nrequire(data.table) # load it\nstudents <- as.data.table(students)\nstudents # note the slightly different print-out\n# =>\n# name year house\n# 1: Cedric 3 H\n# 2: Fred 2 G\n# 3: George 2 G\n# 4: Cho 1 R\n# 5: Draco 0 S\n# 6: Ginny -1 G\nstudents[name==\"Ginny\"] # get rows with name == \"Ginny\"\n# =>\n# name year house\n# 1: Ginny -1 G\nstudents[year==2] # get rows with year == 2\n# =>\n# name year house\n# 1: Fred 2 G\n# 2: George 2 G\n# data.table makes merging two data sets easy\n# let's make another data.table to merge with students\nfounders <- data.table(house=c(\"G\",\"H\",\"R\",\"S\"),\n founder=c(\"Godric\",\"Helga\",\"Rowena\",\"Salazar\"))\nfounders\n# =>\n# house founder\n# 1: G Godric\n# 2: H Helga\n# 3: R Rowena\n# 4: S Salazar\nsetkey(students, house)\nsetkey(founders, house)\nstudents <- founders[students] # merge the two data sets by matching \"house\"\nsetnames(students, c(\"house\",\"houseFounderName\",\"studentName\",\"year\"))\nstudents[,order(c(\"name\",\"year\",\"house\",\"houseFounderName\")), with=F]\n# =>\n# studentName year house houseFounderName\n# 1: Fred 2 G Godric\n# 2: George 2 G Godric\n# 3: Ginny -1 G Godric\n# 4: Cedric 3 H Helga\n# 5: Cho 1 R Rowena\n# 6: Draco 0 S Salazar\n\n# data.table makes summary tables easy\nstudents[,sum(year),by=house]\n# =>\n# house V1\n# 1: G 3\n# 2: H 3\n# 3: R 1\n# 4: S 0\n\n# To drop a column from a data.frame or data.table,\n# assign it the NULL value\nstudents$houseFounderName <- NULL\nstudents\n# =>\n# studentName year house\n# 1: Fred 2 G\n# 2: George 2 G\n# 3: Ginny -1 G\n# 4: Cedric 3 H\n# 5: Cho 1 R\n# 6: Draco 0 S\n\n# Drop a row by subsetting\n# Using data.table:\nstudents[studentName != \"Draco\"]\n# =>\n# house studentName year\n# 1: G Fred 2\n# 2: G George 2\n# 3: G Ginny -1\n# 4: H Cedric 3\n# 5: R Cho 1\n# Using data.frame:\nstudents <- as.data.frame(students)\nstudents[students$house != \"G\",]\n# =>\n# house houseFounderName studentName year\n# 4 H Helga Cedric 3\n# 5 R Rowena Cho 1\n# 6 S Salazar Draco 0\n\n# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE)\n\n# Arrays creates n-dimensional tables\n# All elements must be of the same type\n# You can make a two-dimensional table (sort of like a matrix)\narray(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))\n# =>\n# [,1] [,2] [,3] [,4]\n# [1,] 1 4 8 3\n# [2,] 2 5 9 6\n# You can use array to make three-dimensional matrices too\narray(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))\n# =>\n# , , 1\n#\n# [,1] [,2]\n# [1,] 2 8\n# [2,] 300 9\n# [3,] 4 0\n#\n# , , 2\n#\n# [,1] [,2]\n# [1,] 5 66\n# [2,] 60 7\n# [3,] 0 847\n\n# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES)\n\n# Finally, R has lists (of vectors)\nlist1 <- list(time = 1:40)\nlist1$price = c(rnorm(40,.5*list1$time,4)) # random\nlist1\n# You can get items in the list like so\nlist1$time # one way\nlist1[[\"time\"]] # another way\nlist1[[1]] # yet another way\n# =>\n# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33\n# [34] 34 35 36 37 38 39 40\n# You can subset list items like any other vector\nlist1$price[4]\n\n# Lists are not the most efficient data structure to work with in R;\n# unless you have a very good reason, you should stick to data.frames\n# Lists are often returned by functions that perform linear regressions\n\n##################################################\n# The apply() family of functions\n##################################################\n\n# Remember mat?\nmat\n# =>\n# [,1] [,2]\n# [1,] 1 4\n# [2,] 2 5\n# [3,] 3 6\n# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X\n# over rows (MAR = 1) or columns (MAR = 2)\n# That is, R does FUN to each row (or column) of X, much faster than a\n# for or while loop would do\napply(mat, MAR = 2, jiggle)\n# =>\n# [,1] [,2]\n# [1,] 3 15\n# [2,] 7 19\n# [3,] 11 23\n# Other functions: ?lapply, ?sapply\n\n# Don't feel too intimidated; everyone agrees they are rather confusing\n\n# The plyr package aims to replace (and improve upon!) the *apply() family.\ninstall.packages(\"plyr\")\nrequire(plyr)\n?plyr\n\n\n\n#########################\n# Loading data\n#########################\n\n# \"pets.csv\" is a file on the internet\n# (but it could just as easily be be a file on your own computer)\npets <- read.csv(\"http://learnxinyminutes.com/docs/pets.csv\")\npets\nhead(pets, 2) # first two rows\ntail(pets, 1) # last row\n\n# To save a data frame or matrix as a .csv file\nwrite.csv(pets, \"pets2.csv\") # to make a new .csv file\n# set working directory with setwd(), look it up with getwd()\n\n# Try ?read.csv and ?write.csv for more information\n\n\n\n#########################\n# Statistical Analysis\n#########################\n\n# Linear regression!\nlinearModel <- lm(price ~ time, data = list1)\nlinearModel # outputs result of regression\n# =>\n# Call:\n# lm(formula = price ~ time, data = list1)\n# \n# Coefficients:\n# (Intercept) time \n# 0.1453 0.4943 \nsummary(linearModel) # more verbose output from the regression\n# =>\n# Call:\n# lm(formula = price ~ time, data = list1)\n#\n# Residuals:\n# Min 1Q Median 3Q Max \n# -8.3134 -3.0131 -0.3606 2.8016 10.3992 \n#\n# Coefficients:\n# Estimate Std. Error t value Pr(>|t|) \n# (Intercept) 0.14527 1.50084 0.097 0.923 \n# time 0.49435 0.06379 7.749 2.44e-09 ***\n# ---\n# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n#\n# Residual standard error: 4.657 on 38 degrees of freedom\n# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 \n# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09\ncoef(linearModel) # extract estimated parameters\n# =>\n# (Intercept) time \n# 0.1452662 0.4943490 \nsummary(linearModel)$coefficients # another way to extract results\n# =>\n# Estimate Std. Error t value Pr(>|t|)\n# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01\n# time 0.4943490 0.06379348 7.74920901 2.440008e-09\nsummary(linearModel)$coefficients[,4] # the p-values \n# =>\n# (Intercept) time \n# 9.234021e-01 2.440008e-09 \n\n# GENERAL LINEAR MODELS\n# Logistic regression\nset.seed(1)\nlist1$success = rbinom(length(list1$time), 1, .5) # random binary\nglModel <- glm(success ~ time, data = list1, \n family=binomial(link=\"logit\"))\nglModel # outputs result of logistic regression\n# =>\n# Call: glm(formula = success ~ time, \n# family = binomial(link = \"logit\"), data = list1)\n#\n# Coefficients:\n# (Intercept) time \n# 0.17018 -0.01321 \n# \n# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual\n# Null Deviance: 55.35 \n# Residual Deviance: 55.12 AIC: 59.12\nsummary(glModel) # more verbose output from the regression\n# =>\n# Call:\n# glm(formula = success ~ time, \n# family = binomial(link = \"logit\"), data = list1)\n\n# Deviance Residuals: \n# Min 1Q Median 3Q Max \n# -1.245 -1.118 -1.035 1.202 1.327 \n# \n# Coefficients:\n# Estimate Std. Error z value Pr(>|z|)\n# (Intercept) 0.17018 0.64621 0.263 0.792\n# time -0.01321 0.02757 -0.479 0.632\n# \n# (Dispersion parameter for binomial family taken to be 1)\n#\n# Null deviance: 55.352 on 39 degrees of freedom\n# Residual deviance: 55.121 on 38 degrees of freedom\n# AIC: 59.121\n# \n# Number of Fisher Scoring iterations: 3\n\n\n#########################\n# Plots\n#########################\n\n# BUILT-IN PLOTTING FUNCTIONS\n# Scatterplots!\nplot(list1$time, list1$price, main = \"fake data\")\n# Plot regression line on existing plot\nabline(linearModel, col = \"red\")\n# Get a variety of nice diagnostics\nplot(linearModel)\n# Histograms!\nhist(rpois(n = 10000, lambda = 5), col = \"thistle\")\n# Barplots!\nbarplot(c(1,4,5,1,2), names.arg = c(\"red\",\"blue\",\"purple\",\"green\",\"yellow\"))\n\n# GGPLOT2\n# But these are not even the prettiest of R's plots\n# Try the ggplot2 package for more and better graphics\ninstall.packages(\"ggplot2\")\nrequire(ggplot2)\n?ggplot2\npp <- ggplot(students, aes(x=house))\npp + geom_histogram()\nll <- as.data.table(list1)\npp <- ggplot(ll, aes(x=time,price))\npp + geom_point()\n# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)", "meta": {"hexsha": "d7ebed49b3a1877976c88653466b160d210ccbb8", "size": 23367, "ext": "r", "lang": "R", "max_stars_repo_path": "src/tests/R.r", "max_stars_repo_name": "maxcoffer/alone-dark-theme", "max_stars_repo_head_hexsha": "ab4d64af5c5ff4032bfedb647fffb6aa59813276", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/R.r", "max_issues_repo_name": "maxcoffer/alone-dark-theme", "max_issues_repo_head_hexsha": "ab4d64af5c5ff4032bfedb647fffb6aa59813276", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/R.r", "max_forks_repo_name": "maxcoffer/alone-dark-theme", "max_forks_repo_head_hexsha": "ab4d64af5c5ff4032bfedb647fffb6aa59813276", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8810741688, "max_line_length": 105, "alphanum_fraction": 0.605084093, "num_tokens": 8262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.4715811946910883}} {"text": "########################################################\n# spectrum_analysis.r #\n# Matheus J. Castro #\n# Version 2.3 #\n# Last Modification: 11/11/2021 (month/day/year) #\n# https://github.com/MatheusJCastro/spectra_comparator #\n# Licensed under MIT License #\n########################################################\n\nlibrary(\"minpack.lm\")\n\n# Files Names\nfiles = c(\"Spectrum_R=14026.csv\", \"Spectrum_R=6000.csv\")\n\n# Load Spectrum 1\nspec_wave_1 = read.table(files[1], sep=\",\", skip=0, nrow=2, header=FALSE, row.names=1, check.names=FALSE)\n\nspec_data_1 = read.table(files[1], sep=\"\", skip=2, header=TRUE, check.names=FALSE)\nspec_data_1 = spec_data_1[,1]\n\n# Load Spectrum 2\nspec_wave_2 = read.table(files[2], sep=\",\", skip=0, nrow=2, header=FALSE, row.names=1, check.names=FALSE)\n\nspec_data_2 = read.table(files[2], sep=\"\", skip=2, header=TRUE, check.names=FALSE)\nspec_data_2 = spec_data_2[,1]\n\n# Calculate wavelengths\nspec_wave_1 = spec_wave_1[\"CRVAL_1\",1] + spec_wave_1[\"CD1_1\",1] * seq.int(0, length(spec_data_1)-1)\nspec_wave_2 = spec_wave_2[\"CRVAL_1\",1] + spec_wave_2[\"CD1_1\",1] * seq.int(0, length(spec_data_2)-1)\n\n# Plot Spectra\npng(file=\"Espectra.png\", width=1200, height=675)\npar(mfrow=c(1, 2))\n\nplot(spec_wave_1, spec_data_1, main=\"Spectra Comparison\", \n xlab=\"Wavelength\", ylab=\"Intensity\", type=\"l\", lty=1,\n cex.axis=2, cex.lab=1.5, cex.main=2)\nlines(spec_wave_2, spec_data_2, col=\"blue\")\nlabels = c(unlist(strsplit(sub(\".*_\", \"\", files[1]), \"[.]\"))[1])\nlabels = c(labels, unlist(strsplit(sub(\".*_\", \"\", files[2]), \"[.]\"))[1])\nlegend(\"topright\", legend=c(labels),\n col=c(\"black\", \"blue\"), lty=1, cex=2)\ngrid()\n\ninterval = 1550:1700\nplot(spec_wave_1[interval], spec_data_1[interval], main=\"Spectra Comparison - zoom in\", \n xlab=\"Wavelength\", ylab=\"Intensity\", type=\"l\", lty=1,\n cex.axis=2, cex.lab=1.5, cex.main=2)\nlines(spec_wave_2[interval], spec_data_2[interval], col=\"blue\")\nlabels = c(unlist(strsplit(sub(\".*_\", \"\", files[1]), \"[.]\"))[1])\nlabels = c(labels, unlist(strsplit(sub(\".*_\", \"\", files[2]), \"[.]\"))[1])\nlegend(\"topright\", legend=c(labels),\n col=c(\"black\", \"blue\"), lty=1, cex=2)\ngrid()\n\n# Find Peaks\nfind_peaks <- function(spec_data, threshold=NULL, half_window=10){\n peaks = c()\n\n if(is.null(threshold))\n threshold = mean(spec_data)\n\n lenspec = length(spec_data)\n for(i in 1:lenspec){\n imin = i - half_window\n imax = i + half_window\n if(imin < 1)\n imin = 1\n if(imax > lenspec)\n imax = lenspec\n\n if(spec_data[i] == max(spec_data[imin:imax]) & spec_data[i] > threshold)\n peaks = c(peaks, i)\n }\n\n return(peaks)\n}\n\npeaks1 = find_peaks(spec_data_1)\n# segments(x0=spec_wave_1[peaks1], y0=spec_data_1[peaks1]*1.1, \n # y1=spec_data_1[peaks1]*1.1+10000, col=\"red\")\n\npeaks2 = find_peaks(spec_data_2)\n# segments(x0=spec_wave_2[peaks2], y0=spec_data_2[peaks2]*1.1, \n # y1=spec_data_2[peaks2]*1.1+10000, col=\"green\")\n\n# Find Min Max of each Peak\nfind_min_max_gauss <- function(spec_data, peak){\n miny_old = spec_data[peak]\n j = peak\n while(TRUE){\n miny = spec_data[j]\n if(miny <= miny_old){\n miny_old = miny\n j = j - 1\n } else{\n ind_miny = j\n break\n }\n }\n\n maxy_old = spec_data[peak]\n j = peak\n while(TRUE){\n maxy = spec_data[j]\n if(maxy <= maxy_old){\n maxy_old = maxy\n j = j + 1\n } else{\n ind_maxy = j\n break\n }\n }\n\n return(c(ind_miny, ind_maxy))\n}\n\n# Gaussian function\ngauss <- function(x, a, m, s){\n G = a * exp(-1/2 * ((x-m)/s)**2)\n}\n\n# Gaussian Fit and Spectrum Analysis\ngaussian_fit <- function(spec_wave, spec_data, peaks, plot=FALSE){\n stds = c()\n new_peaks = c()\n\n for(i in peaks){\n ind_min_max = find_min_max_gauss(spec_data, i)\n\n x = spec_wave[ind_min_max[1]:ind_min_max[2]]\n y = spec_data[ind_min_max[1]:ind_min_max[2]]\n\n if(plot){\n png(file=paste(\"Fits/Fit_\", format(spec_wave[i], digits=2, nsmall=2), \".png\", sep=\"\"), width=1200, height=675)\n plot(x, y, main=\"Gauss Fit\", xlab=\"Wavelength\", ylab=\"Intensity\", type=\"l\", lty=1, lwd=5,\n cex.axis=2, cex.lab=1.5, cex.main=2)\n }\n\n chi_square <- function(par){\n y_gauss = gauss(x, par[1], par[2], par[3])\n chi = y - y_gauss\n if(plot) lines(x, gauss(x, par[1], par[2], par[3]), col=\"lightblue\", lty=2)\n return(chi)\n }\n\n fit = nls.lm(par=c(1, spec_wave[i], 0.1),# upper=c(280000, spec_wave[i]+100, 5), \n fn=chi_square, control=nls.lm.control(maxiter=500))\n \n if(plot){\n x = seq(min(x), max(x), 0.01)\n lines(x, gauss(x, fit$par[1], fit$par[2], fit$par[3]), col=\"red\", lty=2, lwd=2)\n graphics.off()\n }\n \n if(fit$par[3] <= 1 & fit$par[3] > 0){\n stds = c(stds, fit$par[3])\n new_peaks = c(new_peaks, i)\n }\n }\n return(list(std=stds, peak=new_peaks))\n}\n\n# Standard Devations\nfit_res = gaussian_fit(spec_wave_1, spec_data_1, peaks1)\nstds1 = fit_res$std\nstd1p = format(mean(stds1), digits=2, nsmall=2)\npeaks1 = fit_res$peak\n\nfit_res = gaussian_fit(spec_wave_2, spec_data_2, peaks2)\nstds2 = fit_res$std\nstd2p = format(mean(stds2), digits=2, nsmall=2)\npeaks2 = fit_res$peak\n\n# Plot Stds\npng(file=\"Desvio_padrao.png\", width=1200, height=675)\npar(mfrow=c(1, 2))\n\nhist(stds1, main=paste(\"Standard Deviation of Original Spectrum Peaks\\nwith mean\", std1p), \n ylab=\"Frequency\", xlab=\"Values\", breaks=15, col=\"lightblue\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\nabline(v=mean(stds1), lty=2, col=\"red\")\n\nhist(stds2, main=paste(\"Standard Deviation of Reduced Spectrum Peaks\\nwith mean\", std2p), \n ylab=\"Frequency\", xlab=\"Values\", breaks=15, col=\"lightblue\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\nabline(v=mean(stds2), lty=2, col=\"red\")\n\n# Plot Correlation of Stds and Wavelength\npng(file=\"Desvio_Padrao_por_Comp_Onda.png\", width=1200, height=675)\npar(mfrow=c(1, 2))\n\nplot(spec_wave_1[peaks1], stds1, main=\"Original Spectrum\\nMean of Peaks x Standard Deviation\", \n xlab=\"Wavelength\", ylab=expression(sigma), lty=1, col=\"blue\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\n\nplot(spec_wave_2[peaks2], stds2, main=\"Reduced Spectrum\\nMean of Peaks x Standard Deviation\", \n xlab=\"Wavelength\", ylab=expression(sigma), lty=1, col=\"red\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\n\n# Change of means for each peak\ncross_match <- function(spec1, spec2, radius=10){\n matchs = matrix(, nrow=0, ncol=2)\n colnames(matchs) <- c(\"Spec1\", \"Spec2\")\n\n if(length(spec1) >= length(spec2)){\n spec_big = spec1\n spec_few = spec2\n } else{\n spec_big = spec2\n spec_few = spec1\n }\n\n for(i in 1:length(spec_big)){\n val1 = spec_big[i]\n for(j in 1:length(spec_few)){\n val2 = spec_few[j]\n if(val2-radius <= val1 & val2+radius >= val1){\n if(i %in% matchs[,1]){\n ind_rep = which(matchs[,1]==i)\n if(abs(val1-val2) < abs(val1-spec_few[matchs[ind_rep,2]]))\n matchs[ind_rep,2] = j\n } else{\n matchs = rbind(matchs, c(i, j))\n }\n }\n }\n }\n\n if(length(spec1) < length(spec2)){\n order = c(\"Spec2\", \"Spec1\")\n matchs = matchs[,order]\n }\n\n return(matchs)\n}\n\nmatch = cross_match(spec_wave_1[peaks1], spec_wave_2[peaks2])\nmatchc1 = spec_wave_1[peaks1[match[,1]]]\nmatchc2 = spec_wave_2[peaks2[match[,2]]]\n\n# Plot Change of Means\npng(file=\"Mudanca_das_Medias.png\", width=1200, height=675)\npar(mfrow=c(1, 2))\n\nplot(matchc1, abs(matchc1-matchc2), \n main=\"Wavelengths of Original Spectrum\\nPeaks x Drifting from Reduced Spectrum\", \n xlab=\"Original Spectrum Wavelength\", ylab=\"Drifting from Reduced Spectrum Peaks\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\nabline(h=quantile(abs(matchc1-matchc2), prob=c(.75)), lty=2, col=\"red\")\n\nhist(abs(matchc1-matchc2), breaks=10, \n main=\"Histogram of Peak Value Differences\",\n xlab=\"Change of Means\", ylab=\"Frequency\", col=\"lightblue\",\n cex.axis=2, cex.lab=1.5, cex.main=2)\nabline(v=mean(abs(matchc1-matchc2)), lty=2, col=\"red\")\n\n# Quartile of Peaks Change\nsave_txt = \"Qartile of Peaks Change\"\nsave_txt = paste(save_txt, \"\\n50% =\", quantile(abs(matchc1-matchc2), prob=c(.50)))\nsave_txt = paste(save_txt, \"\\n75% =\", quantile(abs(matchc1-matchc2), prob=c(.75)))\n\n# Identificacion of Blended Lines\nblend_indentify <- function(spec1, spec2, radius=0.1){\n blends = matrix(, nrow=0, ncol=2)\n colnames(blends) <- c(\"Spec1\", \"Spec2\")\n\n if(length(spec1) >= length(spec2)){\n spec_big = spec1\n spec_few = spec2\n } else{\n spec_big = spec2\n spec_few = spec1\n }\n\n for(i in 1:length(spec_big)){\n val1 = spec_big[i]\n actual_blend = c()\n for(j in 1:length(spec_few)){\n val2 = spec_few[j]\n if(val2-radius <= val1 & val2+radius >= val1){\n actual_blend = c(actual_blend, j)\n }\n\n }\n if(length(actual_blend) > 1){\n for(j in 1:length(actual_blend))\n blends = rbind(blends, c(i, actual_blend[j]))\n }\n }\n\n if(length(spec1) < length(spec2)){\n order = c(\"Spec2\", \"Spec1\")\n blends = blends[,order]\n }\n\n return(blends)\n}\n\nblend = blend_indentify(spec_wave_1[peaks1], spec_wave_2[peaks2], radius=3*mean(abs(matchc1-matchc2)))\nblends1_wave = spec_wave_1[peaks1[blend[,1]]]\nblends2_wave = spec_wave_2[peaks2[blend[,2]]]\nblends1_data = spec_data_1[peaks1[blend[,1]]]\n\n# Find Correlation of Blend and Intensity\ncorr_blends <- function(bl1_w, bl1_d){\n intensities = c(50, 40, 25, 12.5, 6.25, 3.125, 0) * 1000\n\n intens_blends = list()\n\n for(i in 1:length(intensities)){\n blends_count = c()\n for(j in 1:length(bl1_w)){\n if(bl1_d[j] >= intensities[i]){\n if(i == 1)\n blends_count = c(blends_count, bl1_w[j])\n else if(bl1_d[j] <= intensities[i-1])\n blends_count = c(blends_count, bl1_w[j])\n }\n }\n intens_blends[[paste(intensities[i])]] = unique(blends_count)\n }\n \n return(intens_blends)\n}\n\nblends_correlation = corr_blends(blends1_wave, blends1_data)\n\n# Plot Blended Lines in Spectra\npng(file=\"Linhas_com_Blends.png\", width=1200, height=675)\nplot(spec_wave_1, spec_data_1, main=\"Blended Lines found for each Intensity level\", \n xlab=\"Wavelength\", ylab=\"Intensity\", type=\"l\", lty=1,\n cex.axis=2, cex.lab=1.5, cex.main=2)\n\nfor(i in names(blends_correlation)){\n y_inten = rep(as.numeric(i), length(blends_correlation[[i]]))\n points(blends_correlation[[i]], y_inten, col=1+which(i==names(blends_correlation)), pch=4, lwd=3)\n}\n\nlabels = names(blends_correlation)\nlegend(\"topright\", legend=labels, title=\"Intensities levels\",\n col=2:(length(names(blends_correlation))+1), lty=1, cex=2)\n\n# Fit Correlation of Blend and Intensity\ne_func <- function(x, a, b, c){\n E = b * exp(a*x) + c\n}\n\nchi_square_e_func <- function(x, y, par){\n e_teor = e_func(x, par[1], par[2], par[3])\n chi = sum(((y - e_teor)^2)/e_teor)\n return(chi)\n}\n\nintens = as.numeric(names(blends_correlation))\nfit = optim(par=c(-0.0001, 50, 1), fn=chi_square_e_func, x=as.numeric(names(blends_correlation)), y=lengths(blends_correlation))\nsave_txt = paste(save_txt, \"\\nExponential of b*e^(ax)+c\")\nsave_txt = paste(save_txt, \"\\na =\", fit$par[1])\nsave_txt = paste(save_txt, \"\\nb =\", fit$par[2])\nsave_txt = paste(save_txt, \"\\nc =\", fit$par[3])\n\nx_inten = seq(min(intens), max(intens), length=1000)\ny_count = e_func(x_inten, fit$par[1], fit$par[2], fit$par[3])\n\n# Plot Blended Lines as Intensity function\npng(file=\"Relacao_Blend_Intensidade.png\", width=1200, height=675)\n\nplot(intens, lengths(blends_correlation), main=\"Blended Lines as funtction of Intensity\", \n xlab=\"Intensity\", ylab=\"Blend Line Count\", pch=8, cex=2, lwd=2,\n cex.axis=2, cex.lab=1.5, cex.main=2)\n\nlines(x_inten, y_count, lty=2, col=\"red\")\n\n# Save Results\nfl <- file(\"Resultados.txt\")\nwriteLines(save_txt, fl)\nclose(fl)\n", "meta": {"hexsha": "cc0087e1b0171cbc040bc15731937e57c3aa3c6c", "size": 13354, "ext": "r", "lang": "R", "max_stars_repo_path": "spectrum_analysis.r", "max_stars_repo_name": "MatheusJCastro/spectra_comparator", "max_stars_repo_head_hexsha": "0d5e2fde2c459b598a987eb42d3dd1cfcb08d78b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-24T13:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T13:05:51.000Z", "max_issues_repo_path": "spectrum_analysis.r", "max_issues_repo_name": "MatheusJCastro/spectra_comparator", "max_issues_repo_head_hexsha": "0d5e2fde2c459b598a987eb42d3dd1cfcb08d78b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectrum_analysis.r", "max_forks_repo_name": "MatheusJCastro/spectra_comparator", "max_forks_repo_head_hexsha": "0d5e2fde2c459b598a987eb42d3dd1cfcb08d78b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.328042328, "max_line_length": 131, "alphanum_fraction": 0.5602066796, "num_tokens": 3971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.47158118861434073}} {"text": "library(SuperLearner)\r\nsource('utils.r')\r\nsource('slfunctions.r')\r\n\r\nfitnuisance <- function(data, nfolds,\r\n sl_lib = c('SL.myglmnet', 'SL.myglm', 'SL.mean')) {\r\n\r\n candidatesg <- candidatese <- candidatesm <- candidatesb <-\r\n candidatesd <- sl_lib\r\n ## extract data\r\n Y <- data[, \"Y\"]\r\n Z <- data[, substr(names(data), 1, 1) == \"Z\"]\r\n L <- data[, \"L\"]\r\n A <- data[, \"A\"]\r\n W <- data[, substr(names(data), 1, 1) == \"W\"]\r\n\r\n ## observations and cross-validation\r\n n <- length(A)\r\n valSets <- split(sample(seq_len(n)), rep(seq_len(nfolds), length = n))\r\n\r\n ## fit nuisance functions\r\n fitg <- mySL(\r\n Y = A,\r\n X = W,\r\n family = stats::binomial(),\r\n SL.library = candidatesg,\r\n validRows = valSets\r\n )\r\n fite <- mySL(\r\n Y = A,\r\n X = data.frame(Z, W),\r\n family = stats::binomial(),\r\n SL.library = candidatese,\r\n validRows = valSets\r\n )\r\n fitm <- mySL(\r\n Y = Y,\r\n X = data.frame(Z, L, A, W),\r\n family = binomial(),\r\n SL.library = candidatesm,\r\n validRows = valSets\r\n )\r\n fitb <- mySL(\r\n Y = L,\r\n X = data.frame(A, W),\r\n family = stats::binomial(),\r\n SL.library = candidatesb,\r\n validRows = valSets\r\n )\r\n fitd <- mySL(\r\n Y = L,\r\n X = data.frame(Z, A, W),\r\n family = stats::binomial(),\r\n SL.library = candidatesd,\r\n validRows = valSets\r\n )\r\n\r\n return(list(fitg = fitg, fite = fite, fitm = fitm, fitb = fitb,\r\n fitd = fitd, valSets = valSets))\r\n}\r\n\r\nestimators <- function(data, delta, nuisance, seed, type,\r\n sl_lib = c('SL.myglmnet', 'SL.myglm', 'SL.mean')) {\r\n\r\n candidatesv <- candidatess <- candidatesq <- candidatesubar <- sl_lib\r\n\r\n ## extract data\r\n Y <- data[, \"Y\"]\r\n Z <- data[, substr(names(data), 1, 1) == \"Z\"]\r\n L <- data[, \"L\"]\r\n A <- data[, \"A\"]\r\n W <- data[, substr(names(data), 1, 1) == \"W\"]\r\n\r\n n <- length(A)\r\n\r\n g1 <- truncate(nuisance$fitg$SL.predict[, 1])\r\n e1 <- truncate(nuisance$fite$SL.predict[, 1])\r\n b1A <- nuisance$fitb$SL.predict[, 1]\r\n d1A <- truncate(nuisance$fitd$SL.predict[, 1])\r\n\r\n g <- A * g1 + (1 - A) * (1 - g1)\r\n e <- A * e1 + (1 - A) * (1 - e1)\r\n b <- L * b1A + (1 - L) * (1 - b1A)\r\n d <- L * d1A + (1 - L) * (1 - d1A)\r\n\r\n b11 <- predict(nuisance$fitb, newdata = data.frame(A = 1, W))$pred[, 1]\r\n b10 <- predict(nuisance$fitb, newdata = data.frame(A = 0, W))$pred[, 1]\r\n d11 <- truncate(predict(nuisance$fitd, newdata = data.frame(Z, A = 1, W))$pred[, 1])\r\n d10 <- truncate(predict(nuisance$fitd, newdata = data.frame(Z, A = 0, W))$pred[, 1])\r\n m11 <- predict(nuisance$fitm, newdata = data.frame(Z, L = 1, A = 1, W))$pred[, 1]\r\n m10 <- predict(nuisance$fitm, newdata = data.frame(Z, L = 1, A = 0, W))$pred[, 1]\r\n m01 <- predict(nuisance$fitm, newdata = data.frame(Z, L = 0, A = 1, W))$pred[, 1]\r\n m00 <- predict(nuisance$fitm, newdata = data.frame(Z, L = 0, A = 0, W))$pred[, 1]\r\n\r\n m <- nuisance$fitm$SL.predict[, 1]\r\n m1A <- A * m11 + (1 - A) * m10\r\n m0A <- A * m01 + (1 - A) * m00\r\n\r\n uA <- m1A * b1A + m0A * (1 - b1A)\r\n u1 <- m11 * b11 + m01 * (1 - b11)\r\n u0 <- m10 * b10 + m00 * (1 - b10)\r\n\r\n vout <- m * b / d\r\n sout <- m * b / d * g / e\r\n\r\n if(sd(vout) < .Machine$double.eps * 10) {\r\n v1 <- v0 <- rep(mean(vout), length(vout))\r\n } else {\r\n fitv <- mySL(\r\n Y = vout,\r\n X = data.frame(L, A, W),\r\n family = stats::gaussian(),\r\n SL.library = candidatesv,\r\n validRows = nuisance$valSets\r\n )\r\n v1 <- predict(fitv, newdata = data.frame(L = 1, A, W))$pred[, 1]\r\n v0 <- predict(fitv, newdata = data.frame(L = 0, A, W))$pred[, 1]\r\n }\r\n\r\n if(sd(sout) < .Machine$double.eps * 10) {\r\n s1 <- s0 <- rep(mean(sout), length(sout))\r\n } else {\r\n fits <- mySL(\r\n Y = sout,\r\n X = data.frame(L, A, W),\r\n family = stats::gaussian(),\r\n SL.library = candidatess,\r\n validRows = nuisance$valSets\r\n )\r\n s1 <- predict(fits, newdata = data.frame(L = 1, A, W))$pred[, 1]\r\n s0 <- predict(fits, newdata = data.frame(L = 0, A, W))$pred[, 1]\r\n }\r\n\r\n if(sd(uA) < .Machine$double.eps * 10) {\r\n ubar1 <- ubar0 <- rep(mean(uA), length(uA))\r\n } else {\r\n fitubar <- mySL(\r\n Y = uA,\r\n X = data.frame(A, W),\r\n family = stats::gaussian(),\r\n SL.library = candidatesubar,\r\n validRows = nuisance$valSets\r\n )\r\n ubar1 <- predict(fitubar, newdata = data.frame(A = 1, W))$pred[, 1]\r\n ubar0 <- predict(fitubar, newdata = data.frame(A = 0, W))$pred[, 1]\r\n }\r\n\r\n ubarA <- A * ubar1 + (1 - A) * ubar0\r\n q1 <- ubar1 - ubar0\r\n\r\n if(sd(u1 - u0) < .Machine$double.eps * 10) {\r\n q2 <- rep(mean(u1 - u0), length(u1))\r\n } else {\r\n fitq2 <- mySL(\r\n Y = u1 - u0,\r\n X = data.frame(W),\r\n family = stats::gaussian(),\r\n SL.library = candidatesq,\r\n validRows = nuisance$valSets\r\n )\r\n q2 <- fitq2$SL.predict[, 1]\r\n }\r\n\r\n g1delta <- gdelta1(g1, delta)\r\n gdelta <- A * g1delta + (1 - A) * (1 - g1delta)\r\n\r\n HD <- b / d * (1 - gdelta / e)\r\n HI <- b / d * gdelta * (1 / e - 1 / g)\r\n KD <- v1 - v0 - gdelta / g * (s1 - s0)\r\n KI <- gdelta / g * (s1 - s0 - v1 + v0)\r\n MD <- - g1delta * (1 - g1delta) / (g1 * (1 - g1)) * q2\r\n MI <- g1delta * (1 - g1delta) / (g1 * (1 - g1)) * (q2 - q1)\r\n J <- - gdelta / g\r\n\r\n de <- ubar1 * g1 + ubar0 * (1 - g1) - (u1 * g1delta + u0 * (1 - g1delta))\r\n ie <- (u1 - ubar1) * g1delta + (u0 - ubar0) * (1 - g1delta)\r\n eifD <- HD * (Y - m) + KD * (L - b1A) + MD * (A - g1) + (uA - ubarA) + de\r\n eifI <- HI * (Y - m) + KI * (L - b1A) + MI * (A - g1) + J * (uA - ubarA) + ie\r\n\r\n osde <- mean(eifD)\r\n osie <- mean(eifI)\r\n seosde <- sd(eifD) / sqrt(n)\r\n seosie <- sd(eifI) / sqrt(n)\r\n\r\n ## now, compute the TMLE\r\n stopcrit <- FALSE\r\n iter <- 1\r\n\r\n ## iterative TMLE\r\n while (!stopcrit) {\r\n tiltm <- glm(Y ~ 0 + offset(qlogis(bound(m))) + HD + HI, family = binomial())\r\n tiltb <- glm(L ~ 0 + offset(qlogis(bound(b1A))) + KD + KI, family = binomial())\r\n tiltg <- glm(A ~ 0 + offset(qlogis(bound(g1))) + MD + MI, family = binomial())\r\n\r\n m <- predict(tiltm, type = 'response')\r\n b1A <- predict(tiltb, type = 'response')\r\n g1 <- predict(tiltg, type = 'response')\r\n\r\n HD11 <- b11 / d11 * (1 - g1delta / e1)\r\n HI11 <- b11 / d11 * g1delta * (1 / e1 - 1 / g1)\r\n HD10 <- b10 / d10 * (1 - (1 - g1delta) / (1 - e1))\r\n HI10 <- b10 / d10 * (1 - g1delta) * (1 / (1 - e1) - 1 / (1 - g1))\r\n\r\n HD01 <- (1 - b11) / (1 - d11) * (1 - g1delta / e1)\r\n HI01 <- (1 - b11) / (1 - d11) * g1delta * (1 / e1 - 1 / g1)\r\n HD00 <- (1 - b10) / (1 - d10) * (1 - (1 - g1delta) / (1 - e1))\r\n HI00 <- (1 - b10) / (1 - d10) * (1 - g1delta) * (1 / (1 - e1) - 1 / (1 - g1))\r\n\r\n m11 <- plogis(qlogis(bound(m11)) + coef(tiltm)[1] * HD11 + coef(tiltm)[2] * HI11)\r\n m10 <- plogis(qlogis(bound(m10)) + coef(tiltm)[1] * HD10 + coef(tiltm)[2] * HI10)\r\n m01 <- plogis(qlogis(bound(m01)) + coef(tiltm)[1] * HD01 + coef(tiltm)[2] * HI01)\r\n m00 <- plogis(qlogis(bound(m00)) + coef(tiltm)[1] * HD00 + coef(tiltm)[2] * HI00)\r\n\r\n g <- A * g1 + (1 - A) * (1 - g1)\r\n b <- L * b1A + (1 - L) * (1 - b1A)\r\n g1delta <- gdelta1(g1, delta)\r\n gdelta <- A * g1delta + (1 - A) * (1 - g1delta)\r\n\r\n HD <- b / d * (1 - gdelta / e)\r\n HI <- b / d * gdelta * (1 / e - 1 / g)\r\n KD <- v1 - v0 - gdelta / g * (s1 - s0)\r\n KI <- gdelta / g * (s1 - s0 - v1 + v0)\r\n MD <- - g1delta * (1 - g1delta) / (g1 * (1 - g1)) * q2\r\n MI <- g1delta * (1 - g1delta) / (g1 * (1 - g1)) * (q2 - q1)\r\n\r\n de <- ubar1 * g1 + ubar0 * (1 - g1) - (u1 * g1delta + u0 * (1 - g1delta))\r\n ie <- (u1 - ubar1) * g1delta + (u0 - ubar0) * (1 - g1delta)\r\n\r\n eifDp <- HD * (Y - m) + KD * (L - b1A) + MD * (A - g1)\r\n eifIp <- HI * (Y - m) + KI * (L - b1A) + MI * (A - g1)\r\n\r\n ## iterate iterator\r\n iter <- iter + 1\r\n ## note: interesting stopping criterion\r\n stopcrit <- max(abs(c(mean(eifDp), mean(eifIp)))) <\r\n max(c(sd(eifDp), sd(eifIp))) * log(n) / n | iter > 6\r\n }\r\n\r\n J <- - gdelta / g\r\n J1 <- - g1delta / g1\r\n J0 <- - (1 - g1delta) / (1 - g1)\r\n\r\n m1A <- A * m11 + (1 - A) * m10\r\n m0A <- A * m01 + (1 - A) * m00\r\n\r\n uA <- m1A * b1A + m0A * (1 - b1A)\r\n u1 <- m11 * b11 + m01 * (1 - b11)\r\n u0 <- m10 * b10 + m00 * (1 - b10)\r\n\r\n tiltu <- glm(uA ~ offset(qlogis(bound(ubarA))) + J, family = binomial())\r\n ubar1 <- plogis(coef(tiltu)[1] + qlogis(bound(ubar1)) + coef(tiltu)[2] * J1)\r\n ubar0 <- plogis(coef(tiltu)[1] + qlogis(bound(ubar0)) + coef(tiltu)[2] * J0)\r\n ubarA <- A * ubar1 + (1 - A) * ubar0\r\n\r\n de <- ubar1 * g1 + ubar0 * (1 - g1) - (u1 * g1delta + u0 * (1 - g1delta))\r\n ie <- (u1 - ubar1) * g1delta + (u0 - ubar0) * (1 - g1delta)\r\n\r\n eifD <- HD * (Y - m) + KD * (L - b1A) + MD * (A - g1) + (uA - ubarA) + de\r\n eifI <- HI * (Y - m) + KI * (L - b1A) + MI * (A - g1) + J * (uA - ubarA) + ie\r\n\r\n tmlede <- mean(de)\r\n tmleie <- mean(ie)\r\n setmlede <- sd(eifD) / sqrt(n)\r\n setmleie <- sd(eifI) / sqrt(n)\r\n\r\n out <- data.frame(\r\n parameter = c('DE', 'IE', 'DE', 'IE'),\r\n estimator = c('OS', 'OS', 'TMLE', 'TMLE'),\r\n estimate = c(osde, osie, tmlede, tmleie),\r\n ses = c(seosde, seosie, setmlede, setmleie),\r\n n = n,\r\n seed = seed,\r\n type = type)\r\n\r\n return(out)\r\n}\r\n", "meta": {"hexsha": "573b1eabf1baf252392db25294c36561fd31928e", "size": 9952, "ext": "r", "lang": "R", "max_stars_repo_path": "sandbox/intmedlite/sandbox/estim.r", "max_stars_repo_name": "nhejazi/medshift", "max_stars_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-01-11T17:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T01:12:08.000Z", "max_issues_repo_path": "sandbox/intmedlite/sandbox/estim.r", "max_issues_repo_name": "nhejazi/medshift", "max_issues_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-01-15T19:11:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T06:54:52.000Z", "max_forks_repo_path": "sandbox/intmedlite/sandbox/estim.r", "max_forks_repo_name": "nhejazi/medshift", "max_forks_repo_head_hexsha": "48b2b3a65b40bd35366497c2bf77ad6bac527d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-02T15:56:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T21:35:25.000Z", "avg_line_length": 35.9277978339, "max_line_length": 90, "alphanum_fraction": 0.4553858521, "num_tokens": 3694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4715188227285354}} {"text": "subroutine stl(y,n,np,ns,nt,nl,isdeg,itdeg,ildeg,nsjump,ntjump,nljump,ni,no,rw,\n\tseason,trend,work)\n\ninteger n, np, ns, nt, nl, isdeg, itdeg, ildeg, nsjump, ntjump, nljump, ni, no, k\ninteger newns, newnt, newnl, newnp\nreal y(n), rw(n), season(n), trend(n), work(n+2*np,5)\nlogical userw\n\nuserw = .false.\nk = 0\ndo i = 1,n\n\ttrend(i) = 0.0\nnewns = max0(3,ns)\nnewnt = max0(3,nt)\nnewnl = max0(3,nl)\nnewnp = max0(2,np)\nif(mod(newns,2)==0) newns = newns + 1\t#make odd\nif(mod(newnt,2)==0) newnt = newnt + 1\nif(mod(newnl,2)==0) newnl = newnl + 1\nrepeat {\n\tcall onestp(y,n,newnp,newns,newnt,newnl,isdeg,itdeg,ildeg,nsjump,ntjump,nljump,\n\tni,userw,rw,season, trend, work)\n\tk = k+1\n\tif(k>no) break\n\tdo i = 1,n\n\t\twork(i,1) = trend(i)+season(i)\n\tcall rwts(y,n,work(1,1),rw)\n\tuserw = .true.\n\t}\nif (no<=0)\n\tdo i = 1,n\n\t\trw(i) = 1.0\nreturn\nend\n\n\n\nsubroutine ess(y,n,len,ideg,njump,userw,rw,ys,res)\n\ninteger n, len, ideg, njump, newnj, nleft, nright, nsh, k, i, j\nreal y(n), rw(n), ys(n), res(n), delta\nlogical ok, userw\n\nif(n<2) { ys(1) = y(1); return }\nnewnj = min0(njump, n-1)\nif(len>=n) {\t#len > or = n\n\tnleft = 1\n\tnright = n\n\tdo i = 1,n,newnj {\n\t\tcall est(y,n,len,ideg,float(i),ys(i),nleft,nright,res,userw,rw,ok)\n\t\tif(!ok) ys(i) = y(i)\n\t\t}\n\t}\nelse if(newnj==1) {\t# newnj equal to one, len less than n\n\tnsh = (len+1)/2\n\tnleft = 1\n\tnright = len\n\tdo i = 1,n {\t# fitted value at i\n\t\tif(i>nsh && nright!=n) {\n\t\t\tnleft = nleft+1\n\t\t\tnright = nright+1\n\t\t\t}\n\t\tcall est(y,n,len,ideg,float(i),ys(i),nleft,nright,res,userw,rw,ok)\n\t\tif(!ok) ys(i) = y(i)\n\t\t}\n\t}\nelse { # newnj greater than one, len less than n\n\tnsh = (len+1)/2\n\tdo i = 1,n,newnj {\t# fitted value at i\n\t\tif(i=n-nsh+1) {\n\t\t\tnleft = n-len+1\n\t\t\tnright = n\n\t\t\t}\n\t\telse {\n\t\t\tnleft = i-nsh+1\n\t\t\tnright = len+i-nsh\n\t\t\t}\n\t\tcall est(y,n,len,ideg,float(i),ys(i),nleft,nright,res,userw,rw,ok)\n\t\tif(!ok) ys(i) = y(i)\n\t\t}\n\t}\nif(newnj!=1){\n\tdo i = 1,n-newnj,newnj {\n\t\tdelta = (ys(i+newnj)-ys(i))/float(newnj)\n\t\tdo j = i+1,i+newnj-1\n\t\t\tys(j) = ys(i)+delta*float(j-i)\n\t\t}\n\tk = ((n-1)/newnj)*newnj+1\n\tif(k!=n) {\n\t\tcall est(y,n,len,ideg,float(n),ys(n),nleft,nright,res,userw,rw,ok)\n\t\tif(!ok) ys(n) = y(n)\n\t\tif(k!=n-1) {\n\t\t\tdelta = (ys(n)-ys(k))/float(n-k)\n\t\t\tdo j = k+1,n-1\n\t\t\t\tys(j) = ys(k)+delta*float(j-k)\n\t\t\t}\n\t\t}\n\t}\nreturn\nend\n\n\nsubroutine est(y,n,len,ideg,xs,ys,nleft,nright,w,userw,rw,ok)\n\ninteger n, len, ideg, nleft, nright, j\nreal y(n), w(n), rw(n), xs, ys, range, h, h1, h9, a, b, c, r\nlogical userw,ok\n\nrange = float(n)-float(1)\nh = amax1(xs-float(nleft),float(nright)-xs)\nif (len>n) h = h+float((len-n)/2)\nh9 = .999*h\nh1 = .001*h\n# compute weights\na = 0.0\ndo j = nleft,nright {\n\tw(j) = 0.\n\tr = abs(float(j)-xs)\n\tif (r<=h9) {\n\t\tif (r<=h1) w(j) = 1.\n\t\telse w(j) = (1.0-(r/h)**3)**3\n\t\tif (userw) w(j) = rw(j)*w(j)\n\t\ta = a+w(j)\n\t\t}\n\t}\nif (a<=0.0)\n\tok = .false.\nelse {\t# weighted least squares\n\tok = .true.\n\tdo j = nleft,nright\t# make sum of w(j) == 1\n\t\tw(j) = w(j)/a\n\tif ((h>0.)&(ideg>0)) {\t# use linear fit\n\t\ta = 0.0\n\t\tdo j = nleft,nright\t# weighted center of x values\n\t\t\ta = a+w(j)*float(j)\n\t\tb = xs-a\n\t\tc = 0.0\n\t\tdo j = nleft,nright\n\t\t\tc = c+w(j)*(float(j)-a)**2\n\t\tif (sqrt(c)>.001*range) {\n\t\t\tb = b/c\n# points are spread out enough to compute slope\n\t\t\tdo j = nleft,nright\n\t\t\t\tw(j) = w(j)*(b*(float(j)-a)+1.0)\n\t\t\t}\n\t\t}\n\tys = 0.0\n\tdo j = nleft,nright\n\t\tys = ys+w(j)*y(j)\n\t}\nreturn\nend\n\n\n\nsubroutine fts(x,n,np,trend,work)\n\ninteger n, np\nreal x(n), trend(n), work(n)\n\ncall ma(x,n,np,trend)\ncall ma(trend,n-np+1,np,work)\ncall ma(work,n-2*np+2,3,trend)\nreturn\nend\n\n\nsubroutine ma(x, n, len, ave)\n\ninteger n, len, i, j, k, m, newn\nreal x(n), ave(n), flen, v\n\nnewn = n-len+1\nflen = float(len)\nv = 0.0\n# get the first average\ndo i = 1,len\n\tv = v+x(i)\nave(1) = v/flen\t\nif (newn>1) {\n\tk = len\n\tm = 0\n\tdo j = 2, newn {\n# window down the array\n\t\tk = k+1\n\t\tm = m+1\n\t\tv = v-x(m)+x(k)\n\t\tave(j) = v/flen\t\n\t}\n}\nreturn\nend\n\n\nsubroutine onestp(y,n,np,ns,nt,nl,isdeg,itdeg,ildeg,nsjump,ntjump,nljump,ni,\n\tuserw,rw,season,trend,work)\n\ninteger n,ni,np,ns,nt,nsjump,ntjump,nl,nljump,isdeg,itdeg,ildeg\nreal y(n),rw(n),season(n),trend(n),work(n+2*np,5)\nlogical userw\n\ndo j = 1,ni {\n\tdo i = 1,n\n\t\twork(i,1) = y(i)-trend(i)\n\tcall ss(work(1,1),n,np,ns,isdeg,nsjump,userw,rw,work(1,2),work(1,3),work(1,4),\n\t\twork(1,5),season)\n\tcall fts(work(1,2),n+2*np,np,work(1,3),work(1,1))\n\tcall ess(work(1,3),n,nl,ildeg,nljump,.false.,work(1,4),work(1,1),work(1,5))\n\tdo i = 1,n\n\t\tseason(i) = work(np+i,2)-work(i,1)\n\tdo i = 1,n\n\t\twork(i,1) = y(i)-season(i)\n\tcall ess(work(1,1),n,nt,itdeg,ntjump,userw,rw,trend,work(1,3))\n\t}\nreturn\nend\n\n\nsubroutine rwts(y,n,fit,rw)\n\ninteger mid(2), n\nreal y(n), fit(n), rw(n), cmad, c9, c1, r\n\ndo i = 1,n\n\trw(i) = abs(y(i)-fit(i))\nmid(1) = n/2+1\nmid(2) = n-mid(1)+1\ncall psort(rw,n,mid,2)\ncmad = 3.0*(rw(mid(1))+rw(mid(2)))\t#6 * median abs resid\nc9 = .999*cmad\nc1 = .001*cmad\ndo i = 1,n {\n\tr = abs(y(i)-fit(i))\n\tif (r<=c1) rw(i) = 1.\n\telse if (r<=c9) rw(i) = (1.0-(r/cmad)**2)**2\n\telse rw(i) = 0.\n\t}\nreturn\nend\n\n\n\nsubroutine ss(y,n,np,ns,isdeg,nsjump,userw,rw,season,work1,work2,work3,work4)\n\ninteger n, np, ns, isdeg, nsjump, nright, nleft, i, j, k\nreal y(n), rw(n), season(n+2*np), work1(n), work2(n), work3(n), work4(n), xs\nlogical userw,ok\n\nfor(j=1; j<=np; j=j+1){\n\tk = (n-j)/np+1\n\tdo i = 1,k\n\t\twork1(i) = y((i-1)*np+j)\n\tif(userw)\n\t\tdo i = 1,k\n\t\t\twork3(i) = rw((i-1)*np+j)\n\tcall ess(work1,k,ns,isdeg,nsjump,userw,work3,work2(2),work4)\n\txs = 0\n\tnright = min0(ns,k)\n\tcall est(work1,k,ns,isdeg,xs,work2(1),1,nright,work4,userw,work3,ok)\n\tif(!ok) work2(1) = work2(2)\n\txs = k+1\n\tnleft = max0(1,k-ns+1)\n\tcall est(work1,k,ns,isdeg,xs,work2(k+2),nleft,k,work4,userw,work3,ok)\n\tif(!ok) work2(k+2) = work2(k+1)\n\tdo m = 1,k+2\n\t\tseason((m-1)*np+j) = work2(m)\n\t}\nreturn\nend\nsubroutine stlez(y, n, np, ns, isdeg, itdeg, robust, no, rw, season, trend, work)\n\nlogical robust\ninteger n, i, j, np, ns, no, nt, nl, ni, nsjump, ntjump, nljump, newns, newnp\ninteger isdeg, itdeg, ildeg\nreal y(n), rw(n), season(n), trend(n), work(n+2*np,7)\nreal maxs, mins, maxt, mint, maxds, maxdt, difs, dift\n\nildeg = itdeg\nnewns = max0(3,ns)\nif(mod(newns,2)==0) newns = newns+1\nnewnp = max0(2,np)\nnt = (1.5*newnp)/(1 - 1.5/newns) + 0.5\nnt = max0(3,nt)\nif(mod(nt,2)==0) nt = nt+1\nnl = newnp\nif(mod(nl,2)==0) nl = nl+1\nif(robust) ni = 1\nelse ni = 2\nnsjump = max0(1,int(float(newns)/10 + 0.9))\nntjump = max0(1,int(float(nt)/10 + 0.9))\nnljump = max0(1,int(float(nl)/10 + 0.9))\ndo i = 1,n\n\ttrend(i) = 0.0\ncall onestp(y,n,newnp,newns,nt,nl,isdeg,itdeg,ildeg,nsjump,ntjump,nljump,ni,\n\t.false.,rw,season,trend,work)\nno = 0\nif(robust){\n\tfor(j=1; j<=15; j=j+1){\t#robustness iterations\n\t\tdo i = 1,n{\t#initialize for testing\n\t\t\twork(i,6) = season(i)\n\t\t\twork(i,7) = trend(i)\n\t\t\twork(i,1) = trend(i)+season(i)\n\t\t\t}\n\t\tcall rwts(y,n,work(1,1),rw)\n\t\tcall onestp(y, n, newnp, newns, nt, nl, isdeg, itdeg, ildeg, nsjump,\n\t\t\tntjump, nljump, ni, .true., rw, season, trend, work)\n\t\tno = no+1\n\t\tmaxs = work(1,6)\n\t\tmins = work(1,6)\n\t\tmaxt = work(1,7)\n\t\tmint = work(1,7)\n\t\tmaxds = abs(work(1,6) - season(1))\n\t\tmaxdt = abs(work(1,7) - trend(1))\n\t\tdo i = 2,n{\n\t\t\tif(maxswork(i,6)) mins = work(i,6)\n\t\t\tif(mint>work(i,7)) mint = work(i,7)\n\t\t\tdifs = abs(work(i,6) - season(i))\n\t\t\tdift = abs(work(i,7) - trend(i))\n\t\t\tif(maxds10) {\n# first order a(i),a(j),a((i+j)/2), and use median to split the data\n\t\t\t\t10 k = i\n\t\t\t\tij = (i+j)/2\n\t\t\t\tt = a(ij)\n\t\t\t\tif (a(i)>t) {\n\t\t\t\t\ta(ij) = a(i)\n\t\t\t\t\ta(i) = t\n\t\t\t\t\tt = a(ij)\n\t\t\t\t\t}\n\t\t\t\tl = j\n\t\t\t\tif (a(j)t) {\n\t\t\t\t\t\ta(ij) = a(i)\n\t\t\t\t\t\ta(i) = t\n\t\t\t\t\t\tt = a(ij)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\trepeat {\n\t\t\t\t\tl = l-1\n\t\t\t\t\tif (a(l)<=t) {\n\t\t\t\t\t\ttt = a(l)\n\t\t\t\t\t\trepeat\n# split the data into a(i to l).lt.t, a(k to j).gt.t\n\t\t\t\t\t\t\tk = k+1\n\t\t\t\t\t\t\tuntil(a(k)>=t)\n\t\t\t\t\t\tif (k>l) break\n\t\t\t\t\t\ta(l) = a(k)\n\t\t\t\t\t\ta(k) = tt\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tindl(m) = jl\n\t\t\t\tindu(m) = ju\n\t\t\t\tp = m\n\t\t\t\tm = m+1\n# split the larger of the segments\n\t\t\t\tif (l-i<=j-k) {\n\t\t\t\t\til(p) = k\n\t\t\t\t\tiu(p) = j\n\t\t\t\t\tj = l\n\t\t\t\t\trepeat {\n\t\t\t\t\t\tif (jl>ju) next 3\n\t\t\t\t\t\tif (ind(ju)<=j) break\n\t\t\t\t\t\tju = ju-1\n\t\t\t\t\t\t}\n\t\t\t\t\tindl(p) = ju+1\n\t\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\til(p) = i\n\t\t\t\t\tiu(p) = l\n\t\t\t\t\ti = k\n\t\t\t\t\trepeat {\n# skip all segments not corresponding to an entry in ind\n\t\t\t\t\t\tif (jl>ju) next 3\n\t\t\t\t\t\tif (ind(jl)>=i) break\n\t\t\t\t\t\tjl = jl+1\n\t\t\t\t\t\t}\n\t\t\t\t\tindu(p) = jl-1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (i==1) break\n\t\t\ti = i-1\n\t\t\trepeat {\n\t\t\t\ti = i+1\n\t\t\t\tif (i==j) break\n\t\t\t\tt = a(i+1)\n\t\t\t\tif (a(i)>t) {\n\t\t\t\t\tk = i\n\t\t\t\t\trepeat {\n\t\t\t\t\t\ta(k+1) = a(k)\n\t\t\t\t\t\tk = k-1\n\t\t\t\t\t\t}\n\t\t\t\t\t\tuntil(t>=a(k))\n\t\t\t\t\ta(k+1) = t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nreturn\nend\n", "meta": {"hexsha": "4c964bb2192c2423890f14e7d8fd9feaa688514f", "size": 9362, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/StlPerfTest/fortran_benchmark/stl.r", "max_stars_repo_name": "shahgoshtasbi/stl-decomp-4j", "max_stars_repo_head_hexsha": "9e28dfcdeeae53023242890c0fca61766fb44613", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2017-04-20T01:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:17:37.000Z", "max_issues_repo_path": "examples/StlPerfTest/fortran_benchmark/stl.r", "max_issues_repo_name": "shahgoshtasbi/stl-decomp-4j", "max_issues_repo_head_hexsha": "9e28dfcdeeae53023242890c0fca61766fb44613", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-05-29T12:39:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-05T21:13:33.000Z", "max_forks_repo_path": "examples/StlPerfTest/fortran_benchmark/stl.r", "max_forks_repo_name": "shahgoshtasbi/stl-decomp-4j", "max_forks_repo_head_hexsha": "9e28dfcdeeae53023242890c0fca61766fb44613", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2017-05-15T22:07:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T08:05:15.000Z", "avg_line_length": 20.9440715884, "max_line_length": 81, "alphanum_fraction": 0.5583208716, "num_tokens": 4218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.471498491068562}} {"text": "###############################################################################\n# NMDS_bioenv\n#------------------------------------------------------------------------------\n# by Umer Zeeshan Ijaz (http://userweb.eng.gla.ac.uk/umer.ijaz)\n# \n###############################################################################\n\n#==============================================================================\n# LIBRARY DEPENDENCE\n#==============================================================================\nlibrary(vegan)\nlibrary(ggplot2)\nlibrary(grid)\n\n\n#==============================================================================\n# Let's rock'n'roll!\n#==============================================================================\n# \n# Tutorial on plotting significant taxa and environmental variables on an NMDS \n# plot using ggplot2.\n# by Umer Zeeshan Ijaz (http://userweb.eng.gla.ac.uk/umer.ijaz)\n# \n \n# This R script is an extension of vegan library's bioenv()\n# function and uses the bio.env() and bio.step() of\n#\thttp://menugget.blogspot.co.uk/2011/06/clarke-and-ainsworths-bioenv-and-bvstep.html\n#\tThe original author suggested these functions to overcome\n#\tthe inflexibility of the bioenv() function which uses\n#\ta similarity matrix based on normalized \"euclidean\" distance.\n# The new functions are given below and implement the following algorithms: \n# Clarke, K. R & Ainsworth, M. 1993. A method of linking multivariate community structure to environmental variables. Marine Ecology Progress Series, 92, 205-219.\n# Clarke, K. R., Gorley, R. N., 2001. PRIMER v5: User Manual/Tutorial. PRIMER-E, Plymouth, UK.\n# Clarke, K. R., Warwick, R. M., 2001. Changes in Marine Communities: An Approach to Statistical Analysis and Interpretation, 2nd edition. PRIMER-E Ltd, Plymouth, UK.\n# Clarke, K. R., Warwick, R. M., 1998. Quantifying structural redundancy in ecological communities. Oecologia, 113:278-289. \n \nbv.step <- function(fix.mat, var.mat, \n fix.dist.method=\"bray\", var.dist.method=\"euclidean\", correlation.method=\"spearman\",\n scale.fix=FALSE, scale.var=TRUE,\n max.rho=0.95,\n min.delta.rho=0.001,\n random.selection=TRUE,\n prop.selected.var=0.2,\n num.restarts=10,\n var.always.include=NULL,\n var.exclude=NULL,\n output.best=10\n){\n \n if(dim(fix.mat)[1] != dim(var.mat)[1]){stop(\"fixed and variable matrices must have the same number of rows\")}\n if(sum(var.always.include %in% var.exclude) > 0){stop(\"var.always.include and var.exclude share a variable\")}\n require(vegan)\n \n if(scale.fix){fix.mat <- scale(fix.mat)}else{fix.mat <- fix.mat}\n if(scale.var){var.mat <- scale(var.mat)}else{var.mat <- var.mat}\n \n fix.dist <- vegdist(as.matrix(fix.mat), method=fix.dist.method)\n \n # an initial removal phase\n var.dist.full <- vegdist(as.matrix(var.mat), method=var.dist.method)\n full.cor <- suppressWarnings(cor.test(fix.dist, var.dist.full, method=correlation.method))$estimate\n var.comb <- combn(1:ncol(var.mat), ncol(var.mat)-1)\n RES <- data.frame(var.excl=rep(NA,ncol(var.comb)), n.var=ncol(var.mat)-1, rho=NA)\n for(i in 1:dim(var.comb)[2]){\n var.dist <- vegdist(as.matrix(var.mat[,var.comb[,i]]), method=var.dist.method)\n temp <- suppressWarnings(cor.test(fix.dist, var.dist, method=correlation.method))\n RES$var.excl[i] <- c(1:ncol(var.mat))[-var.comb[,i]]\n RES$rho[i] <- temp$estimate\n }\n delta.rho <- RES$rho - full.cor\n exclude <- sort(unique(c(RES$var.excl[which(abs(delta.rho) < min.delta.rho)], var.exclude)))\n \n if(random.selection){\n num.restarts=num.restarts\n prop.selected.var=prop.selected.var\n prob <- rep(1,ncol(var.mat))\n if(prop.selected.var< 1){\n prob[exclude] <- 0\n }\n n.selected.var <- min(sum(prob),prop.selected.var*dim(var.mat)[2])\n } else {\n num.restarts=1\n prop.selected.var=1 \n prob <- rep(1,ncol(var.mat))\n n.selected.var <- min(sum(prob),prop.selected.var*dim(var.mat)[2])\n }\n \n RES_TOT <- c()\n for(i in 1:num.restarts){\n step=1\n RES <- data.frame(step=step, step.dir=\"F\", var.incl=NA, n.var=0, rho=0)\n attr(RES$step.dir, \"levels\") <- c(\"F\",\"B\")\n best.comb <- which.max(RES$rho)\n best.rho <- RES$rho[best.comb]\n delta.rho <- Inf\n selected.var <- sort(unique(c(sample(1:dim(var.mat)[2], n.selected.var, prob=prob), var.always.include)))\n while(best.rho < max.rho & delta.rho > min.delta.rho & RES$n.var[best.comb] < length(selected.var)){\n # forward step\n step.dir=\"F\"\n step=step+1\n var.comb <- combn(selected.var, RES$n.var[best.comb]+1, simplify=FALSE)\n if(RES$n.var[best.comb] == 0){\n var.comb.incl <- 1:length(var.comb)\n } else {\n var.keep <- as.numeric(unlist(strsplit(RES$var.incl[best.comb], \",\")))\n temp <- NA*1:length(var.comb)\n for(j in 1:length(temp)){\n temp[j] <- all(var.keep %in% var.comb[[j]]) \n }\n var.comb.incl <- which(temp==1)\n }\n \n RES.f <- data.frame(step=rep(step, length(var.comb.incl)), step.dir=step.dir, var.incl=NA, n.var=RES$n.var[best.comb]+1, rho=NA)\n for(f in 1:length(var.comb.incl)){\n var.incl <- var.comb[[var.comb.incl[f]]]\n var.incl <- var.incl[order(var.incl)]\n var.dist <- vegdist(as.matrix(var.mat[,var.incl]), method=var.dist.method)\n temp <- suppressWarnings(cor.test(fix.dist, var.dist, method=correlation.method))\n RES.f$var.incl[f] <- paste(var.incl, collapse=\",\")\n RES.f$rho[f] <- temp$estimate\n }\n \n last.F <- max(which(RES$step.dir==\"F\"))\n RES <- rbind(RES, RES.f[which.max(RES.f$rho),])\n best.comb <- which.max(RES$rho)\n delta.rho <- RES$rho[best.comb] - best.rho \n best.rho <- RES$rho[best.comb]\n \n if(best.comb == step){\n while(best.comb == step & RES$n.var[best.comb] > 1){\n # backward step\n step.dir=\"B\"\n step <- step+1\n var.keep <- as.numeric(unlist(strsplit(RES$var.incl[best.comb], \",\")))\n var.comb <- combn(var.keep, RES$n.var[best.comb]-1, simplify=FALSE)\n RES.b <- data.frame(step=rep(step, length(var.comb)), step.dir=step.dir, var.incl=NA, n.var=RES$n.var[best.comb]-1, rho=NA)\n for(b in 1:length(var.comb)){\n var.incl <- var.comb[[b]]\n var.incl <- var.incl[order(var.incl)]\n var.dist <- vegdist(as.matrix(var.mat[,var.incl]), method=var.dist.method)\n temp <- suppressWarnings(cor.test(fix.dist, var.dist, method=correlation.method))\n RES.b$var.incl[b] <- paste(var.incl, collapse=\",\")\n RES.b$rho[b] <- temp$estimate\n }\n RES <- rbind(RES, RES.b[which.max(RES.b$rho),])\n best.comb <- which.max(RES$rho)\n best.rho <- RES$rho[best.comb]\n }\n } else {\n break()\n }\n \n }\n \n RES_TOT <- rbind(RES_TOT, RES[2:dim(RES)[1],])\n print(paste(round((i/num.restarts)*100,3), \"% finished\"))\n }\n \n RES_TOT <- unique(RES_TOT[,3:5])\n \n \n if(dim(RES_TOT)[1] > output.best){\n order.by.best <- RES_TOT[order(RES_TOT$rho, decreasing=TRUE)[1:output.best],]\n } else {\n order.by.best <- RES_TOT[order(RES_TOT$rho, decreasing=TRUE), ]\n }\n rownames(order.by.best) <- NULL\n \n order.by.i.comb <- c()\n for(i in 1:length(selected.var)){\n f1 <- which(RES_TOT$n.var==i)\n f2 <- which.max(RES_TOT$rho[f1])\n order.by.i.comb <- rbind(order.by.i.comb, RES_TOT[f1[f2],])\n }\n rownames(order.by.i.comb) <- NULL\n \n if(length(exclude)<1){var.exclude=NULL} else {var.exclude=exclude}\n out <- list(\n order.by.best=order.by.best,\n order.by.i.comb=order.by.i.comb,\n best.model.vars=paste(colnames(var.mat)[as.numeric(unlist(strsplit(order.by.best$var.incl[1], \",\")))], collapse=\",\"),\n best.model.rho=order.by.best$rho[1],\n var.always.include=var.always.include,\n var.exclude=var.exclude\n )\n out\n \n}\n \nbio.env <- function(fix.mat, var.mat, \n fix.dist.method=\"bray\", var.dist.method=\"euclidean\", correlation.method=\"spearman\",\n scale.fix=FALSE, scale.var=TRUE,\n output.best=10,\n var.max=ncol(var.mat)\n){\n if(dim(fix.mat)[1] != dim(var.mat)[1]){stop(\"fixed and variable matrices must have the same number of rows\")}\n if(var.max > dim(var.mat)[2]){stop(\"var.max cannot be larger than the number of variables (columns) in var.mat\")}\n \n require(vegan)\n \n combn.sum <- sum(factorial(ncol(var.mat))/(factorial(1:var.max)*factorial(ncol(var.mat)-1:var.max)))\n \n if(scale.fix){fix.mat <- scale(fix.mat)}else{fix.mat <- fix.mat}\n if(scale.var){var.mat <- scale(var.mat)}else{var.mat <- var.mat}\n fix.dist <- vegdist(fix.mat, method=fix.dist.method)\n RES_TOT <- c()\n best.i.comb <- c()\n iter <- 0\n for(i in 1:var.max){\n var.comb <- combn(1:ncol(var.mat), i, simplify=FALSE)\n RES <- data.frame(var.incl=rep(NA, length(var.comb)), n.var=i, rho=0)\n for(f in 1:length(var.comb)){\n iter <- iter+1\n var.dist <- vegdist(as.matrix(var.mat[,var.comb[[f]]]), method=var.dist.method)\n temp <- suppressWarnings(cor.test(fix.dist, var.dist, method=correlation.method))\n RES$var.incl[f] <- paste(var.comb[[f]], collapse=\",\")\n RES$rho[f] <- temp$estimate\n if(iter %% 100 == 0){print(paste(round(iter/combn.sum*100, 3), \"% finished\"))}\n }\n \n order.rho <- order(RES$rho, decreasing=TRUE)\n best.i.comb <- c(best.i.comb, RES$var.incl[order.rho[1]])\n if(length(order.rho) > output.best){\n RES_TOT <- rbind(RES_TOT, RES[order.rho[1:output.best],])\n } else {\n RES_TOT <- rbind(RES_TOT, RES)\n }\n }\n rownames(RES_TOT) <- NULL\n \n if(dim(RES_TOT)[1] > output.best){\n order.by.best <- order(RES_TOT$rho, decreasing=TRUE)[1:output.best]\n } else {\n order.by.best <- order(RES_TOT$rho, decreasing=TRUE)\n }\n OBB <- RES_TOT[order.by.best,]\n rownames(OBB) <- NULL\n \n order.by.i.comb <- match(best.i.comb, RES_TOT$var.incl)\n OBC <- RES_TOT[order.by.i.comb,]\n rownames(OBC) <- NULL\n \n out <- list(\n order.by.best=OBB,\n order.by.i.comb=OBC,\n best.model.vars=paste(colnames(var.mat)[as.numeric(unlist(strsplit(OBB$var.incl[1], \",\")))], collapse=\",\") ,\n best.model.rho=OBB$rho[1]\n )\n out\n}\n \nabund_table <- read.csv(\"SPE_pitlatrine.csv\",row.names=1,check.names=FALSE)\n\n# Transpose the data to have sample names on rows\nabund_table <- t(abund_table)\nmeta_table <- read.csv(\"ENV_pitlatrine.csv\",row.names=1,check.names=FALSE)\n\n# Just a check to ensure that the samples in meta_table are in the same order as in abund_table\nmeta_table <- meta_table[rownames(abund_table),]\n\n# Get grouping information\ngrouping_info <- data.frame(row.names=rownames(abund_table),t(as.data.frame(strsplit(rownames(abund_table),\"_\"))))\n \n# Parameters\ncmethod <- \"pearson\" # Correlation method to use: pearson, pearman, kendall\nfmethod <- \"bray\" # Fixed distance method: euclidean, manhattan, gower, altGower, canberra, bray, kulczynski, morisita,horn, binomial, and cao\nvmethod <- \"bray\" # Variable distance method: euclidean, manhattan, gower, altGower, canberra, bray, kulczynski, morisita,horn, binomial, and cao\nnmethod <- \"bray\" # NMDS distance method: euclidean, manhattan, gower, altGower, canberra, bray, kulczynski, morisita,horn, binomial, and cao\n \nres <- bio.env(wisconsin(abund_table), meta_table,fix.dist.method=fmethod, var.dist.method=vmethod, correlation.method=cmethod,\n scale.fix=FALSE, scale.var=TRUE) \n \n# Get the 10 best subset of environmental variables\nenvNames <- colnames(meta_table)\nbestEnvFit <- \"\"\nfor(i in (1:length(res$order.by.best$var.incl)))\n{\n bestEnvFit[i] <- paste(paste(envNames[as.numeric(unlist(strsplit(res$order.by.best$var.incl[i], split=\",\")))],collapse=' + '), \" = \",res$order.by.best$rho[i],sep=\"\")\n}\nbestEnvFit <- data.frame(bestEnvFit)\ncolnames(bestEnvFit) <- \"Best combination of environmental variables with similarity score\"\n \nres.bv.step.biobio <- bv.step(wisconsin(abund_table), wisconsin(abund_table), \n fix.dist.method=fmethod, var.dist.method=vmethod,correlation.method=cmethod,\n scale.fix=FALSE, scale.var=FALSE, \n max.rho=0.95, min.delta.rho=0.001,\n random.selection=TRUE,\n prop.selected.var=0.3,\n num.restarts=10,\n output.best=10,\n var.always.include=NULL) \n \n# Get the 10 best subset of taxa\ntaxaNames <- colnames(abund_table)\nbestTaxaFit <- \"\"\nfor(i in (1:length(res.bv.step.biobio$order.by.best$var.incl)))\n{\n bestTaxaFit[i] <- paste(paste(taxaNames[as.numeric(unlist(strsplit(res.bv.step.biobio$order.by.best$var.incl[i], split=\",\")))],collapse=' + '), \" = \",res.bv.step.biobio$order.by.best$rho[i],sep=\"\")\n}\nbestTaxaFit <- data.frame(bestTaxaFit)\ncolnames(bestTaxaFit) <- \"Best combination of taxa with similarity score\"\n \n# > bestTaxaFit\n# Best combination of taxa with similarity score\n# 1 Bacilli + Bacteroidia + Chrysiogenetes + Clostridia + Dehalococcoidetes + Fibrobacteria + Flavobacteria + Fusobacteria + Gammaproteobacteria + Methanomicrobia + Mollicutes + Opitutae + Synergistia + Thermomicrobia + Unknown = 0.900998476657462\n# 2 Bacilli + Bacteroidia + Clostridia + Dehalococcoidetes + Fibrobacteria + Flavobacteria + Fusobacteria + Gammaproteobacteria + Methanomicrobia + Mollicutes + Opitutae + Synergistia + Thermomicrobia + Unknown = 0.899912718316228\n# 3 Bacilli + Bacteroidia + Clostridia + Dehalococcoidetes + Fibrobacteria + Flavobacteria + Fusobacteria + Gammaproteobacteria + Methanomicrobia + Mollicutes + Opitutae + Synergistia + Thermomicrobia = 0.896821772937576\n# 4 Clostridia + Dehalococcoidetes + Deltaproteobacteria + Epsilonproteobacteria + Erysipelotrichi + Flavobacteria + Fusobacteria + Methanobacteria + Mollicutes + Opitutae + Planctomycetacia + Sphingobacteria + Subdivision3 + Synergistia + Thermomicrobia = 0.892670058822226\n# 5 Bacilli + Bacteroidia + Clostridia + Dehalococcoidetes + Fibrobacteria + Flavobacteria + Fusobacteria + Gammaproteobacteria + Methanomicrobia + Opitutae + Synergistia + Thermomicrobia = 0.892533063335985\n# 6 Clostridia + Dehalococcoidetes + Deltaproteobacteria + Epsilonproteobacteria + Erysipelotrichi + Flavobacteria + Fusobacteria + Methanobacteria + Mollicutes + Opitutae + Planctomycetacia + Sphingobacteria + Subdivision3 + Synergistia = 0.891217789278463\n# 7 Clostridia + Dehalococcoidetes + Deltaproteobacteria + Epsilonproteobacteria + Erysipelotrichi + Flavobacteria + Fusobacteria + Mollicutes + Opitutae + Planctomycetacia + Sphingobacteria + Subdivision3 + Synergistia = 0.888669881927483\n# 8 Bacilli + Bacteroidia + Clostridia + Dehalococcoidetes + Fibrobacteria + Flavobacteria + Fusobacteria + Gammaproteobacteria + Opitutae + Synergistia + Thermomicrobia = 0.887052815492516\n# 9 Clostridia + Dehalococcoidetes + Deltaproteobacteria + Epsilonproteobacteria + Erysipelotrichi + Flavobacteria + Fusobacteria + Opitutae + Planctomycetacia + Sphingobacteria + Subdivision3 + Synergistia = 0.885880090785632\n# 10 Acidobacteria_Gp4 + Actinobacteria + Bacilli + Betaproteobacteria + Clostridia + Dehalococcoidetes + Erysipelotrichi + Fibrobacteria + Lentisphaeria + Methanomicrobia + Opitutae + Sphingobacteria + Thermomicrobia + Unknown = 0.882956559638505\n \n# Generate NMDS plot\nMDS_res=metaMDS(abund_table, distance = nmethod, k = 2, trymax = 50)\n \nbio.keep <- as.numeric(unlist(strsplit(res.bv.step.biobio$order.by.best$var.incl[1], \",\")))\nbio.fit <- envfit(MDS_res, abund_table[,bio.keep,drop=F], perm = 999)\n \n# use the best set of environmental variables in env.keep\neval(parse(text=paste(\"env.keep <- c(\",res$order.by.best$var.incl[1],\")\",sep=\"\")))\nenv.fit <- envfit(MDS_res, meta_table[,env.keep,drop=F], perm = 999) \n \n# Get site information\ndf <- scores(MDS_res,display=c(\"sites\"))\n \n# Add grouping information\ndf <- data.frame(df,Type=grouping_info[rownames(df),1])\n \n# Get the vectors for bioenv.fit\ndf_biofit <- scores(bio.fit,display=c(\"vectors\"))\ndf_biofit <- df_biofit*vegan:::ordiArrowMul(df_biofit)\ndf_biofit <- as.data.frame(df_biofit)\n \n# Get the vectors for env.fit\ndf_envfit <- scores(env.fit,display=c(\"vectors\"))\ndf_envfit <- df_envfit*vegan:::ordiArrowMul(df_envfit)\ndf_envfit <- as.data.frame(df_envfit)\n \n#==============================================================================\n# Draw samples\n#==============================================================================\n\np <- ggplot()\np <- p+geom_point(data=df,aes(NMDS1,NMDS2,colour=Type))\n# Draw taxas\np <- p+geom_segment(data=df_biofit, aes(x = 0, y = 0, xend = NMDS1, yend = NMDS2),\n arrow = arrow(length = unit(0.2, \"cm\")),color=\"# 808080\",alpha=0.5)\n \np <- p+geom_text(data=as.data.frame(df_biofit*1.1),aes(NMDS1, NMDS2, label = rownames(df_biofit)),color=\"# 808080\",alpha=0.5)\n# Draw environmental variables\np <- p+geom_segment(data=df_envfit, aes(x = 0, y = 0, xend = NMDS1, yend = NMDS2),\n arrow = arrow(length = unit(0.2, \"cm\")),color=\"# 4C005C\",alpha=0.5)\n \np <- p+geom_text(data=as.data.frame(df_envfit*1.1),aes(NMDS1, NMDS2, label = rownames(df_envfit)),color=\"# 4C005C\",alpha=0.5)\np <- p+theme_bw()\npdf(\"NMDS_bioenv.pdf\")\nprint(p)\ndev.off()", "meta": {"hexsha": "d304fe66b36d3f6a886d9817ed124a78dea0243a", "size": 17924, "ext": "r", "lang": "R", "max_stars_repo_path": "NMDS/NMDS_bioenv.r", "max_stars_repo_name": "isix/R", "max_stars_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NMDS/NMDS_bioenv.r", "max_issues_repo_name": "isix/R", "max_issues_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NMDS/NMDS_bioenv.r", "max_forks_repo_name": "isix/R", "max_forks_repo_head_hexsha": "806e2a22e5abd93dc7933d3b9e8c3368562e1eaa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6509695291, "max_line_length": 275, "alphanum_fraction": 0.6127538496, "num_tokens": 5286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47133307470744684}} {"text": "#' @title calcKristWettedSA\n#'\n#'@description Calculate hull wetted surface area (\\code{wettedSA}) (m^2)\n#' using the Kristensen method.\n#'\n#' @param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}}).\n#' Must align with \\code{paxTugShipTypes},\n#'\\code{tankerBulkCarrierGCargoShipTypes}, and \\code{containerShipTypes}\n#'groupings\n#'@param maxDisplacement Maximum ship displacement (vector of numericals, m^3)\n#'@param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'@param actualDraft Actual draft (vector of numericals, m)\n#'@param lwl Waterline length (vector of numericals, m) (see \\code{\\link{calclwl}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param Cbw Waterline block coefficient (vector of numericals, dimensionless)\n#'(see \\code{\\link{calcCbw}})\n#'@param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#'@param paxTugShipTypes Ship types specified in input \\code{shipTypes} to be\n#'modeled as passengers and tug vessels (vector of strings)\n#'@param tankerBulkCarrierGCargoShipTypes Ship types specified in input\n#'\\code{shipTypes} to be modeled as tankers, bulk carriers and general cargo\n#'vessels (vector of strings)\n#'@param containerShipTypes Ship types specified in input \\code{shipTypes}to be\n#'modeled as container ships (vector of strings)\n#'\n#' @details\n#'\n#' This method this requires ship types to be grouped. Use the\n#' \\code{paxTugShipTypes}, \\code{tankerBulkCarrierGCargoShipTypes}, and\n#' \\code{containerShipTypes} grouping parameters to provide these ship\n#' type groupings. Any ship types not included in this grouping will be\n#' considered as miscellaneous vessels.\n#'\n#'\n#' Container ship wetted surface area:\n#'\n#' = 0.995(disp./lloyds draft + 1.9 * Lwl * lloyds draft)-2.4(lloyds draft-actual draft)(lwl+breadth)\n#'\n#' Bulk carrier, tanker, and general cargo ship wetted surface area:\n#'\n#' = 0.99(disp./lloyds draft + 1.9 * Lwl * lloyds draft)-2(lloyds draft- actual draft)(lwl+breadth)\n#'\n#' Cruise ships and tugs treated as twin screw RORO in Kristensen formulas on\n#' the basis of sample of vessels from Lloyds and their number of propellers.\n#'\n#' Twin Screw RORO wetted surface area:\n#'\n#' = 1.21(disp./lloyds draft +1.3*lwl*lloyds draft)*(1.2-0.34*Cbw)-2.5(lloyds draft-actual draft)*(lwl+breadth)\n#'\n#' Auto carriers, miscellaneous, reefer, and RORO ships are treated as single\n#' skeg ROROs in Kristensen formulas on the basis of sample of vessels from\n#' Lloyds and their number of propellers.\n#'\n#' Single screw RORO wetted surface area:\n#'\n#' 0.87(disp./lloyds draft +2.7*lwl*lloyds draft)*(1.2-0.34*Cbw)-3.0(lloyds draft-actual draft)*(lwl+breadth)\n#'\n#' Note: Actual draft is typically obtained from sources such as AIS messages or ship records.\n#'\n#' @return \\code{wettedSA} (vector of numericals, m^2)\n#'\n#' @references\n#'Kristensen, H. O. and Lutzen, M. 2013. \"Prediction of Resistance and Propulsion\n#'Power of Ships.\"\n#'\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCbw}}\n#'\\item \\code{\\link{calcShipType}}\n#'}\n#'\n#' @family Kristensen Calculations\n#'\n#' @examples\n#' calcKristWettedSA(\"bulk.carrier\", 80097, 13.6, 12.5, 218, 32.25, 0.8099003, 1.025)\n#' calcKristWettedSA(\"other.tanker\", 238942, 15.6, 14, 400, 49, 0.7490287, 1.025,\n#' tankerBulkCarrierGCargoShipTypes=c(\"other.tanker\",\"bulk.carrier\"))\n#' calcKristWettedSA(\"container.ship\", 238942, 15.6, 14, 400, 49, 0.7490287, 1.025)\n#'\n#' @export\n\ncalcKristWettedSA <- function(shipType, maxDisplacement, maxDraft, actualDraft, lwl, breadth, Cbw, seawaterDensity=1.025,\n tankerBulkCarrierGCargoShipTypes=c(\"general.cargo\",\"tanker\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\"),\n containerShipTypes=c(\"container.ship\"),\n paxTugShipTypes=c(\"ferry.pax\",\"ferry.ro.pax\",\"cruise\",\"cruise.ed\",\"yacht\",\"tug\",\"passenger\",\"ro.ro\")\n ){\n\n\n wettedSA<- ifelse(#case 1\n shipType %in% containerShipTypes,\n 0.995*( maxDisplacement/(seawaterDensity*maxDraft) + 1.9*lwl*maxDraft)\n - 2.4*(maxDraft-actualDraft)*(lwl+breadth)\n ,\n ifelse(#case2\n shipType %in% tankerBulkCarrierGCargoShipTypes,\n 0.99*( maxDisplacement/(seawaterDensity*maxDraft) + 1.9 *lwl*maxDraft)\n - 2*(maxDraft-actualDraft)*(lwl+breadth)\n ,\n ifelse(#case3\n shipType %in% paxTugShipTypes,\n 1.21*( maxDisplacement/(seawaterDensity*maxDraft) + 1.3*lwl*maxDraft)*(1.2-0.34*Cbw)\n - 2.5*(maxDraft-actualDraft)*(lwl+breadth)\n ,\n #miscelaneous case: reefer, roro, etc...\n 0.87*( maxDisplacement/(seawaterDensity*maxDraft) + 2.7*lwl*maxDraft)*(1.2-0.34*Cbw)\n - 3.0*(maxDraft-actualDraft)*(lwl+breadth)\n )#end case 3\n )#end case 2\n )#end case 1\n\n return(wettedSA)\n}\n", "meta": {"hexsha": "458b9e1ad4f667434d5e88c199ed339baf99f85b", "size": 5537, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristWettedSA.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcKristWettedSA.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcKristWettedSA.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 47.3247863248, "max_line_length": 175, "alphanum_fraction": 0.6461983023, "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47089026917391974}} {"text": "\nrinvgamma <- function(a, b){\n 1 / stats::rgamma(1, shape = a, rate = b)\n}\n\n\ndinvgamma <- function (x, shape, scale = 1) {\n log.density <- shape * log(scale) - lgamma(shape) - \n (shape + 1) * log(x) - (scale / x)\n return(exp(log.density))\n}\n\n\nupdate_sigma <- function(a_s, k_s, a_sigma, b_sigma){\n \n a_s_sites <- a_s[!duplicated(k_s$Site)]\n n <- length(a_s_sites)\n \n rinvgamma(a_sigma + (n / 2), b_sigma + sum(a_s_sites^2)/2)\n \n}\n\nupdate_l_sigma_integrated <- function(l_T, sigma_T, a_l_T, b_l_T, a_ig, b_ig, Y, sigma_psi,\n z, XbetaY, Xbetas, Xbeta_cov, eps_s, Omega, \n b_psi_b, sd_l, sd_sigma_T, X_y_index, usingSpatial){\n \n l_T_star <- stats::rnorm(1, l_T, sd_l)\n sigma_T_star <- stats::rnorm(1, sigma_T, sd_sigma_T)\n \n if(l_T_star < 4 & l_T_star > 0 & sigma_T_star > 0){\n \n K_l <- K(1:Y, 1:Y, sigma_T^2, l_T) + sigma_psi^2 + diag(exp(-10), nrow = Y)\n K_l_star <- K(1:Y, 1:Y, sigma_T_star^2, l_T_star) + sigma_psi^2 + diag(exp(-10), nrow = Y)\n \n # term 1\n \n tXOmegX <- matrixProductXtOmegaX_year(Y, Omega, X_y_index)\n \n logterm1_1 <- -.5 * log(FastGP::rcppeigen_get_det(K_l_star %*% tXOmegX + diag(1, nrow = Y)))\n logterm1_2 <- -.5 * log(FastGP::rcppeigen_get_det(K_l %*% tXOmegX + diag(1, nrow = Y)))\n \n logdeterminantsRatio <- logterm1_1 - logterm1_2\n \n # term 2\n \n logmuKlmu <- - .5 * b_psi_b %*% (FastGP::rcppeigen_invert_matrix(K_l_star) - \n FastGP::rcppeigen_invert_matrix(K_l)) %*% b_psi_b\n \n # term 3\n \n if(usingSpatial){\n c_i <- Xbetas + Xbeta_cov + eps_s \n } else {\n c_i <- Xbeta_cov + eps_s\n }\n \n \n k_i <- z - .5\n z_tilde <- k_i - c_i * as.vector(Omega)\n \n Xtz_tilde <- XpsiYz(X_y_index, z_tilde, Y)\n \n mu_tilde <- Xtz_tilde + FastGP::rcppeigen_invert_matrix(K_l) %*% b_psi_b\n mu_tilde_star <- Xtz_tilde + FastGP::rcppeigen_invert_matrix(K_l_star) %*% b_psi_b\n \n XtOXpB <- tXOmegX + FastGP::rcppeigen_invert_matrix(K_l)\n XtOXpB_star <- tXOmegX + FastGP::rcppeigen_invert_matrix(K_l_star)\n \n log_term2ratio_star <- .5 * ( t(mu_tilde_star) %*% FastGP::rcppeigen_invert_matrix(XtOXpB_star) %*% mu_tilde_star )\n log_term2ratio <- .5 * ( t(mu_tilde) %*% FastGP::rcppeigen_invert_matrix(XtOXpB) %*% mu_tilde )\n \n logterm3 <- log_term2ratio_star - log_term2ratio\n \n likelihood <- exp(logdeterminantsRatio + logmuKlmu + logterm3)\n \n prior_l <- exp(stats::dgamma(l_T_star, a_l_T, b_l_T, log = T) - stats::dgamma(l_T, a_l_T, b_l_T, log = T))\n prior_sigma <- exp(dinvgamma(sigma_T_star, a_ig, b_ig) - dinvgamma(sigma_T, a_ig, b_ig))\n \n posterior <- likelihood * prior_l * prior_sigma\n \n if(!is.na(posterior)){\n if(stats::runif(1) < posterior){\n l_T <- l_T_star\n sigma_T <- sigma_T_star\n } \n }\n \n }\n \n list(\"l_T\" = l_T, \"sigma_T\" = sigma_T)\n}\n\nrcpp_log_dmvnorm_fast <- function (inv_S, diag_S, sigma_s, x) {\n n <- length(x)\n # return((-n/2) * log(2 * pi) - sum(log(diag_S)) - (1/2) * x %*% inv_S %*% x)\n return((-n/2) * log(2 * pi) - sum(log(diag_S) + log(sigma_s)) -\n (1/2) * (1 / sigma_s^2) * x %*% inv_S %*% x)\n}\n\nsample_l_grid <- function(l_s_grid, inv_K_s_grid, diag_K_s_grid,\n a_l_s, b_l_s, a_s, sigma_s){\n \n posterior_val <- rep(NA, length(l_s_grid))\n \n for (j in 1:length(l_s_grid)) {\n \n l_s <- l_s_grid[j]\n # K_s_grid_j <- K_s_grid[,,j] * sigma_s^2\n # inv_K_s_grid_j <- inv_K_s_grid[,,j] / sigma_s^2\n # diag_K_s_grid_j <- diag_K_s_grid[,j] * sigma_s\n \n # loglikelihood <- rcpp_log_dmvnorm_fast(inv_K_s_grid[,,j],\n # diag_K_s_grid[,j], sigma_s, a_s)\n \n loglikelihood <- ((-length(a_s)/2) * log(2 * pi) - sum(log(diag_K_s_grid[,j]) + log(sigma_s)) -\n (1/2) * (1 / sigma_s^2) * a_s %*% inv_K_s_grid[,,j] %*% a_s)\n \n # loglikelihood <- rcpp_log_dmvnorm_fast(1, inv_K_s_grid_j,\n # diag_K_s_grid_j, a_s)\n \n # Sigma_l <- K2(X_tilde, X_tilde, sigma_s^2, l_s) + diag(exp(-10), nrow = nrow(X_tilde))\n \n # (loglikelihood2 <- rcpp_log_dmvnorm( Sigma_l, rep(0, X_centers), a_s, F))\n \n logPrior <- dgamma(l_s, a_l_s, b_l_s, log = T)\n \n posterior_val[j] <- logPrior + loglikelihood\n \n }\n \n # posterior_val <- sample_l_grid_cpp(l_s_grid, sigma_s, inv_K_s_grid, diag_K_s_grid,\n # a_l_s, b_l_s, a_s)\n \n posterior_val <- posterior_val - max(posterior_val)\n \n index_l_grid <- sample(1:length(l_s_grid), size = 1, \n prob = exp(posterior_val) / sum(exp(posterior_val)))\n \n index_l_grid\n}\n\nupdate_hyperparameters <- function(l_T, a_l_T, b_l_T, sd_l_T, sd_sigma_T,\n sigma_T, a_sigma_T, b_sigma_T, Y,\n beta_psi, inv_B_psi, \n b_psi, sigma_psi,\n l_s_grid, K_s_grid, inv_K_s_grid, \n inv_chol_K_s_grid, diag_K_s_grid,\n a_l_s, b_l_s, \n sigma_s, a_sigma_s, b_sigma_s, X_tilde,\n a_sigma_eps, b_sigma_eps,\n usingSpatial, \n XbetaY, Xbetas, Xbeta_cov,\n eps_s, k_s, \n z, X_psi, Omega, X_y_index){\n \n \n # update l_T and sigma_T -------------------\n \n list_l_sigma <- update_l_sigma_integrated(l_T, sigma_T, a_l_T, b_l_T, a_sigma_T, b_sigma_T, Y, \n sigma_psi,\n z, betaY, Xbetas, Xbeta_cov, eps_s, Omega, \n b_psi[1:Y], sd_l = sd_l_T, \n sd_sigma_T, X_y_index, usingSpatial)\n l_T <- list_l_sigma$l_T\n sigma_T <- list_l_sigma$sigma_T\n \n # reupdate inv_B_psi ------------\n \n K_l <- K(1:Y, 1:Y, sigma_T^2, l_T) + sigma_psi^2 + diag(exp(-8), nrow = Y)\n \n inverse_Kl <- FastGP::rcppeigen_invert_matrix(K_l)\n inverse_Kl[lower.tri(K_l)] <- t(inverse_Kl)[lower.tri(K_l)]\n \n inv_B_psi[1:Y, 1:Y] <- inverse_Kl\n \n # update l_s -------------------\n \n if(usingSpatial){\n index_ls_grid <- sample_l_grid(l_s_grid, inv_K_s_grid, diag_K_s_grid,\n a_l_s, b_l_s, beta_psi[Y + 1:nrow(X_tilde)], sigma_s)\n l_s <- l_s_grid[index_ls_grid]\n } else {\n l_s <- 0\n index_ls_grid <- 0\n }\n \n # update sigma_s ---------------------\n \n if(usingSpatial){\n \n X_centers <- nrow(X_tilde)\n \n inv_chol_Kl <- inv_chol_K_s_grid[,,index_ls_grid]\n \n a_s <- beta_psi[Y + 1:X_centers]\n \n a_ig <- X_centers / 2\n Ltas <- inv_chol_Kl %*% a_s\n b_ig <- (t(Ltas) %*% Ltas) / 2\n \n sigma_s <- sqrt(rinvgamma(a_sigma_s + a_ig, b_sigma_s + b_ig))\n } \n \n # reupdate inv_B_psi ------------\n \n if(usingSpatial){\n X_centers <- nrow(X_tilde)\n \n inv_K_lsigma <- inv_K_s_grid[,,index_ls_grid] / sigma_s^2\n \n inv_B_psi[Y + 1:X_centers, Y + 1:X_centers] <- inv_K_lsigma \n }\n \n # update sigma_as ------------------------------\n \n sigma_eps <- sqrt(update_sigma(eps_s, k_s, a_sigma_eps, b_sigma_eps))\n \n list(\"l_T\" = l_T,\n \"sigma_T\" = sigma_T,\n \"inv_B_psi\" = inv_B_psi,\n \"l_s\" = l_s,\n \"index_ls_grid\" = index_ls_grid,\n \"sigma_s\" = sigma_s,\n \"sigma_eps\" = sigma_eps)\n}\n", "meta": {"hexsha": "4eff909abc2ab191e76333d0f1327e9b9b35b3d0", "size": 7553, "ext": "r", "lang": "R", "max_stars_repo_path": "R/update_hyperparameters.r", "max_stars_repo_name": "alexdiana1992/FastOccupancy", "max_stars_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/update_hyperparameters.r", "max_issues_repo_name": "alexdiana1992/FastOccupancy", "max_issues_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/update_hyperparameters.r", "max_forks_repo_name": "alexdiana1992/FastOccupancy", "max_forks_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4203539823, "max_line_length": 119, "alphanum_fraction": 0.5501125381, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4700139767375135}} {"text": "#http://esapubs.org/archive/ecol/E095/262/STARS.R\n\n# Modified from Sergei Rodionov's VBA and Andrew Gardner's Matlab codes to produce an R version of STARS. Go to http://www.climatelogic.com/overview for more information, or see the Rodionov (2004; 2006) references in the paper.\n\n# Red noise correction included, but some other functions from VBA code (version 3.2) still missing (e.g. tests in shifts in variance).\n\n# Checked RSI results using two independent time-series against Rodionov plug in.\n\n# Alistair Seddon, October 2013. \n# alistair.seddon@gmail.com\n\nstars<- function(y=c(rnorm(50), rnorm(50,2,1)), L=20, p=0.05, h=1, AR1red=\"none\", prewhitening = F) {\n \n \n if(AR1red==\"none\" && prewhitening== T) stop(\"Impossible to perform prewhitening if AR1 coefficient is not estimated\")\n \n m= round((L+1)/3)\t\t\t\t# formula to estimate subsample size for calculating alpha (Rodionov 2006 + http://www.climatelogic.com/documentation/red-noise-estimation) \t \n \n # library(\"MASS\") needed if you want to use Huber correction parameter built in to MASS \n \n \n \n \n \n # -------------------------------------------------------------------------\n # hWeightedAverage(xwin)\n \n # Calculates the mean estimate for a given range using Huber's weights.\n # -------------------------------------------------------------------------\n \n \n hWeightedAverage<-function(xwin, h){\n \n # simple estimate of the regime mean for the windowed clip\n dblEstAve <- mean(xwin);\n \n for(jjj in 1:2){\n sumWeights = 0\n sumAve = 0\n \n # Estimate normalised deviation\n xDev = (xwin-dblEstAve)/sqrt(sigL)\n \n # Estimate weights or normalised deviation\n xDev[xDev==0] = 1\n wDev = pmin(rep(1, length(xwin)), h/abs(xDev), na.rm=T)\n \n #sum weights and weighed values\n sumWeights = sum(wDev)\n sumAve = sum(xDev*wDev)\n \n sumAve = sumAve/sumWeights\n sumAve = sumAve*sqrt(sigL) + dblEstAve\n dblEstAve = sumAve\n }\n \n dblWeightedAve = dblEstAve\n # hestimate<- huber(xwin, h)\n # dblWeightedAve = hestimate$mu\n }\n \n \n \n #-------------------------------------------------------------------\n # estimateSigma\n # Estimate the long-term, L-pt variance (assume homoskedastic signals).\n #-------------------------------------------------------------------\n \n estimateSigma<-function(x, L){\n \n # Estimate the long-term length-L variance. If the signal >> length of the analysis window, sample to estimate the variance.\n \n nx<-length(x)\n if(nx/L>300) ix <- as.integer(runif(100)*(nx-2*L)+L) else ix<-seq(L,nx,1)\n s<-0\n for(i in 1:length(ix)){\n xwin <- x[(ix[i]-L+1):ix[i]]\n s <- s + var(xwin, na.rm=T)\n }\n sigL1 = s / length(ix)\n sigL1\n }\n \n \n # ------------------------------------------------------------------\n # getThreshold()\n #\n # Calculate the critical threshold of deviation that signals regime changes. This does not change over the signal.\n # ---------------------------------------------------------------\n getThreshold<-function(L, p, sigL){\n \n if(prewhitening == T){\n dof <- 2*L-2\t\t\t\t\t\t# number degrees freedom\n } else {\n dof <- EqN((2*L-2), alpha)\n }\n \n t <- abs(qt(p/2, dof)); # crit 2-sided t-value\n thresh1 = t*sqrt(2*sigL/L); # crit deviation\n thresh1\n }\n \n \n \n # -------------------------------------------------------------------\n \n # OLS estimate of AR1 coefficient from Orcutt and Winokur, 1969, Econometrica, 37:1,1-14\n \n # -------------------------------------------------------------------\n \n OLScalc<-function(x){\n Nobs = length(x)\n \n ave1 = mean(x[2:Nobs])\n ave2 = mean(x[1:(Nobs-1)])\n \n sumNom=0\n sumDenom=0\n for(i in 2:Nobs){\n sumNom = sumNom + (x[i] - ave1) * (x[i - 1] - ave2)\n sumDenom = sumDenom + (x[i - 1] - ave2) * (x[i - 1] - ave2)\n }\n if(sumDenom > 0) OLSAR1 = sumNom / sumDenom else OLSAR1 = 0\n OLSAR1\n }\n \n \n # -------------------------------------------------------------------\n # AR1 correlation estimate (alpha)\n \n # ------------------------------------------------------------------- \n \n AR1cor<-function (m, y){\n m= m #define this in big function above\n \n ny=length(y)\n iy=seq(1,ny-m+1,1)\n OLS=rep(NA, length(iy))\n \n # Calculate OLS for sequential samples of length m\n for(i in 1:length(iy)){\n \n xwin = y[(iy[i]):(iy[i]+m-1)]\n \n if(length(xwin[is.na(xwin)]) == 0) OLS[i] <- OLScalc(xwin)\n }\n \n est<-median(OLS, na.rm=T)\n \n # Calculate IP4\t\n IP4= est + 1/m\n for(j in 1:3) IP4=IP4 + abs(IP4)/m\n \n # Calculate MPK\n if (m>4) MPK=((m-1)*est+1)/(m-4) else MPK= est\n \n alphaEst<-c(est, MPK, IP4) \t\n \n } \t\n \n \n # -------------------------------------------------------------------\n # Function EqP: calculates t-test using equivalent sample size as in von Storch and Zwiers (1999, p.115)\n # ------------------------------------------------------------------- \n \n EqP= function(rng1, rng2){ \n \n # Set standard no-result for if command at end\n EqP = 0\n \n # Calculate means and variances\n ave1 = mean(rng1, na.rm =T)\n ave2 = mean(rng2, na.rm =T) \n \n var1 = sd(rng1, na.rm = T)\n var2 = sd(rng2, na.rm = T) \n \n # Calculate effective sample sizes \n Ns1 = length(na.omit(rng1))\n if(Ns1 < 2){\n EqP = -1\n } \n eN1 = EqN(Ns1, alpha)\n \n Ns2 = length(na.omit(rng2))\n if(Ns2 < 2){\n EqP = -1\n } \n eN2 = EqN(Ns2, alpha)\n \n if(EqP == -1){\n EqP\n } else{\n # Calculate t-statistics\n T_stat = sqrt(var1/eN1 + var2/ eN2)\n T_stat = abs(ave1 - ave2)/ T_stat\n \n EqP = (1-pt(T_stat, eN1 + eN2 -2))*2\n EqP\n }\n \n }\n \n # -------------------------------------------------------------------\n # EqN: Calculates equivalent sample size as in von Storch and Zwiers (1999, p.115)\n # -------------------------------------------------------------------\n \n EqN = function(Ns, alpha){\n \n sumEqN = rep(NA, Ns-1)\n for(i in 1: (Ns-1)){\n sumEqN[i] = (1-i/Ns)*alpha^i\n }\n \n \n EqN = Ns / (1 + sum(c(sumEqN)))\n \n # just in case\n if( EqN <=2) EqN = 2\n if(EqN > Ns) EqN =Ns\n EqN\n }\n \n \n \n # ------------------------------------------------------------------\n # cusumUp()\n \n # Compute the L-pt cusum for positive level changes. For a positive regime change to be accepted, we require the L-pt lookahead samples\tto produce a cusum sequence which does not go negative.\n \n # -------------------------------------------------------------------\n \n cusumUp<-function(k){\n # LL sets the look ahead length: L, or the number of points until the end of the signal. k is the sample point running through the iteration\n LL <- min(L, N-k+1)\n \n # dblXdev is the length-LL vector of normalized deviations of x outside of the range lvl +/- thresh\n dblXdev = ((x[k:(k+LL-1)]) - (lvl+thresh)) / sqrt(sigL)\n \n # these are Huber weight values, so large deviations are deemphasized\n dblXdev[dblXdev==0] = 1\n dblXweight = pmin(rep(1, length(dblXdev)), h/abs(dblXdev), na.rm=T)\n \n # % the cusum is the integral of the weighted deviations; we normalize\n # % here, too, by dividing by the sum of the weights\n \n cs<- cumsum(dblXweight*dblXdev)/sum(dblXweight)\n \n # cs<-cumsum(dblXdev) #simple non weighted version\n \n # we check for cusum values below zero, which would indicate a failed\n # regime change; otherwise, we have a positive shift\n if (length(which(cs < 0) > 0)) cs = 0 else cs = cs[LL]\n cs\n } \n \n # ------------------------------------------------------------------\n # cusumDown()\n \n # Compute the L-pt cusum for positive level changes. For a positive regime change to be accepted, we require the L-pt lookahead samples\tto produce a cusum sequence which does not go negative.\n \n # -------------------------------------------------------------------\n \n cusumDown<-function(k){\n # LL sets the look ahead length: L, or the number of points until the end of the signal. k is the sample point running through the iteration\n LL <- min(L, N-k+1)\n \n # dblXdev is the length-LL vector of normalized deviations of x outside of the range lvl +/- thresh\n dblXdev = ((x[k:(k+LL-1)]) - (lvl-thresh)) / sqrt(sigL)\n \n # these are Huber weight values, so large deviations are deemphasized\n dblXdev[dblXdev==0] = 1\n dblXweight = pmin(rep(1, length(dblXdev)), h/abs(dblXdev), na.rm=T)\n \n # % the cusum is the integral of the weighted deviations; we normalize\n # % here, too, by dividing by the sum of the weights\n \n cs<- cumsum(dblXweight*dblXdev)/sum(dblXweight)\n \n # cs<-cumsum(dblXdev) # simple non-weighted version\n \n # we check for cusum values above zero, which would indicate a failed\n # regime change; otherwise, we have a positive shift\n if (length(which(cs > 0) > 0)) cs = 0 else cs = cs[LL]\n cs\n \n } \n \n \n # -------------------------------------------------------------------------\n # rsi(k)\n \n # Compute the rsi for a given sample index, regime mean, and critical\n # threshold.\n # -------------------------------------------------------------------------\n rsi<-function(k){\n if(x[k] > (lvl + thresh)){\n r = cusumUp(k)\n } else if(x[k] < (lvl - thresh)){\n r = cusumDown(k)\n } else {\n r = 0\n }\n r\n } \n \n \n \n # -------------------------------------------------------------------------\n \n # Red noise filtering of timeseries.\n \n \n # -------------------------------------------------------------------------\n \n \n \n alpha<-AR1cor(m,y) # calculate alpha estimates\n \n if(AR1red==\"est\"){\n alpha = alpha[1]\n }else if(AR1red==\"MPK\"){\n alpha = alpha[2]\t\n }else if(AR1red==\"IP4\"){\n alpha = alpha[3]\n }else if(AR1red==\"none\"){\n alpha= 0\n }\n \n if(alpha<0) alpha <- 0 ; if(alpha>1) alpha <- 1\n \n # Filter time series if selected and select as x for main procedure, otherwise use timeseries\n \n if(prewhitening == T){ \t\n Zt=rep(NA, length(y))\n for(j in 2:length(y)) Zt[j]<-y[j]-(y[j-1]*alpha)\n \n \n if(alpha>0) x=Zt[-1] else x=y[-1]\n names(x) <- names(y)[-1]\n \n } else x=y[-1]\n \n x <- na.omit(x)\n \n # -------------------------------------------------------------------------\n \n # initialisation \n \n \n # -------------------------------------------------------------------------\n \n \n sigL = estimateSigma(x, L); \t\t\t# sample L-pt variance\n thresh = getThreshold(L, p, sigL); # critical threshold\n lvl = hWeightedAverage(x[1:L], h); # initial mean level\n R = rep(0, length(x)); # rsi values\n RpVal<-rep(0, length(x))\n cp = 1; # current change-point index\n N = length(x) # number of samples\n \n if(length(names(y))==0) {\n stop(\"Stopped: No ages supplied with timeseries\")\n \n \n } else ages = names(y) \n \n \n \n # Main routine.\n for (k in 2:N){\n R[k] = rsi(k)\n \n # too few samples to confirm last regime change?\n if (abs(R[k]) > 0 && k > (N-L+1)) break \n \n # test for regime shifts and update current regime mean (unless we are within L-pts of most recent change-point)\n if(R[k] == 0){\n if(k >= (cp + L)) lvl = hWeightedAverage(x[cp:k], h) # same regime, far enough \n \n } else{\n cp = k # regime change\n lvl = hWeightedAverage(x[k:(k+L-1)], h); # same regime, far enough from cp\n }\n }\n \n # Calculation of new regime sample means and associated pvalues of shifts)\n if(R[length(R)] != 0) R[length(R)]<- 0\n cps<-which(abs(R)>0)\n \n rID<-rep(1, length(x))\n rLabel<-seq(2, length(cps)+1,1)\n Rmean<-rep(0, length(cps)+1)\n \n for(j in 1:length(cps)) rID[cps[j]:N]<-rLabel[j]\n for(j in 1:length(Rmean)) Rmean[j]<- hWeightedAverage(x[rID==j], h)\n # for(j in 1:length(Rmean)) Rmean[j]<- mean(x[rID==j])\n xNames= names(x)\n \n rID1 = rID\n for(j in 1:length(Rmean)) rID[rID==j]<-Rmean[j]\n \n xNA=rep(NA, length(y))\n xNA[match(xNames, names(y))] <- x\n \n RNA=rep(NA, length(y))\n RNA[match(xNames, names(y))] <- c(R)\n \n rIDNA=rep(NA, length(y)) \n rIDNA[match(xNames, names(y))] <- c(rID)\n starsResult<-cbind(y,xNA, RNA , rIDNA) \n \n colnames(starsResult) = c(\"ts\", \"AR1.cor\", \"rsi\", \"mean\"); rownames(starsResult) = ages\n \n \n \n # Estimate pValues of shifts on either white-noise filtered series, or by using the AR1 correction parameter\n \n pVal = rep(0, length(cps))\n \n for(j in 1:length(cps)) {\n \n rs1 = x[rID1==j]\n rs2 = x[rID1==(j+1)]\n \n if(length(rs2)==1) {\n next\n } else {\n ifelse(prewhitening ==T, pVal[j] <- t.test(rs1, rs2)$p.value, pVal[j] <- EqP(rs1, rs2))\n }\n }\n \n if(length(which(pVal == -1)) >0) warning(\"pValue calculation of -1 due regime containing only one sample\")\t\t\n \n starsOUT=list(starsResult, alpha, pVal)\n names(starsOUT)=c(\"starsResult\", \"alpha\", \"pVal\") \n starsOUT\n \n}\n\n\n", "meta": {"hexsha": "8635d1a2aa15d4992768486ac6cf225665aacb43", "size": 13173, "ext": "r", "lang": "R", "max_stars_repo_path": "stars.r", "max_stars_repo_name": "ozjimbob/FireScar", "max_stars_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T05:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T05:47:55.000Z", "max_issues_repo_path": "stars.r", "max_issues_repo_name": "ozjimbob/FireScar", "max_issues_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stars.r", "max_forks_repo_name": "ozjimbob/FireScar", "max_forks_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8031674208, "max_line_length": 228, "alphanum_fraction": 0.5061109846, "num_tokens": 3761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.469937915274214}} {"text": "##################################################\n##### Manipulate raster and netCDF datasets ######\n##### J Chave 15 Dec 2013 ######\n##### M Rejou-Mechain & J Chave 25 Mar 2014 ######\n##### Written in R version 3.0.3 ######\n##################################################\n\n#=========================================================================\n## In Chave et al. E and CWD are environmental variables\n## CWD is long-term climatic water deficit (see Chave et al for a precise definition)\n## TS is temperature seasonality extracted from the Worldclim dataset\n## PS is the precipitation seasonality extracted from the Worldclim dataset\n## E is an environmental stress variable defined in Eq (6b) of Chave et al as:\n## E=(0,178*TS-0.938*CWD-6.61*PS)/1000\n##\n## The layers are provided at 2.5 arc-minute resolution, or ca. 5 km\n## This 24 cells per degree, or 0.041666666666667 degree per cell\n# For 'raster' beginners:\n# raster starts at top left corner; Latitude is from +90 to -60, longitude from -180 to +180 \n# thus, French Guiana is at (+5,-55), or 85 rows from top and (180-55)=125 cols from left.\n# grain size is 0.041666666666667 degree, hence there are 24 cells per degree, or about 1 cell every 5 km\n#=========================================================================\n\n## filename is either CWD or E\n## format 'nc' denotes a file in netCDF format (default; much faster in linux-based environments)\n## format 'bil' denotes a file in raster format\n## default interpolation method used here is 'bilinear', where the exact value at the coordinates\n## is interpolated along both the x and y axes. The other option is 'simple' (the cell value is retrieved)\n\nretrieve_raster=function(filename,coord,plot=F,format=\"nc\"){\n require(\"raster\")\n if(format=='nc') require(\"ncdf\")\n zipurl <- \"http://chave.ups-tlse.fr/pantropical_allometry\"\n if(format=='nc') zipurl = paste(zipurl,\"/\",filename,\".nc.zip\",sep=\"\")\n if(format=='bil') zipurl = paste(zipurl,\"/\",filename,\".bil.zip\",sep=\"\")\n # Read the raster file in netCDF format from \n # http://chave.ups-tlse.fr/pantropical_allometry.htm\n print(zipurl);\n DEMzip <- download.file(zipurl, destfile = \"zipdir\")\n unzip(\"zipdir\", exdir = \"unzipdir\")\n nam=paste(\"unzipdir/\",filename,\".nc\",sep=\"\")\n RAST <- raster(nam)\n # Check that the dataset has properly been imported and that \n # your coordinates are correct\n # This step takes time\n if(plot==T){\n plot(RAST)\n points(coord,pch=\"x\")\n }\n # Extract the raster value\n # coord=cbind(longitude,latitude)\n RASTval=extract(RAST,coord,method=\"bilinear\")\n return(RASTval)\n}\n", "meta": {"hexsha": "c60f8ee5535c07cd6e4f0733a3700c4546808f5a", "size": 2624, "ext": "r", "lang": "R", "max_stars_repo_path": "R/readlayers.r", "max_stars_repo_name": "gabonNRI/tree-data-functions", "max_stars_repo_head_hexsha": "514fcb3e31473d62102fd0a6409d1eff0974dfb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/readlayers.r", "max_issues_repo_name": "gabonNRI/tree-data-functions", "max_issues_repo_head_hexsha": "514fcb3e31473d62102fd0a6409d1eff0974dfb4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/readlayers.r", "max_forks_repo_name": "gabonNRI/tree-data-functions", "max_forks_repo_head_hexsha": "514fcb3e31473d62102fd0a6409d1eff0974dfb4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7090909091, "max_line_length": 106, "alphanum_fraction": 0.6303353659, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.46963680504515787}} {"text": "#' Global Distance Metric Learning\n#'\n#' Performs Global Distance Metric Learning (GDM) on the given data, learning a full matrix.\n#'\n#' Put GdmFull function details here.\n#'\n#' @param data \\code{n * d} data matrix. \\code{n} is the number of data points,\n#' \\code{d} is the dimension of the data.\n#' Each data point is a row in the matrix.\n#' @param simi \\code{n * 2} matrix describing the similar constrains.\n#' Each row of matrix is serial number of a similar pair in the original data.\n#'\t\t\t\tFor example, pair(1, 3) represents the first observation is similar the 3th observation in the original data.\n#' @param dism \\code{n * 2} matrix describing the dissimilar constrains as \\code{simi}.\n#'\t\t\t\tEach row of matrix is serial number of a dissimilar pair in the original data.\n#' @param maxiter numeric, the number of iteration.\n#'\n#' @return list of the GdmDiag results:\n#' \\item{newData}{GdmDiag transformed data}\n#' \\item{fullA}{suggested Mahalanobis matrix}\n#' \\item{dmlA}{matrix to transform data, square root of diagonalA }\n#' \\item{converged}{whether the iteration-projection optimization is converged or not}\n#'\n#' For every two original data points (x1, x2) in newData (y1, y2):\n#'\n#' \\eqn{(x2 - x1)' * A * (x2 - x1) = || (x2 - x1) * B ||^2 = || y2 - y1 ||^2}\n#'\n#' @keywords GDM global distance metirc learning transformation mahalanobis metric\n#'\n#' @note Be sure to check whether the dimension of original data and constrains' format are valid for the function.\n#'\n#' @author Tao Gao <\\url{http://www.gaotao.name}>\n#'\n#' @references\n#' Steven C.H. Hoi, W. Liu, M.R. Lyu and W.Y. Ma (2003).\n#' Distance metric learning, with application to clustering with side-information.\n# in \\emph{Proc. NIPS}.\n#'\n\n#' @examples\n#' set.seed(123)\n#' library(MASS)\n#' library(scatterplot3d)\n#'\n#' # generate simulated Gaussian data\n#' k = 100\n#' m <- matrix(c(1, 0.5, 1, 0.5, 2, -1, 1, -1, 3), nrow =3, byrow = T)\n#' x1 <- mvrnorm(k, mu = c(1, 1, 1), Sigma = m)\n#' x2 <- mvrnorm(k, mu = c(-1, 0, 0), Sigma = m)\n#' data <- rbind(x1, x2)\n#'\n#' # define similar constrains\n#' simi <- rbind(t(combn(1:k, 2)), t(combn((k+1):(2*k), 2)))\n#'\n#' temp <- as.data.frame(t(simi))\n#' tol <- as.data.frame(combn(1:(2*k), 2))\n#'\n#' # define disimilar constrains\n#' dism <- t(as.matrix(tol[!tol %in% simi]))\n#'\n#' # transform data using GdmFull\n#' result <- GdmFull(data, simi, dism)\n#' newData <- result$newData\n#' # plot original data\n#' color <- gl(2, k, labels = c(\"red\", \"blue\"))\n#' par(mfrow = c(2, 1), mar = rep(0, 4) + 0.1)\n#' scatterplot3d(data, color = color, cex.symbols = 0.6,\n#'\t\t\t xlim = range(data[, 1], newData[, 1]),\n#'\t\t\t ylim = range(data[, 2], newData[, 2]),\n#'\t\t\t zlim = range(data[, 3], newData[, 3]),\n#'\t\t\t main = \"Original Data\")\n#' # plot GdmFull transformed data\n#' scatterplot3d(newData, color = color, cex.symbols = 0.6,\n#'\t\t\t xlim = range(data[, 1], newData[, 1]),\n#'\t\t\t ylim = range(data[, 2], newData[, 2]),\n#'\t\t\t zlim = range(data[, 3], newData[, 3]),\n#'\t\t\t main = \"Transformed Data\")\n\nGdmFull <- function(data, simi, dism, maxiter = 100) {\n\t\tdata <- as.matrix(data)\n\t\tN <- dim(data)[1]\n\t\td <- dim(data)[2]\n\t\tnew.simi <- unique(t(apply(simi, 1, sort)))\n\t\tnew.dism <- unique(t(apply(dism, 1, sort)))\n\n\t\tA <- diag(1, d) * 0.1\n\t\tW <- mat.or.vec(d, d)\n\t\tdij <- mat.or.vec(1, d)\n\n\t\t# sphereMult = cov(data)^(-0.5);\n\t\t# spheredata = data %*% sphereMult\n\n\t\tdist1.simi <- data[new.simi[, 1], ] - data[new.simi[, 2], ]\n\t\tdist2.ij <- t(apply(dist1.simi, 1, function(x) outer(x, x)))\n\t\tW <- matrix(apply(dist2.ij, 2, sum), ncol = d, byrow = TRUE)\n\n\n\t\tw <- matrix(W, ncol = 1)\n\t\tt0 <- as.numeric(crossprod(w, matrix(A, ncol = 1))/100)\n\n\t\tIterProjection <- function(data, simi, dism, A, w, t0 , maxiter = 100) {\n\t\t\t\t\t\t\tdata <- as.matrix(data)\n\t\t\t\t\t\t\tN = dim(data)[1] # number of examples\n\t\t\t\t\t\t\td = dim(data)[2] # dimensionality of examples\n\t\t\t\t\t\t\t# S1 <- mat.or.vec(N, N)\n\t\t\t\t\t\t\t# D1 <- mat.or.vec(N, N)\n\t\t\t\t\t\t\t# simi <- rbind(simi, simi[, c(2, 1)])\n\t\t\t\t\t\t\t# dism <- rbind(dism, dism[, c(2, 1)])\n\t\t\t\t\t\t\t# S1[simi] <- 1\n\t\t\t\t\t\t\t# D1[dism] <- 1\n\t\t\t\t\t\t\tnew.simi <- unique(t(apply(simi, 1, sort)))\n\t\t\t\t\t\t\tnew.dism <- unique(t(apply(dism, 1, sort)))\n\n\t\t\t\t\t\t\t# error1=1e5\n\t\t\t\t\t\t\tthreshold2 <- 0.01 # error-bound of main A-update iteration\n\t\t\t\t\t\t\tepsilon <- 0.01 # error-bound of iterative projection on C1 and C2\n\t\t\t\t\t\t\tmaxcount <- 200\n\n\t\t\t\t\t\t\tw1 <- w/norm(w, \"F\") # make 'w' a unit vector\n\t\t\t\t\t\t\tt1 <- t0/norm(w, \"F\")\n\n\t\t\t\t\t\t\tcount <- 1\n\t\t\t\t\t\t\talpha <- 0.1 # initial step size along gradient\n\n\t\t\t\t\t\t\tGradProjection <- function(grad1, grad2, d) {\n\t\t\t\t\t\t\t\t\t\t\t\tg1 <- matrix(grad1, ncol = 1)\n\t\t\t\t\t\t\t\t\t\t\t\tg2 <- matrix(grad2, ncol = 1)\n\n\t\t\t\t\t\t\t\t\t\t\t\tg2 <- g2/norm(g2, \"F\")\n\t\t\t\t\t\t\t\t\t\t\t\tgtemp <- g1 - as.numeric(crossprod(g2, g1)) * g2\n\t\t\t\t\t\t\t\t\t\t\t\tgtemp <- gtemp/norm(gtemp, \"F\")\n\t\t\t\t\t\t\t\t\t\t\t\tgrad.proj <- matrix(gtemp, d, d)\n\t\t\t\t\t\t\t\t\t\t\t\treturn(grad.proj)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfS1 <- function(data, new.simi, A, N, d, fudge = 0.000001) {\n\n\t\t\t\t\t\t\t\t\tdist1.simi <- data[new.simi[, 1], ] - data[new.simi[, 2], ]\n\t\t\t\t\t\t\t\t\tdist2.ij <- t(apply(dist1.simi, 1, function(x) outer(x, x)))\n\t\t\t\t\t\t\t\t\tfs.1d <- matrix(apply(dist2.ij, 2, sum), ncol = d, byrow = TRUE)\n\t\t\t\t\t\t\t\t\treturn(fs.1d)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfD1 <- function(data, new.simi, A, N, d, fudge = 0.000001) {\n\t\t\t\t\t\t\t\t\tdist1.dism <- data[new.dism[, 1], ] - data[new.dism[, 2], ]\n\t\t\t\t\t\t\t\t\tdist.ij <- numeric(dim(dist1.dism)[1])\n\t\t\t\t\t\t\t\t\tfor (i in 1:dim(dist1.dism)[1]) {\n\t\t\t\t\t\t\t\t\t\tdist.ij[i] <- sqrt(t(dist1.dism[i, ]) %*% A %*% t(t(dist1.dism[i, ])))\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsum.dist <- sum(dist.ij) + 0.000001\n\t\t\t\t\t\t\t\t\tMij <- t(apply(dist1.dism, 1, function(x) outer(x, x)))\n\t\t\t\t\t\t\t\t\ttemp <- cbind(Mij, t(t(dist.ij)))\n\n\t\t\t\t\t\t\t\t\tderi.ij <- 0.5 * temp[, 1:(d^2)]/(temp[, d^2 + 1] + (temp[, d^2 + 1] == 0) * fudge)\n\t\t\t\t\t\t\t\t\tsum.deri <- matrix(apply(deri.ij, 2, sum), ncol = d, byrow = TRUE)\n\t\t\t\t\t\t\t\t\tfd.1d <- sum.deri/sum.dist\n\t\t\t\t\t\t\t\t\treturn(fd.1d)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfD <- function(data, new.dism, A, N, d) {\n\t\t\t\t\t\t\t\t\tdist1.dism <- data[new.dism[, 1], ] - data[new.dism[, 2], ]\n\t\t\t\t\t\t\t\t\tdist.ij <- numeric(dim(dist1.dism)[1])\n\t\t\t\t\t\t\t\t\tfor (i in 1:dim(dist1.dism)[1]) {\n\t\t\t\t\t\t\t\t\t\tdist.ij[i] <- sqrt(t(dist1.dism[i, ]) %*% A %*% t(t(dist1.dism[i, ])))\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfd <- sum(dist.ij) + 0.000001\n\t\t\t\t\t\t\t\t\tfd <- log(fd)\n\t\t\t\t\t\t\t\t\treturn(fd)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tgrad1 <- fS1(data, new.simi, A, N, d); # gradient of similarity constraint function\n\t\t\t\t\t\t\tgrad2 <- fD1(data, new.dism, A, N, d); # gradient of dissimilarity constraint func.\n\t\t\t\t\t\t\tM <- GradProjection(grad1, grad2, d); # gradient of fD1 orthognal to fS1\n\n\n\t\t\t\t\t\t\tA.last <- A # initial A\n\t\t\t\t\t\t\tdone <- 0\n\t\t\t\t\t\t\tdelta <- 0\n\t\t\t\t\t\t\tconverged <- 0\n\t\t\t\t\t\t\twhile (done == 0) {\n\t\t\t\t\t\t\t\t\tprojection.iters <- 0\n\t\t\t\t\t\t\t\t\tsatisfy <- 0\n\n\t\t\t\t\t\t\t\t\twhile (projection.iters < maxiter & satisfy == 0) {\n\t\t\t\t\t\t\t\t\t\tA0 <- A\n\t\t\t\t\t\t\t\t\t\tx0 <- matrix(A0, ncol = 1)\n\t\t\t\t\t\t\t\t\t\tif(crossprod(w, x0) <= t0)\n\t\t\t\t\t\t\t\t\t\t\tA <- A0\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tx <- x0 + as.numeric(t1 - crossprod(w1, x0)) * w1\n\t\t\t\t\t\t\t\t\t\t\tA <- matrix(x, 3, 3)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tA <- (A + t(A))/2\n\t\t\t\t\t\t\t\t\t\tvl <- eigen(A)\n\t\t\t\t\t\t\t\t\t\tvl[[1]][vl[[1]] < 0] = 0\n\t\t\t\t\t\t\t\t\t\tA <- vl[[2]] %*% diag(vl[[1]], d) %*% t(vl[[2]])\n\n\t\t\t\t\t\t\t\t\t\tfDC2 <- crossprod(w, matrix(A, ncol = 1))\n\t\t\t\t\t\t\t\t\t\terror1 <- as.numeric((fDC2 - t0)/t0)\n\t\t\t\t\t\t\t\t\t\tprojection.iters <- projection.iters + 1\n\t\t\t\t\t\t\t\t\t\tsatisfy <- as.numeric(ifelse(error1 > epsilon, 0, 1))\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tobj.previous <- fD(data, new.dism, A.last, N, d)\n\t\t\t\t\t\t\t\t\tobj <- fD(data, new.dism, A, N, d)\n\n\t\t\t\t\t\t\t\t\tif (obj > obj.previous & satisfy == 1) {\n\t\t\t\t\t\t\t\t\t\talpha <- alpha * 1.05\n\t\t\t\t\t\t\t\t\t\tA.last <- A\n\t\t\t\t\t\t\t\t\t\tgrad2 <- fS1(data, new.simi, A, N, d)\n\t\t\t\t\t\t\t\t\t\tgrad1 <- fD1(data, new.dism, A, N, d)\n\t\t\t\t\t\t\t\t\t\tM <- GradProjection(grad1, grad2, d)\n\t\t\t\t\t\t\t\t\t\tA <- A + alpha * M\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\t\talpha <- alpha/2\n\t\t\t\t\t\t\t\t\t\tA <- A.last + alpha * M\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdelta <- norm(alpha * M, \"F\")/norm(A.last, \"F\")\n\t\t\t\t\t\t\t\t\tcount <- count + 1\n\t\t\t\t\t\t\t\t\tdone <- ifelse(delta < threshold2 | count == maxcount, 1, 0)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconverged <- ifelse(delta > threshold2, 0, 1)\n\t\t\t\t\t\t\treturn(list(\"converged\" = ifelse(converged == 1, \"Yes\", \"No\"), \"fullA\" = A))\n\t\t}\n\n\t\titerproj <- IterProjection(data, simi, dism, A, w, t0)\n\t\teigenvalue <- eigen(iterproj$fullA)\n\t\tdml <- eigenvalue[[2]] %*% sqrt(diag(eigenvalue[[1]], d))\n\t\tnewData <- data %*% dml\n\t\treturn(list(\"newData\" = newData, \"fullA\" = iterproj[[2]], \"dmlA\" = dml, \"converged\" = iterproj[[1]]))\n}\n", "meta": {"hexsha": "abbdb9ad57084def2f6ddb9751eaa21d116f1164", "size": 8518, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gdmf.r", "max_stars_repo_name": "vishalbelsare/sdml", "max_stars_repo_head_hexsha": "5497f697a882136c83d397a476419fd4503a80bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-01T02:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T02:57:45.000Z", "max_issues_repo_path": "R/gdmf.r", "max_issues_repo_name": "nanxstats/sdml", "max_issues_repo_head_hexsha": "5497f697a882136c83d397a476419fd4503a80bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/gdmf.r", "max_forks_repo_name": "nanxstats/sdml", "max_forks_repo_head_hexsha": "5497f697a882136c83d397a476419fd4503a80bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5579399142, "max_line_length": 115, "alphanum_fraction": 0.5403850669, "num_tokens": 2923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.46959246243369834}} {"text": "# Synthetic Data Project\r\n# Common Functions\r\n\r\n# Author:\r\n# Version: 5/14/2017\r\n\r\n# Copyright 2017\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\r\n# associated documentation files (the \"Software\"), to deal in the Software without restriction, including\r\n# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the\r\n# following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all copies or substantial\r\n# portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\r\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\nfrequencyMode <- function(x, nbins=25, nTopMean=1) {\r\n\r\n # compute mode of vector x as weighted mean of top nTopMean frequencies using nbins cut intervals\r\n # tabulate frequencies\r\n # take weighted mean of all bin midpoints in top nTopMean frequencies\r\n xtab <- table(cut(x, nbins))\r\n # identify top nTopMean frequencies\r\n k <- which(xtab %in% sort(unique(xtab), decreasing=T)[1:nTopMean])\r\n sum(mapply(k, FUN=function(i) {\r\n # multiply interval centerpoints by frequencies\r\n # format is \"(b0,b1]\" from cut()\r\n interval <- names(xtab)[i]\r\n # locate comma\r\n cpos <- regexpr(\",\", interval)[1]\r\n # exclude leading ( and trailing ]\r\n b0 <- as.numeric(substr(interval, 2, cpos-1))\r\n b1 <- as.numeric(substr(interval, cpos+1, nchar(interval)-1))\r\n # multiply frequency by midpoint of lower and upper bounds\r\n as.numeric(xtab[i])*(b0+b1)/2\r\n })) / sum(xtab[k])\r\n\r\n}\r\n", "meta": {"hexsha": "fcc5ffa7b338a557cd2aa968800e1cec459d78d3", "size": 2263, "ext": "r", "lang": "R", "max_stars_repo_path": "VerificationServer/CommonFunctions.r", "max_stars_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_stars_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VerificationServer/CommonFunctions.r", "max_issues_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_issues_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VerificationServer/CommonFunctions.r", "max_forks_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_forks_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1956521739, "max_line_length": 107, "alphanum_fraction": 0.6575342466, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.46894613456619544}} {"text": "# ########################################\n# ########## FUNCTIONS SECTION ############\n\n###### CREATE BASIC ADJACENCY MATRIX #####\n# no edge weights, useful for DCI with no distance decay\n# rbgl requires adjacency matrix \n# FIPEX outputs adjacency table so need to convert\n# note: igraph requires only adjacency table\n\n# library(rbenchmark) can be used to test\n#https://stackoverflow.com/questions/34355892/build-a-square-adjacency-matrix-from-data-frame-or-data-tablelevs <- unique(unlist(neighbournodes_all, use.names=F))\n\ncreate_basic_adjmatrix_2020 <- function(neighbournodes_all,option=\"2020_tapply\") {\n # binary adjacency matrix defining connectivity\n \n if(option==\"2020_tapply\"){\n neighbournodes_all$edgeLength <- 1\n adj_matrix <- with(neighbournodes_all, tapply(edgeLength, list(Node1, Node2),FUN=length, default = 0))\n \n }else if(option==\"2020_dfmatrix\"){\n matrix_table <- table(neighbournodes_all)\n adj_mat1 <- as.data.frame.matrix(matrix_table)\n adj_matrix <- as.matrix(adj_mat1)\n \n }else if(option==\"oldway\"){\n \n # pre-2020 code\n segments<-with(neighbournodes_all, unique(Node2))\n #create a matrix with only 0's in them\n adj_matrix<-matrix(nrow=length(segments), \n ncol=length(segments), \n rep(0,length(segments)*length(segments)))\n segment_length<-length(segments)\n rownames(adj_matrix)<-colnames(adj_matrix)<-segments\n\n for (i in 1:segment_length){\n # find the segments in segment.matrix$Seg where segment.matrix$Seg_ID matches segments[i]\n # index of matching positions - this will be a vector of 1's and NA's\n pos_match<-\tmatch(neighbournodes_all$Node2,segments[i])\n \n # keep only the positions where pos.match==1\n adj_segments<-neighbournodes_all$Node1[!is.na(pos_match)]\n\n # find the column positions that correspond to the adjacaent segments\n col<-match(adj_segments,segments)\n\n # the row number should correspond to i\n row<-i\n\n # assign a value of 1 for all values of row and col\n adj_matrix[row,col]<-1\n }\n } \n adj_matrix\n}\n\n\n################################################################\n# edge-weighted connectivity list (edges_all) and matrix - for DCI w/ DD\n# nodes / edges are not reversed as in original way\n# do not need self-connected\n\ncreate_advanced_adjmatrix_2020 <- function(FIPEX_table=NULL){\n\n # get connectivity list, convert columns to characters\n FIPEX_table_DD <- FIPEX_table %>% select(NodeEID,DownstreamEID,DownstreamNeighDistance) %>%\n mutate(temp = as.character(NodeEID)) %>%\n mutate(NodeEID = temp) %>%\n mutate(temp = as.character(DownstreamEID)) %>%\n mutate(DownstreamEID = temp) %>%\n select(-temp) %>%\n mutate(DownstreamEID = ifelse(DownstreamEID == \"Sink\",\"sink\",DownstreamEID))\n\n # downstream neighbours\n edges_down <- FIPEX_table_DD\n\n # upstream neigbours\n edges_up <- FIPEX_table_DD %>% select(NodeEID,DownstreamEID,DownstreamNeighDistance) %>%\n mutate(temp = DownstreamEID) %>%\n mutate(DownstreamEID = NodeEID) %>%\n mutate(NodeEID = temp) %>%\n select(-temp)\n\n # self-connected\n #FIPEX_table %>% select(NodeEID,DownstreamEID,DownstreamNeighDistance) %>%\n #mutate(NodeEID = DownstreamEID, DownstreamNeighDistance = 0.1)\n\n # merge\n edges_all <- edges_down %>%\n bind_rows(edges_up) %>%\n #add_row(NodeEID = \"sink\", DownstreamEID = \"sink\") %>%\n rename(Node1 = NodeEID, Node2 = DownstreamEID, edgeLength = DownstreamNeighDistance)\n \n # convert to matrix\n adj_matrix_edgelengths <- with(edges_all, tapply(edgeLength, list(Node1, Node2), FUN=sum, default = 0))\n \n return(adj_matrix_edgelengths)\n}\n\n################################################################\n# CREATE GRAPH OBJECT for DCI w/ Distance Decay\n# edge weights are used for distance calculations\n# edge data / attributes used for habitat quantity calculations\n# #https://www.rdocumentation.org/packages/graph/versions/1.50.0/topics/graphAM-class\ncreate_graph_dd_2020 <- function(adj_matrix_edgelengths=0.0,FIPEX_table=NULL){\n\n # Create graph object\n # 2020 - different way to call the graphAM function \n # vs pre-2020\n g_dd <- graphAM(adjMat=adj_matrix_edgelengths, edgemode=\"directed\", values=list(weight=1))\n\n # associate passabilities with nodes using NodeData slot\n # e.g. nodeData(g,n=c(\"b\", \"c\"), attr =\"color\") <- \"red\"\n nodeDataDefaults(g_dd, attr =\"pass\") <- 1.0\n nodeData(g_dd,n=as.character(FIPEX_table$NodeEID), attr=\"pass\") <- as.double(FIPEX_table$BarrierPerm)\n #nd <- nodes(g_dd)\n\n nodeDataDefaults(g_dd, attr =\"nodelabel\") <- \"none\"\n nodeData(g_dd,n=as.character(FIPEX_table$NodeEID), attr=\"nodelabel\") <- as.character(FIPEX_table$NodeLabel)\n nodeData(g_dd,n=\"sink\", attr=\"nodelabel\") <- \"sink\"\n #nd <- nodes(g_dd)\n\n nodeDataDefaults(g_dd, attr =\"downnodelabel\") <- \"none\"\n nodeData(g_dd,n=as.character(FIPEX_table$NodeEID), attr=\"downnodelabel\") <- as.character(FIPEX_table$DownstreamNodeLabel)\n #nd <- nodes(g_dd)\n\n nodeDataDefaults(g_dd, attr =\"natural\") <- \"none\"\n nodeData(g_dd,n=as.character(FIPEX_table$NodeEID), attr=\"natural\") <- FIPEX_table$NaturalTF\n nodeData(g_dd,n=\"sink\", attr=\"natural\") <- FALSE\n #nd <- nodes(g_dd)\n\n # optionally can give edges attributes\n #edgeDataDefaults(g_dd, attr=\"name\")<-\"noname\"\n #edgeData(self, from, to, attr)\n #edgeData(self, from, to, attr) <- value\n edgeDataDefaults(g_dd, attr=\"HabitatQuan\")<-0.0\n edgeData(g_dd,from=as.character(FIPEX_table$NodeEID), \n to=as.character(FIPEX_table$DownstreamEID), \n attr=\"HabitatQuan\")<-as.double(FIPEX_table$HabQuantity)\n # reverse - attr associated with each direction along one edge\n edgeData(g_dd,from=as.character(FIPEX_table$DownstreamEID), \n to=as.character(FIPEX_table$NodeEID), \n attr=\"HabitatQuan\")<-as.double(FIPEX_table$HabQuantity)\n\n\n # give edges an easy-to-access name insensitive to direction\n # this is done to quickly identify duplicates later\n # there may be alternatives such as accessing edgeNames but I suspect\n # they are slower than this\n edgeDataDefaults(g_dd, attr=\"EdgeNameGO\")<-\"init\"\n edgeData(g_dd,from=as.character(FIPEX_table$NodeEID), \n to=as.character(FIPEX_table$DownstreamEID), \n attr=\"EdgeNameGO\")<-paste(as.character(FIPEX_table$DownstreamEID),\n as.character(FIPEX_table$NodeEID),\n sep=\"-\")\n # reverse - attr associated with each direction along one edge\n edgeData(g_dd,from=as.character(FIPEX_table$DownstreamEID), \n to=as.character(FIPEX_table$NodeEID), \n attr=\"EdgeNameGO\")<-paste(as.character(FIPEX_table$DownstreamEID),\n as.character(FIPEX_table$NodeEID),\n sep=\"-\")\n return(g_dd)\n}\n\n################################################################################\n# get all distances and paths (from penult) to all nodes from Sink / all nodes\n# https://www.rdocumentation.org/packages/RBGL/versions/1.48.1/topics/dijkstra.sp\n# note it must be node-node - no edge-edge possible\n# note using this function repeatedly during DCIp is inefficient \n# !!! (should use BFS w/ LCA i.e., custom algorithm) !!!\n# (cannot edit the source for Djikstra.sp because it's actually an \n# interface to C++ 'Boost'library for graphs - can't get edge and node attributes \n# during net traversal)\n\nget_paths_distances <- function(g=NULL,fromnode=\"sink\"){\n dijkstra.sp(g,fromnode,eW=unlist(edgeWeights(g)))\n \n # TO DO: ALTERNATIVES FOR BENCHMARKING\n}\n\n##############################################################################\n##### SUMMARY TABLE 2020 #####\n\n# replaces similar pre-2020 function to create a table for each edge-edge pair\n# Includes options for alternative data management for benchmarking\n# (code could be trimmed).\n# this function could be sped up with custom algorithm that can find path \n# while also grabbing attribute data (BFS w/ LCA). \n# - G Oldford, 2020\n\n# gets cumulative passability each pair using path info\n# and get other attributes\n\n# pseudocode:\n# for each 'from node' (e.g., sink in DCId, and all nodes in DCIp)\n# get paths between node and all other node\n#\n# for each 'to node' in 'all paths' results\n# get the first edge len and hab traversed from node to sink\n#\n# store length and hab of the edge between 'to node' and first node encountered\n# in path back to 'from node' (i.e., the 'to edge')\n\n# do while next node name <> \"from node\"\n# pass = nodeData(g_dd, nextnode, \"pass\")\n# cumulativepass = cumulativepass * pass\n# nextnode = the next node in path towards 'from node'\n# if last edge traversed on the way to 'from node'\n# store the length and habitat of this edge which is the 'from edge'\n# if there is a maxdistance set for distance decay, \n# add a TRUE/FALSE column to indicate this\n# \n# \n# add various other attributes to master table (attr's from g object)\n\n# requires library(data.table)\n# data.table vs other options likely to speed things up for large networks\n#https://rstudio-pubs-static.s3.amazonaws.com/406521_7fc7b6c1dc374e9b8860e15a699d8bb0.html\n#https://www.rdocumentation.org/packages/data.table/versions/1.13.0/topics/rbindlist\n\nget_summary_tab_2020 <- function(option=\"dt-lists\",\n naturalonly=FALSE,\n g = NULL,\n DCIp=FALSE,\n bDistanceLim=FALSE,\n dMaxDist=0.0){\n \n # funciton params:\n # option - for benchmarking speed of appending to table\n # naturalonly - will calculate pass-weighted path distances\n # while ignoring non-natural barriers\n # g - the graph object (rbgl GraphAM in BioconductR)\n # DCIp - TRUE / FALSE will trigger loop that finds path\n # between all nodes, node just sink\n # initialize empty data object in different ways\n \n # for different options and benchmarking:\n DT2 = data.table(FromNode=\"init\",\n ToNode=\"init\",\n FromNodeLabel=\"init\",\n ToNodeLabel=\"init\",\n CumulativePass=0.0,\n FromEdgeLen=0.0,\n ToEdgeLen=0.0,\n TotalDist=0.0,\n DistMinusStartEndLen=0.0,\n DistMinusSEExceedsThreshold=FALSE,\n FromEdgeHab=0.0,\n ToEdgeHab=0.0,\n ToEdgeName=\"init\",\n FromEdgeName=\"init\",\n ToFromEdgeNameCombo=\"init\")\n \n DF2 = data.frame(FromNode=\"init\",\n ToNode=\"init\",\n FromNodeLabel=\"init\",\n ToNodeLabel=\"init\",\n CumulativePass=0.0,\n FromEdgeLen=0.0,\n ToEdgeLen=0.0,\n TotalDist=0.0,\n DistMinusStartEndLen=0.0,\n DistMinusSEExceedsThreshold=FALSE,\n FromEdgeHab=0.0,\n ToEdgeHab=0.0,\n ToEdgeName=\"init\",\n FromEdgeName=\"init\",\n ToFromEdgeNameCombo=\"init\", stringsAsFactors=F)\n \n # lists in R must have size pre-allocated \n # size of our table is almost n^2 - n*(n-1) \n # (less than n^2 since not getting distance from node to itself)\n if(DCIp==FALSE){\n outlist <- vector(\"list\", length(numNodes(g_dd)))\n }else{\n outlist <- vector(\"list\", length(numNodes(g_dd)*(numNodes(g_dd)-1))) \n }\n \n outlist[[numNodes(g_dd)]] <- list(FromNode=\"init\",\n ToNode=\"init\",\n FromNodeLabel=\"init\",\n ToNodeLabel=\"init\",\n CumulativePass=0.0,\n FromEdgeLen=0.0,\n ToEdgeLen=0.0,\n TotalDist=0.0,\n DistMinusStartEndLen=0.0,\n DistMinusSEExceedsThreshold=FALSE,\n FromEdgeHab=0.0,\n ToEdgeHab=0.0,\n FromEdgeName=\"init\",\n ToEdgeName=\"init\",\n ToFromEdgeNameCombo=\"init\")\n\n # from = sink / start node\n # to = other nodes\n if(DCIp==FALSE){\n fromnodecount=1\n }else{\n fromnodecount=numNodes(g_dd)\n }\n \n bDistMinusSEExceedsThreshold = FALSE\n count = 0\n for (j in 1:fromnodecount){\n #indendation for two nested for loops not done to save space\n if(DCIp==FALSE){\n fromnode_name = \"sink\"\n fromnode_label = \"sink\" \n }else{\n fromnode_name = nodes(g_dd)[j]\n if (fromnode_name==\"sink\"){\n fromnode_label = \"sink\"\n }else{\n fromnode_label = nodeData(g_dd, fromnode_name, \"nodelabel\")[[1]] \n }\n }\n \n ###########################################################\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # get path & distances between 'fromnode' and all other nodes\n paths_distances <- get_paths_distances(g,fromnode_name)\n # this can be time consuming\n \n for (k in 1:length(paths_distances$penult)) {\n \n tonode <- paths_distances$penult[k] \n tonode_name = names(tonode)\n tonode_name <- tonode_name[[1]]\n tonode_label = nodeData(g_dd, tonode_name, \"nodelabel\")[[1]]\n \n if (tonode_name == fromnode_name){\n # not interested in distance from one node to itself\n next\n }\n count = count+1\n # initialize\n cumulativepass = 1.0\n pass = 1.0 # watch not to take pass from to/from end nodes since traversal starts at edge\n totaldistance = paths_distances$distances[tonode_name]\n totaldistance <- totaldistance[[1]] \n \n # get length of edge \n nextnode = paths_distances$penult[tonode]\n nextnode_name = names(nextnode)\n lastnode_name = tonode_name\n \n # get the last edge length traversed on the way to 'to node'\n # alternatively could grab the weight for this edge instead of subtraction\n toedgelen = totaldistance - paths_distances$distances[nextnode_name]\n toedgelen <- toedgelen[[1]]\n toedgedata =edgeData(g_dd, tonode_name,nextnode_name)\n toedgehab = toedgedata[[1]]$HabitatQuan\n toedgename = toedgedata[[1]]$EdgeNameGO\n \n exitvar = \"go\"\n while (exitvar != \"stop\"){\n \n if(nextnode_name != fromnode_name){\n pass = nodeData(g_dd, nextnode_name, \"pass\")\n if(naturalonly==FALSE){\n cumulativepass = cumulativepass * pass[[1]]\n }else{\n natural = nodeData(g_dd,nextnode_name,\"natural\")\n if(natural[[1]]==TRUE){\n cumulativepass = cumulativepass * pass[[1]]\n }\n }\n }else{\n fromedgelen = paths_distances$distances[lastnode_name]\n fromedgelen <- fromedgelen[[1]]\n fromedgedata = edgeData(g_dd, lastnode_name,fromnode_name)\n fromedgehab = fromedgedata[[1]]$HabitatQuan\n fromedgename = fromedgedata[[1]]$EdgeNameGO\n \n exitvar=\"stop\"\n }\n \n lastnode_name = nextnode_name\n nextnode = paths_distances$penult[nextnode]\n nextnode_name = names(nextnode)\n }\n \n distminusstartendlen = totaldistance - toedgelen - fromedgelen\n # less than zero distance indicates it's an edge-to-itself distance\n # correct for this\n if (distminusstartendlen<0){\n distminusstartendlen = 0 \n }\n \n tofromedgename_combo = paste(toedgename,fromedgename,sep=\"|\")\n \n if (bDistanceLim == TRUE){\n if (distminusstartendlen > dMaxDist){\n bDistMinusSEExceedsThreshold=TRUE\n }else{\n bDistMinusSEExceedsThreshold=FALSE\n }\n }else{\n bDistMinusSEExceedsThreshold=FALSE\n }\n \n if (option==\"dt\"){\n #print(cumulativepass)\n #https://www.rdocumentation.org/packages/data.table/versions/1.13.0/topics/rbindlist\n DT1 = data.table(FromNode=fromnode_name,\n ToNode=tonode_name,\n FromNodeLabel=fromnode_label,\n ToNodeLabel=tonode_label,\n CumulativePass=cumulativepass, \n FromEdgeLen=fromedgelen,\n ToEdgeLen=toedgelen,\n TotalDist=totaldistance,\n DistMinusStartEndLen=distminusstartendlen,\n DistMinusSEExceedsThreshold = as.logical(bDistMinusSEExceedsThreshold),\n FromEdgeHabLen=fromedgehablen,\n ToEdgeHab=toedgehab,\n FromEdgeHab=fromedgehab,\n FromEdgeName=fromedgename,\n ToEdgeName=toedgename,\n ToFromEdgeNameCombo=tofromedgename_combo)\n l = list(DT1,DT2)\n \n DT2 = rbindlist(l, use.names=TRUE)\n }else if(option==\"dt-lists\"){\n # append lists to list rather than work yet with tables\n DL1 = list(FromNode=fromnode_name,\n ToNode=tonode_name,\n FromNodeLabel=fromnode_label,\n ToNodeLabel=tonode_label,\n CumulativePass=cumulativepass, \n FromEdgeLen=fromedgelen,\n ToEdgeLen=toedgelen,\n TotalDist=totaldistance,\n DistMinusStartEndLen=distminusstartendlen,\n DistMinusSEExceedsThreshold = as.logical(bDistMinusSEExceedsThreshold),\n FromEdgeHab=fromedgehab,\n ToEdgeHab=toedgehab,\n FromEdgeName=fromedgename,\n ToEdgeName=toedgename,\n ToFromEdgeNameCombo=tofromedgename_combo)\n #print(\"Length DL1: \")\n #print(length(DL1))\n outlist[[count]] <- (DL1)\n \n }else if(option==\"df\"){\n DF1 = data.frame(FromNode=fromnode_name,\n ToNode=tonode_name,\n FromNodeLabel=fromnode_label,\n ToNodeLabel=tonode_label,\n CumulativePass=cumulativepass, \n FromEdgeLen=fromedgelen,\n ToEdgeLen=toedgelen,\n TotalDist=totaldistance,\n DistMinusStartEndLen=distminusstartendlen,\n DistMinusSEExceedsThreshold = as.logical(bDistMinusSEExceedsThreshold),\n FromEdgeHab=fromedgehab,\n ToEdgeHab=toedgehab,\n FromEdgeName=fromedgename,\n ToEdgeName=toedgename,\n ToFromEdgeNameCombo=tofromedgename_combo)\n #print(fromedgehabarea)\n #print(DF1)\n DF2 <- rbind(DF2, DF1)\n }else if(option==\"df-lists\"){\n DL1 = list(FromNode=as.character(fromnode_name),\n ToNode=as.character(tonode_name),\n FromNodeLabel=as.character(fromnode_label),\n ToNodeLabel=as.character(tonode_label),\n CumulativePass=as.numeric(cumulativepass), \n FromEdgeLen=as.numeric(fromedgelen),\n ToEdgeLen=as.numeric(toedgelen),\n TotalDist=as.numeric(totaldistance),\n DistMinusStartEndLen=as.numeric(distminusstartendlen),\n DistMinusSEExceedsThreshold = as.logical(bDistMinusSEExceedsThreshold),\n FromEdgeHab=fromedgehab,\n ToEdgeHab=toedgehab,\n FromEdgeName=as.character(fromedgename),\n ToEdgeName=as.character(toedgename),\n ToFromEdgeNameCombo=as.character(tofromedgename_combo))\n outlist[[count]] <- (DL1)\n }else if(option==\"dplyr\"){\n DL1 = list(FromNode=as.character(fromnode_name),\n ToNode=as.character(tonode_name),\n FromNodeLabel=as.character(fromnode_label),\n ToNodeLabel=as.character(tonode_label),\n CumulativePass=as.numeric(cumulativepass), \n FromEdgeLen=as.numeric(fromedgelen),\n ToEdgeLen=as.numeric(toedgelen),\n TotalDist=as.numeric(totaldistance),\n DistMinusStartEndLen=as.numeric(distminusstartendlen),\n DistMinusSEExceedsThreshold = as.logical(bDistMinusSEExceedsThreshold),\n FromEdgeHab=as.numeric(fromedgehab),\n ToEdgeHab=as.numeric(toedgehab),\n FromEdgeName=fromedgename,\n ToEdgeName=toedgename,\n ToFromEdgeNameCombo=tofromedgename_combo)\n #print(row1)\n DF2 <- bind_rows(DF2,DL1)\n }\n } #k\n } #j\n \n if(option==\"dt\"){\n sum_tab <- DT2\n }else if(option==\"dt-lists\"){\n DT2 <- data.table(rbindlist(outlist))\n \n sum_tab <- DT2\n }else if(option==\"df\"){\n #DF2 <- DF2[!duplicated(DF2$ToFromEdgeNameCombo), ]\n sum_tab <- DF2\n }else if(option==\"df-lists\"){\n DF2 <- data.frame(do.call(rbind, outlist))\n #DF2 <- DF2[!duplicated(DF2$ToFromEdgeNameCombo), ]\n sum_tab <- DF2\n }else if(option==\"dplyr\"){\n sum_tab <- DF2\n }\n \n # if a distance limit, eliminate rows\n if(bDistanceLim == TRUE){\n return(sum_tab[DistMinusSEExceedsThreshold==FALSE])\n }else{\n return(sum_tab) \n } \n \n}\n\n#######################################################\n###### Calculate DCI #####\n#dci_calc_2020_dd <- function(){}\n# warning: the sum_tab_2020 must be a data.table\n# only some data frames work ('dplyr' is ok not\n# the 'df-lists' option)\n\n\n######### (1) DCId - calc_DCId #########\ncalc_DCId_2020 <- function(sum_tab_2020=NULL,\n totalhabitat=0.0,\n FromNode=\"sink\",\n bDistanceLim=FALSE){\n \n # filter table\n DCId_data<-subset(sum_tab_2020,FromNode==\"sink\")\n \n # Credit to Chris Edge Code for avoiding loops in R here: \n if(bDistanceLim==FALSE){\n DCId_data$temp <- DCId_data$CumulativePass * (DCId_data$ToEdgeHab/totalhabitat)\n }else{\n DCId_data$temp <- DCId_data$CumulativePass * (DCId_data$ToEdgeHabMaxAccessible/DCId_data$MaxTotalAccessHabFromEdge)\n }\n DCId <- sum(DCId_data$temp)\n return(round(DCId*100,2))\n} # DCId\n\n######### (2) DCIp - calc_DCIp #########\n# Credit to C Edge for shorter code\ncalc_DCIp_2020 <- function(sum_tab_2020=NULL,\n totalhabitat=0.0,\n option=\"unique\",\n bDistanceLim=FALSE){\n \n # 'option' = unique / distinct for benchmarking speeds\n # unique = data.table / base r\n # distinct = dplyr\n # to do: sometimes sum_tab may be a data.table sometimes data.frame\n if(option==\"unique\"){\n sum_tab_2020 <- unique(sum_tab_2020, by = \"ToFromEdgeNameCombo\")\n }else{\n sum_tab_2020 <- distinct(sum_tab_2020, ToFromEdgeNameCombo, .keep_all = TRUE)\n }\n\n DCIp <- 0\n if(bDistanceLim==FALSE){\n for (i in 1:nrow(sum_tab_2020)) {\n DCIp <- DCIp + (sum_tab_2020$CumulativePass[i] * (sum_tab_2020$FromEdgeHab[i]/totalhabitat)) * (sum_tab_2020$ToEdgeHab[i]/totalhabitat)\n }\n }else{\n for (i in 1:nrow(sum_tab_2020)) {\n DCIp <- DCIp + (sum_tab_2020$CumulativePass[i] * (sum_tab_2020$FromEdgeHab[i]/totalhabitat))* (sum_tab_2020$ToEdgeHabMaxAccessible[i]/sum_tab_2020$MaxTotalAccessHabFromEdge[i]) \n }\n }\n return(round(DCIp*100,2))\n}\n\n######### (3) DCIs - calc_DCIs #########\n# can be added into (2) as option see below\ncalc_DCIs_2020 <- function (sum_tab_2020=NULL,\n totalhabitat=0.0,\n option=\"dt\",\n bDistanceLim=FALSE){\n \n # option: \"dt\",\"dplyr\",\"old\"\n # alternative methods for benchmarking\n if(option==\"dt\"){\n \n DCIs <- sum_tab_2020\n # remove duplicates\n DCIs <- unique(sum_tab_2020, by = \"ToFromEdgeNameCombo\")\n \n if(bDistanceLim==FALSE){\n # select only a required columns\n cols = c(\"FromEdgeName\",\"ToEdgeHab\",\"CumulativePass\")\n DCIs <- DCIs[,..cols]\n # first step to DCIs\n DCIs[, DCIs_i := round(ToEdgeHab/totalhabitat * CumulativePass * 100,2)]\n }else{\n # select only a required columns\n cols = c(\"FromEdgeName\",\"ToEdgeHabMaxAccessible\",\"CumulativePass\",\"MaxTotalAccessHabFromEdge\")\n DCIs <- DCIs[,..cols]\n # first step to DCIs\n DCIs[, DCIs_i := round(ToEdgeHabMaxAccessible/MaxTotalAccessHabFromEdge * CumulativePass * 100,2)]\n }\n \n cols = c(\"FromEdgeName\",\"DCIs_i\")\n DCIs <- DCIs[,..cols]\n # second step to DCIs\n DCIs <- DCIs[, lapply(.SD,sum), by=.(FromEdgeName)]\n \n }else if(option==\"dplyr\"){\n \n if(bDistanceLim==FALSE){\n DCIs <- sum_tab_2020 %>%\n distinct(ToFromEdgeNameCombo, .keep_all = TRUE) %>%\n mutate(DCIs_i = CumulativePass * ToEdgeHab/totalhabitat * 100) %>%\n select(DCIs_i,FromEdgeName) %>%\n group_by(FromEdgeName) %>%\n summarise(DCIs = sum(DCIs_i))\n }else{\n DCIs <- sum_tab_2020 %>%\n distinct(ToFromEdgeNameCombo, .keep_all = TRUE) %>%\n mutate(DCIs_i = CumulativePass * ToEdgeHabMaxAccessible/MaxTotalAccessHabFromEdge)*100 %>%\n select(DCIs_i,FromEdgeName) %>%\n group_by(FromEdgeName) %>%\n summarise(DCIs = sum(DCIs_i))\n }\n \n \n }else if(option==\"old\"){\n sum_tab_2020 <- unique(sum_tab_2020, by = \"ToFromEdgeNameCombo\")\n sections<-as.vector(unique(sum_tab_2020$FromEdgeName))\n # store the all section results in DCI.as\n DCI_as<-NULL\n \n for(s in 1:length(sections)){\n DCI_s<-0\n # Old notes:\n # select out only the data that corresponds to pathways from one sectino \n # to all other sections\n d_nrows<-subset(sum_tab_2020, FromEdgeName==sections[s])\n d_sum_table<-d_nrows\n \n if(bDistanceLim==FALSE){\n for (a in 1:dim(d_nrows)[1]){\n # Old note:\n #to get the DCI for diadromous fish, use the following formula: \n # DCId= li/L*Cj (where j= the product of the passability in the pathway)\n la<-d_sum_table$ToEdgeHab[a]/sum(FIPEX_table$HabQuantity)\n pass_d<-d_sum_table$CumulativePass[a]\n DCI_s<-round(DCI_s+la*pass_d*100, digits=2)\n } # end loop over sections for dci calc\n }else{\n for (a in 1:dim(d_nrows)[1]){\n # Old note:\n #to get the DCI for diadromous fish, use the following formula: \n # DCId= li/L*Cj (where j= the product of the passability in the pathway)\n la<-d_sum_table$ToEdgeHabMaxAccessible[a]/d_sum_table$MaxTotalAccessHabFromEdge\n pass_d<-d_sum_table$CumulativePass[a]\n DCI_s<-round(DCI_s+la*pass_d*100, digits=2)\n } # end loop over sections for dci calc\n }\n DCI_as[s]<-round(DCI_s*100,2)\n } # end loop over \"first\" sections\t\n\n # STORE RESULTS IN .CSV file\n DCIs<-data.frame(sections,DCI_as)\n }else{\n print(\"error in options passed to calc_DCIs\")\n DCIs <- 0.0\n }\n return(DCIs)\n}\n\napply_distance_limits <- function(sum_tab_2020 = NULL, \n bDistanceLim=FALSE, \n dMaxDist=0.0,\n bDistanceDecay=FALSE,\n sDDFunction=\"none\"){\n \n # calculate proportion of 'to edge' within the max distance and multiply\n #sum_tab_2020 <- sum_tab_2020 %>%\n #mutate(ToEdgeHabProp = (DistMinusStartEndLen+ToEdgeLen-dMaxDist)/ToEdgeLen) %>%\n #mutate(ToEdgeHabProp = ifelse(ToEdgeHabProp>=0,1-ToEdgeHabProp,1)) %>%\n #mutate(ToEdgeHabMaxAccessible = ToEdgeHabProp * ToEdgeHab) %>%\n #select(-ToEdgeHabProp)\n\n get_max_accessible <- function(DistMinusStartEndLen,ToEdgeLen,ToEdgeHab,dMaxDist){\n prop_accessible = (dMaxDist-DistMinusStartEndLen)/ToEdgeLen\n prop_accessible = ifelse(prop_accessible>0,prop_accessible,0)\n prop_accessible = ifelse(prop_accessible>1,1,prop_accessible)\n toedge_maxaccessible = prop_accessible * ToEdgeHab\n toedge_maxaccessible\n }\n\n sum_tab_2020[, ToEdgeHabMaxAccessible := get_max_accessible(DistMinusStartEndLen,\n ToEdgeLen,ToEdgeHab,dMaxDist)]\n \n if(bDistanceDecay==TRUE & sDDFunction!=\"none\"){\n sum_tab_2020 <- apply_distance_decay(sum_tab_2020,sDDFunction,dMaxDist)\n # overwriting here because totals below should be based on weighted hab\n sum_tab_2020$ToEdgeHabMaxAccessible = sum_tab_2020$toedgehabaccessible_dd\n }\n \n # sum habitat accessible from edge and add as attribute\n # in new column \n # remove duplicates first...\n # to do: dplyr is slower than data.table - re-code and benchmark\n sum_tab_hab <- sum_tab_2020 %>% \n distinct(ToFromEdgeNameCombo, .keep_all = TRUE) %>%\n group_by(FromEdgeName) %>%\n summarise(MaxTotalAccessHabFromEdge = sum(ToEdgeHabMaxAccessible))\n\n sum_tab_2020 <- sum_tab_2020 %>%\n left_join(sum_tab_hab, by = \"FromEdgeName\", copy=FALSE)\n \n return(data.table(sum_tab_2020))\n}\n\napply_distance_decay <- function(sum_tab_2020=NULL,\n sDDFunction=\"none\",\n dMaxDist = 0.0){\n\n# distance decay options: \"linear\" - linear (1-x), \n# \"natexp1\"- natural exponential #1 (general form: e^x), \n# \"natexp2\" - natural exponential #2 (general form: e^x^2), \n# \"circle\" - based on equation of circle ((1-x^2)^0.5)\n# \"sigmoid\" - sigmoid (general form:1/(1+e^x)\n# functions chosen because they can be integrated analytically.\n# for analytical solutions see documentation. \n# general form modified so intercepts are (0,1),(1,0) - sometimes approximate\n# G Oldford, 2020\n\n# to do: data.tables with many columns don't perform well and melt() may \n# help\n\n########## General Formulas ##########\n# multiplies the 'maximum accessible habitat' at edge j by f_avg(a,b)\n# (max accessible is pre-calculated earlier using cut-off value and distance of edge j from edge i)\n# \n# avg value of a dd function:\n# f_avg(a,b,f(x)) = 1/(b-a)*integral_a_to_b(f(x)dx)\n# represents average value of distance decay function f(x) between \n# two positions, a and b, along total distance from end of edge i to maxdist\n# where a and b are positions from 0 to maxdist (maxdist is always\n# rescaled to 1. \n# 'a' - proportion of maxdist reached at start of edge j \n# 'b' - proportion of maxdist reached at end of edge j \n e = exp(1)\n \n########## LINEAR distance decay function ##########\n# function: (1-x) where x is proportion of maxdist\n# f_avg = ((1-b)+(1-a))/2 \n# toedgehabaccessible_dd = f_avg(a,b)*ToEdgeHabMaxAccessible\n f_avg_linear <- function(a,b) {((1-b)+(1-a))/2}\n\n########## natural exponential DD Function #1 ########## \n########## general form: (-e^x) ##########\n# parameterized function: f(x) = 1-e^(5(x-5)) with zero intercepts (0,1),(1,0)\n# integral of f(x) = F_int = x - e^(5(x-1))/5)\n# f_avg(a,b,f(x)) = 1/(b-a)*(b - e^(5(b-1))/5 -(a - e^(5(a-1))/5))\n integral_fx_natexp1 <- function(x){x-e^(5*(x-1))/5}\n f_avg_natexp1 <- function(a,b) {(1/(b-a)*(integral_fx_natexp1(b)-integral_fx_natexp1(a)))}\n\n########## natural exponential DD Function #2 ########## \n########## general form: -e^x^2 ##########\n# parameterized function: f(x) = 2 - e^((x^2)*1/1.44)\n# integral of f(x) = F_int = ((pi*i)^1/3 * erf(5*i*x/6)) / 5 + 2*x\n# f_avg(a,b,f(x)) = to do\n # Note complete - can't be done without special erfi function \n erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1\n integral_fx_natexp2 <- function(x){((pi*i)^1/3 * erf(5*i*x/6)) / 5 + 2*x}\n\n########## CIRCULAR DD Function ########## \n########## general form: (1-x^2)^0.5 ##########\n# parameterized function: f(x) = (1-x^2)^0.5\n# integral of f(x) = F_int = (asin(x)+x*(1-x^2)^0.5)/2\n# f_avg(a,b,f(x)) = (asin(b)+b*(1-b^2)^0.5)/2 - (asin(a)+a*(1-a^2)^0.5)/2\n integral_fx_circle <- function(x){(asin(x)+x*(1-x^2)^0.5)/2}\n f_avg_circle <- function(a,b){((asin(b)+b*(1-b^2)^0.5)/2 - (asin(a)+a*(1-a^2)^0.5)/2)}\n\n\n###### SIGMOID DD function ###### \n###### general form: 1/(e^x+1))######\n# parameterized function: f(x) = 1/(e^(10(x*0.5)))+1\n# integral f(x) = F_int = x - ln(e^10x+e^5)/10\n# f_avg(a,b,f(x)) = 1/(b-a)*(b - ln(e^10b+e^5)/10- a - ln(e^10a+e^5)/10)\n integral_fx_sigmoid <- function(x){x - log(e^10*x+e^5)/10}\n f_avg_sigmoid <- function(a,b) {(1/(b-a)*(integral_fx_sigmoid(b)-integral_fx_sigmoid(a)))}\n\n##### Calculate distance-decay weighted habitat accessible ######\n##### (at each edge j from each each i)\n get_dd_habitat <- function(DistMinusStartEndLen,ToEdgeHabMaxAccessible,dMaxDist,sDDFunction){\n \n a = round(DistMinusStartEndLen/dMaxDist,3)\n b = round((DistMinusStartEndLen+ToEdgeHabMaxAccessible)/dMaxDist,3)\n \n a = ifelse(a<0,0,a)\n a = ifelse(a>1,1,a)\n b = ifelse(b<0,0,b)\n b = ifelse(b>1,1,b)\n \n if(sDDFunction==\"linear\"){\n toedgehab_dd <- ToEdgeHabMaxAccessible * f_avg_linear(a,b)\n }else if(sDDFunction==\"natexp1\"){\n toedgehab_dd <- ToEdgeHabMaxAccessible*f_avg_natexp1(a,b)\n }else if(sDDFunction==\"natexp2\"){\n # to do\n }else if(sDDFunction==\"circle\"){\n toedgehab_dd <- ToEdgeHabMaxAccessible*f_avg_circle(a,b)\n }else if(sDDFunction==\"sigmoid\"){\n toedgehab_dd <- ToEdgeHabMaxAccessible*f_avg_sigmoid(a,b)\n }\n \n # if the segment is tiny compared to cutoff distance \n # this can result in NaN's which cause issues.\n toedgehab_dd[ is.nan(toedgehab_dd) ] <- 0\n\n toedgehab_dd\n }\n\n sum_tab_2020[, toedgehabaccessible_dd := round(get_dd_habitat(DistMinusStartEndLen,\n ToEdgeHabMaxAccessible,\n dMaxDist,\n sDDFunction),2)]\n return(sum_tab_2020)\n \n}\n\n# ########################################\n# ########## MAIN CODE SECTION ############\n\n# intialize file with error code\nwrite(\"ERROR\",file='out_dd.txt')\n\n# required libraries\nlibrary(RBGL) \nlibrary(data.table) \nlibrary(tidyverse)\n# RBGL and Rgraphviz must be installed via BioconductR\n#install.packages(\"BiocManager\")\n#BiocManager::install(\"Rgraphviz\")\n#BiocManager::install(\"RBGL\")\n\n# optional libraries\n#library(Rgraphviz) # only needed for visuals\n#library(rbenchmark) \n\n########## 1) DATA PREP #########\n\n# 'Advanced' table includes habitat, length, connectivity info in one table\nFIPEX_table=read.csv(\"FIPEX_Advanced_DD_2020.csv\")\n# ensure it's \"sink\" not \"Sink\"\nFIPEX_table <- FIPEX_table %>%\nmutate(DownstreamEID = ifelse(DownstreamEID == \"Sink\",\"sink\",as.character(DownstreamEID)))\n\n# for testing only: natural TF set node 84 to natural barrier\n#FIPEX_table[2,]$NaturalTF <- TRUE\n#FIPEX_table\n\n# The params file allows users to pass param settings\n# to R from within the ArcMap software (new in 2020)\nFIPEX_params=read.csv(\"FIPEX_2020_params.csv\")\n\n###### 2) PARAMETERIZATION #######\n\nbDCISectional <- as.logical(FIPEX_params$bDCISectional)\nbDistanceLim <- as.logical(FIPEX_params$bDistanceLim)\ndMaxDist <- as.double(FIPEX_params$dMaxDist)\nbDistanceDecay <- as.logical(FIPEX_params$bDistanceDecay)\nsDDFunction <- as.character(FIPEX_params$sDDFunction)\n# for testing:\n#sDDFunction = \"linear\"\n#sDDFunction = \"natexp1\"\n#sDDFunction = \"circle\"\n#sDDFunction = \"sigmoid\"\n#sDDFunction = \"none\"\n#bDistanceLim = FALSE\n#dMaxDist = 1000\n#bDistanceDecay = FALSE\nnaturalonly = FALSE\n#bDCISectional = TRUE\nbDCIp = TRUE\n\ntotalhabitat = sum(FIPEX_table$HabQuantity)\ntotallength = sum(FIPEX_table$DownstreamNeighDistance)\n\n######### 3) NETWORK ANALYSIS #########\n\n# build adjacency matrix\nedgeweighted_adj_matrix <- create_advanced_adjmatrix_2020(FIPEX_table)\n\n# build graph object\ng_dd <- create_graph_dd_2020(edgeweighted_adj_matrix,FIPEX_table)\n\n# build summary table (analyses to determine paths, pass, etc between edges)\nsum_tab_2020 <- get_summary_tab_2020(option=\"dt-lists\",\n naturalonly,\n g_dd,\n bDCIp,\n bDistanceLim,\n dMaxDist)\n\nif(bDistanceLim==TRUE){\n sum_tab_2020 <- apply_distance_limits(sum_tab_2020, bDistanceLim, dMaxDist, bDistanceDecay, sDDFunction)\n}\n\n# for testing: turn all pass = 1 and DCI should = 1\n#sum_tab_2020<- sum_tab_2020 %>% mutate(CumulativePass=1)\n#sum_tab_2020 = as.data.table(sum_tab_2020)\n\n######## 4) DCI CALC ########\nDCId = 0.00\nDCIp = 0.00\nDCIs = 0.00\n\nDCId <- calc_DCId_2020(sum_tab_2020,totalhabitat,\"sink\",bDistanceLim)\nif(bDCIp==TRUE){\n DCIp <- calc_DCIp_2020(sum_tab_2020,totalhabitat,\"unique\",bDistanceLim)\n\t# sectional can only be run if DCIp has been selected\n if(bDCISectional==TRUE){\n DCIs <- calc_DCIs_2020(sum_tab_2020,totalhabitat,\"dt\",bDistanceLim)\n }\n}\n\n######## 5) Write to Files ######\n\n# following previous output format\nres<- data.frame(c(DCIp,DCId))\nnames(res)<-\"value\"\nrow.names(res)<-c(\"DCIp\",\"DCId\")\nwrite.table(res,file='out_dd.txt')\n\n# transform data to match what FIPEX expects\n# DCIs 'FromEdgeName' 100-101 has first numbers as downstream node\n# to align in FIPEX it can be adjusted to e.g., 100_s\n# however, this results in more than one segment since, say, node\n# 100 can have multiple upstream edges and nodes.\n# To address this the _downstream_ segment DCI_s can be reported\n# for each node in the system. This change will have to be carefully reported\n# to the user!\nif(bDCISectional==TRUE & bDCIp==TRUE){\n names(DCIs)[names(DCIs) == 'DCIs_i'] <- 'DCI_as'\n names(DCIs)[names(DCIs) == 'FromEdgeName'] <- 'section'\n \n #DCIs$sections <- paste(sub(\"\\\\-.*\", \"\", DCIs$section),\"_s\",sep=\"\")\n # there was a problem encountered with the above because it resulted\n # in more than one upstream segment associated with each node. I \n # reversed this but now need to be careful that the segmental DCI\n # is now reported as associated with the immediate _downstream_\n # segement from each node!\n DCIs$sections <- paste(sub(\".*\\\\-\", \"\", DCIs$section),\"_s\",sep=\"\")\n\n DCIs$sections[DCIs$sections == \"sink_s\"] <- \"sink\"\n DCIs <- DCIs %>% select(sections,DCI_as)\n res<-data.frame(DCIs)\n write.table(x=res,\n file=\"DCI_all_sections_dd.csv\",\n sep=\",\",\n row.names=F)\n}\n\n\n\n\n", "meta": {"hexsha": "4f7e1366b82f67cb4a1b49df8529a2beff727de3", "size": 39828, "ext": "r", "lang": "R", "max_stars_repo_path": "2020/FIPEX_run_DCI_DD_2020.r", "max_stars_repo_name": "aligharouni/DCI-R-Code-2020", "max_stars_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/FIPEX_run_DCI_DD_2020.r", "max_issues_repo_name": "aligharouni/DCI-R-Code-2020", "max_issues_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/FIPEX_run_DCI_DD_2020.r", "max_forks_repo_name": "aligharouni/DCI-R-Code-2020", "max_forks_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-17T17:27:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:27:40.000Z", "avg_line_length": 40.8073770492, "max_line_length": 189, "alphanum_fraction": 0.5929998996, "num_tokens": 10417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.468908336515403}} {"text": "#########################################################################\n# Simulation trial\n\ntrial <- function(tau=1.2) {\n args = commandArgs(trailingOnly=TRUE)\n config_id <- args[1] %>% as.numeric\n trial_id <- Sys.getenv('SLURM_ARRAY_TASK_ID') %>% as.numeric\n obs <- .obs(config_id)\n y <- obs$y; X <- obs$X; Z <- obs$Z; D <- obs$D; u <- obs$u\n n <- nrow(X); px <- ncol(X); pz <- ncol(Z)\n Sigma_z <- obs$Sigma_z\n Alpha0 <- obs$Alpha0\n sigma0_u <- obs$sigma0_u; sigma0_v <- obs$sigma0_v\n beta0 <- obs$beta0\n\n # first stage estimation\n lambda_j.Alpha0hat <- .lambda_j.Alpha0hat(X, Z, sigma0_v, tune_type = \"CV\")\n lambda_j <- lambda_j.Alpha0hat$lambda_j; Alpha0hat <- lambda_j.Alpha0hat$Alpha0hat\n\n # second-stage estimation\n D.hat <- Z %*% Alpha0hat\n lambda.beta_Lasso <- .lambda.beta_Lasso(y, D.hat, sigma0_u, no_pen_ids=c())\n lambda <- lambda.beta_Lasso$lambda; beta_Lasso_D.hat <- lambda.beta_Lasso$beta_Lasso\n\n # relaxed inverse estimation\n Sigma_d.hat <- .Sigmahat(D.hat)\n Id <- diag(1, px) # Identity matrix\n\n # Calculate JM estimator\n res_JM <- .Theta.hat_JM(Sigma_d.hat, n)\n Theta.hat_JM <- res_JM$Theta.hat; mus_JM <- res_JM$mus\n mu_stars_JM <- map_dbl(1:px,\n ~ { (Sigma_d.hat %*% Theta.hat_JM[.,] - Id[.,]) %>% abs %>% max})\n objs_JM <- map_dbl(1:px,\n ~ { Theta.hat_JM[.,] %>% abs %>% sum })\n\n # Calculate CLIME estimator\n mus_CLIME <- find_mus(Sigma_d.hat) * tau\n Theta.hat_CLIME <- .Theta.hat_CLIME(Sigma_d.hat, mus_CLIME)\n mu_stars_CLIME <- map_dbl(1:px,\n ~ { (Sigma_d.hat %*% Theta.hat_CLIME[.,] - Id[.,]) %>% abs %>% max})\n objs_CLIME <- map_dbl(1:px,\n ~ { Theta.hat_CLIME[.,] %>% abs %>% sum })\n\n # de-biased second-stage lasso estimation\n beta_debiased_CLIME <- .beta_debiased(y, X, D.hat, beta_Lasso_D.hat, Theta.hat_CLIME)\n beta_debiased_JM <- .beta_debiased(y, X, D.hat, beta_Lasso_D.hat, Theta.hat_JM)\n\n # Predict the second-stage noise\n u.hat <- y - X %*% beta_Lasso_D.hat\n sd_u.hat <- u.hat^2 %>% mean %>% sqrt\n\n # To record/compute estimate of Theta_jj (and Theta_jj)\n Theta <- solve(t(Alpha0) %*% Sigma_z %*% Alpha0)\n\n # Calculate remainder terms\n rem_1_CLIME <- (Theta.hat_CLIME-Theta)%*%t(D)%*%u/sqrt(n)\n rem_1_JM <- (Theta.hat_JM-Theta)%*%t(D)%*%u/sqrt(n)\n rem_2_CLIME <- Theta.hat_CLIME%*%t(D.hat-D)%*%u/sqrt(n)\n rem_2_JM <- Theta.hat_JM%*%t(D.hat-D)%*%u/sqrt(n)\n rem_3_CLIME <- Theta.hat_CLIME%*%t(D.hat)%*%(X-D.hat)%*%(beta_Lasso_D.hat-beta0)/sqrt(n)\n rem_3_JM <- Theta.hat_JM%*%t(D.hat)%*%(X-D.hat)%*%(beta_Lasso_D.hat-beta0)/sqrt(n)\n rem_4_CLIME <-sqrt(n)*(Theta.hat_CLIME%*%Sigma_d.hat-Id)%*%(beta_Lasso_D.hat-beta0)\n rem_4_JM <-sqrt(n)*(Theta.hat_JM%*%Sigma_d.hat-Id)%*%(beta_Lasso_D.hat-beta0)\n\n # Calculate main term\n w <- Theta%*%t(D)%*%u/sqrt(n)\n\n # estimator data\n df_est <- data.frame(\n config_id = rep(config_id, 3*px),\n trial_id = rep(trial_id, 3*px),\n estimator = c(rep(\"Debiased_CLIME\", px), rep(\"Debiased_JM\", px), rep(\"Lasso\", px)),\n j = rep(1:px, 3),\n estimate_j = c(beta_debiased_CLIME, beta_debiased_JM, beta_Lasso_D.hat),\n beta0_j = rep(beta0, 3),\n SE1 = c(.SE1(Sigma_d.hat, Theta.hat_CLIME, sd_u.hat),\n .SE1(Sigma_d.hat, Theta.hat_JM, sd_u.hat),\n rep(NA, px)),\n SE2 = c(.SE2(D.hat, Theta.hat_CLIME, u.hat),\n .SE2(D.hat, Theta.hat_JM, u.hat),\n rep(NA, px)),\n SE3 = c(.SE3(Theta.hat_CLIME, sd_u.hat),\n .SE3(Theta.hat_JM, sd_u.hat),\n rep(NA, px)),\n Theta_jj = c(diag(Theta), diag(Theta), rep(NA, px)),\n Theta.hat_jj = c(diag(Theta.hat_CLIME), diag(Theta.hat_JM), rep(NA, px)),\n mu = c(mus_CLIME, mus_JM, rep(NA, px)),\n mu_stars = c(mu_stars_CLIME, mu_stars_JM, rep(NA, px)),\n objs = c(objs_CLIME, objs_JM, rep(NA, px)),\n w = c(w, w, rep(NA, px)),\n rem_1 = c(rem_1_CLIME, rem_1_JM, rep(NA, px)),\n rem_2 = c(rem_2_CLIME, rem_2_JM, rep(NA, px)),\n rem_3 = c(rem_3_CLIME, rem_3_JM, rep(NA, px)),\n rem_4 = c(rem_4_CLIME, rem_4_JM, rep(NA, px)),\n lambda_j = rep(lambda_j, 3)\n )\n # df_est <- data.frame(\n # config_id = rep(config_id, 2*px),\n # trial_id = rep(trial_id, 2*px),\n # estimator = c(rep(\"Debiased_CLIME\", px), rep(\"Lasso\", px)),\n # j = rep(1:px, 2),\n # estimate_j = c(beta_debiased_CLIME, beta_Lasso_D.hat),\n # beta0_j = rep(beta0, 2),\n # SE1 = c(.SE1(Sigma_d.hat, Theta.hat_CLIME, sd_u.hat),\n # rep(NA, px)),\n # SE2 = c(.SE2(D.hat, Theta.hat_CLIME, u.hat),\n # rep(NA, px)),\n # SE3 = c(.SE3(Theta.hat_CLIME, sd_u.hat),\n # rep(NA, px)),\n # Theta_jj = c(diag(Theta), rep(NA, px)),\n # Theta.hat_jj = c(diag(Theta.hat_CLIME), rep(NA, px)),\n # mu_stars = c(mu_stars_CLIME, rep(NA, px)),\n # objs = c(objs_CLIME, rep(NA, px))\n # # vhat = rep(vhat, 2),\n # lambda_j = rep(lambda_j, 2)\n # )\n\n # statistics\n mu_star_CLIME <- (Theta.hat_CLIME %*% Sigma_d.hat - diag(1, ncol(Sigma_d.hat))) %>% abs %>% max\n mu_star_JM <- (Theta.hat_JM %*% Sigma_d.hat - diag(1, ncol(Sigma_d.hat))) %>% abs %>% max\n mse_Debiased_CLIME <- (y - X %*% beta_debiased_CLIME)^2 %>% mean\n mse_Debiased_JM <- (y - X %*% beta_debiased_JM)^2 %>% mean\n mse_Lasso_D.hat <- (y - X %*% beta_Lasso_D.hat)^2 %>% mean\n\n # estimation statistics data\n df_stats <- data.frame(\n config_id = rep(config_id, 3),\n trial_id = rep(trial_id, 3),\n estimator = c(\"Debiased_CLIME\", \"Debiased_JM\", \"Lasso\"),\n mse = c(mse_Debiased_CLIME, mse_Debiased_JM, mse_Lasso_D.hat),\n sd_u = rep(sd_u.hat, 3),\n # mu = c(mu, NA),\n tau = c(tau, NA, NA),\n mu_star = c(mu_star_CLIME, mu_star_JM, NA),\n # trial_cvg = c(trial_cvg, NA),\n lambda = rep(lambda, 3)\n )\n # df_stats <- data.frame(\n # config_id = rep(config_id, 2),\n # trial_id = rep(trial_id, 32),\n # estimator = c(\"Debiased_CLIME\", \"Lasso\"),\n # mse = c(mse_Debiased_CLIME, mse_Lasso_D.hat),\n # sd_u = rep(sd_u.hat, 2),\n # # mu = c(mu, NA),\n # tau = c(tau, NA),\n # mu_star = c(mu_star_CLIME, NA),\n # # trial_cvg = c(trial_cvg, NA),\n # lambda = rep(lambda, 2)\n # )\n\n write.csv(df_est, paste(\"res/est_\", config_id, \"_\", trial_id, \".csv\", sep=\"\"))\n write.csv(df_stats, paste(\"res/stats_\", config_id, \"_\", trial_id, \".csv\", sep=\"\"))\n}\n", "meta": {"hexsha": "84a1f70628077e05001f2f045b4f482c6550a949", "size": 6204, "ext": "r", "lang": "R", "max_stars_repo_path": "src/trial.r", "max_stars_repo_name": "LedererLab/InstrumentalVariables", "max_stars_repo_head_hexsha": "35d58b0555d334a669283e7f680248bf041c69fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-02T11:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T09:14:00.000Z", "max_issues_repo_path": "src/trial.r", "max_issues_repo_name": "LedererLab/InstrumentalVariables", "max_issues_repo_head_hexsha": "35d58b0555d334a669283e7f680248bf041c69fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trial.r", "max_forks_repo_name": "LedererLab/InstrumentalVariables", "max_forks_repo_head_hexsha": "35d58b0555d334a669283e7f680248bf041c69fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-23T16:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:14:03.000Z", "avg_line_length": 40.0258064516, "max_line_length": 97, "alphanum_fraction": 0.6060606061, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46890832297653734}} {"text": "# qvalue() function extracted from the package \"qvalue\"\n# by Alan Dabney and John D. Storey, with assistance from Gregory R. Warnes\n#\n# DESCRIPTION file follows:\n#\n# Package: qvalue\n# Title: Q-value estimation for false discovery rate control\n# Version: 1.32.0\n# Author: Alan Dabney and John D. Storey\n# , with assistance from Gregory R.\n# Warnes \n#\n# Description: This package takes a list of p-values resulting from the\n# simultaneous testing of many hypotheses and estimates their\n# q-values. The q-value of a test measures the proportion of\n# false positives incurred (called the false discovery rate)\n# when that particular test is called significant. Various plots\n# are automatically generated, allowing one to make sensible\n# significance cut-offs. Several mathematical results have\n# recently been shown on the conservative accuracy of the\n# estimated q-values from this software. The software can be\n# applied to problems in genomics, brain imaging, astrophysics,\n# and data mining.\n# Maintainer: John D. Storey \n# \tImports: graphics, stats\n# License: LGPL\n# biocViews: MultipleComparisons\n# Packaged: 2012-10-02 02:49:23 UTC; biocbuild\n# InstallableEverywhere: yes\n\nqvalue <- function(p=NULL, lambda=seq(0,0.90,0.05), pi0.method=\"smoother\", fdr.level=NULL, robust=FALSE, \n\t\t\t\t\t\t\t\t\t gui=FALSE, smooth.df = 3, smooth.log.pi0 = FALSE) {\n\t\n\t#This is just some pre-processing\n\tif(is.null(p)) ## change by Alan\n\t{qvalue.gui(); return(\"Launching point-and-click...\")}\n\tif(gui & !interactive()) ## change by Alan\n\t\tgui = FALSE\n\t\n\tif(min(p)<0 || max(p)>1) {\n\t\tif(gui) ## change by Alan: check for GUI\n\t\t\teval(expression(postMsg(paste(\"ERROR: p-values not in valid range.\", \"\\n\"))), parent.frame())\n\t\telse\n\t\t\tprint(\"ERROR: p-values not in valid range.\")\n\t\treturn(0)\n\t}\n\tif(length(lambda)>1 && length(lambda)<4) {\n\t\tif(gui)\n\t\t\teval(expression(postMsg(paste(\"ERROR: If length of lambda greater than 1, you need at least 4 values.\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\\n\"))), parent.frame())\n\t\telse\n\t\t\tprint(\"ERROR: If length of lambda greater than 1, you need at least 4 values.\")\n\t\treturn(0)\n\t}\n\tif(length(lambda)>1 && (min(lambda) < 0 || max(lambda) >= 1)) { ## change by Alan: check for valid range for lambda\n\t\tif(gui)\n\t\t\teval(expression(postMsg(paste(\"ERROR: Lambda must be within [0, 1).\", \"\\n\"))), parent.frame())\n\t\telse\n\t\t\tprint(\"ERROR: Lambda must be within [0, 1).\")\n\t\treturn(0)\n\t}\n\tm <- length(p)\n\t#These next few functions are the various ways to estimate pi0\n\tif(length(lambda)==1) {\n\t\tif(lambda<0 || lambda>=1) { ## change by Alan: check for valid range for lambda\n\t\t\tif(gui)\n\t\t\t\teval(expression(postMsg(paste(\"ERROR: Lambda must be within [0, 1).\", \"\\n\"))), parent.frame())\n\t\t\telse\n\t\t\t\tprint(\"ERROR: Lambda must be within [0, 1).\")\n\t\t\treturn(0)\n\t\t}\n\t\t\n\t\tpi0 <- mean(p >= lambda)/(1-lambda)\n\t\tpi0 <- min(pi0,1)\n\t}\n\telse {\n\t\tpi0 <- rep(0,length(lambda))\n\t\tfor(i in 1:length(lambda)) {\n\t\t\tpi0[i] <- mean(p >= lambda[i])/(1-lambda[i])\n\t\t}\n\t\t\n\t\tif(pi0.method==\"smoother\") {\n\t\t\tif(smooth.log.pi0)\n\t\t\t\tpi0 <- log(pi0)\n\t\t\t\n\t\t\tspi0 <- smooth.spline(lambda,pi0,df=smooth.df)\n\t\t\tpi0 <- predict(spi0,x=max(lambda))$y\n\t\t\t\n\t\t\tif(smooth.log.pi0)\n\t\t\t\tpi0 <- exp(pi0)\n\t\t\tpi0 <- min(pi0,1)\n\t\t}\n\t\telse if(pi0.method==\"bootstrap\") {\n\t\t\tminpi0 <- min(pi0)\n\t\t\tmse <- rep(0,length(lambda))\n\t\t\tpi0.boot <- rep(0,length(lambda))\n\t\t\tfor(i in 1:100) {\n\t\t\t\tp.boot <- sample(p,size=m,replace=TRUE)\n\t\t\t\tfor(i in 1:length(lambda)) {\n\t\t\t\t\tpi0.boot[i] <- mean(p.boot>lambda[i])/(1-lambda[i])\n\t\t\t\t}\n\t\t\t\tmse <- mse + (pi0.boot-minpi0)^2\n\t\t\t}\n\t\t\tpi0 <- min(pi0[mse==min(mse)])\n\t\t\tpi0 <- min(pi0,1)\n\t\t}\n\t\telse { ## change by Alan: check for valid choice of 'pi0.method' (only necessary on command line)\n\t\t\tprint(\"ERROR: 'pi0.method' must be one of 'smoother' or 'bootstrap'.\")\n\t\t\treturn(0)\n\t\t}\n\t}\n\tif(pi0 <= 0) {\n\t\tif(gui)\n\t\t\teval(expression(postMsg(\n\t\t\t\tpaste(\"ERROR: The estimated pi0 <= 0. Check that you have valid p-values or use another lambda method.\",\n\t\t\t\t\t\t\t\"\\n\"))), parent.frame())\n\t\telse\n\t\t\tprint(\"ERROR: The estimated pi0 <= 0. Check that you have valid p-values or use another lambda method.\")\n\t\treturn(0)\n\t}\n\tif(!is.null(fdr.level) && (fdr.level<=0 || fdr.level>1)) { ## change by Alan: check for valid fdr.level\n\t\tif(gui)\n\t\t\teval(expression(postMsg(paste(\"ERROR: 'fdr.level' must be within (0, 1].\", \"\\n\"))), parent.frame())\n\t\telse\n\t\t\tprint(\"ERROR: 'fdr.level' must be within (0, 1].\")\n\t\treturn(0)\n\t}\n\t#The estimated q-values calculated here\n\tu <- order(p)\n\t\n\t# change by Alan\n\t# ranking function which returns number of observations less than or equal\n\tqvalue.rank <- function(x) {\n\t\tidx <- sort.list(x)\n\t\t\n\t\tfc <- factor(x)\n\t\tnl <- length(levels(fc))\n\t\tbin <- as.integer(fc)\n\t\ttbl <- tabulate(bin)\n\t\tcs <- cumsum(tbl)\n\t\t\n\t\ttbl <- rep(cs, tbl)\n\t\ttbl[idx] <- tbl\n\t\t\n\t\treturn(tbl)\n\t}\n\t\n\tv <- qvalue.rank(p)\n\t\n\tqvalue <- pi0*m*p/v\n\tif(robust) {\n\t\tqvalue <- pi0*m*p/(v*(1-(1-p)^m))\n\t}\n\tqvalue[u[m]] <- min(qvalue[u[m]],1)\n\tfor(i in (m-1):1) {\n\t\tqvalue[u[i]] <- min(qvalue[u[i]],qvalue[u[i+1]],1)\n\t}\n\t#The results are returned\n\tif(!is.null(fdr.level)) {\n\t\tretval <- list(call=match.call(), pi0=pi0, qvalues=qvalue, pvalues=p, fdr.level=fdr.level, ## change by Alan\n\t\t\t\t\t\t\t\t\t significant=(qvalue <= fdr.level), lambda=lambda)\n\t}\n\telse {\n\t\tretval <- list(call=match.call(), pi0=pi0, qvalues=qvalue, pvalues=p, lambda=lambda)\n\t}\n\tclass(retval) <- \"qvalue\"\n\treturn(retval)\n}\n", "meta": {"hexsha": "3d4bb725da53c66628254928577ae71e16272194", "size": 5466, "ext": "r", "lang": "R", "max_stars_repo_path": "src/MG-RAST_ipy-mkmq/R/qvalue_function.r", "max_stars_repo_name": "teharrison/narrative", "max_stars_repo_head_hexsha": "71e2c49dfd1426d4a05e1f078946eaa271cae46a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MG-RAST_ipy-mkmq/R/qvalue_function.r", "max_issues_repo_name": "teharrison/narrative", "max_issues_repo_head_hexsha": "71e2c49dfd1426d4a05e1f078946eaa271cae46a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MG-RAST_ipy-mkmq/R/qvalue_function.r", "max_forks_repo_name": "teharrison/narrative", "max_forks_repo_head_hexsha": "71e2c49dfd1426d4a05e1f078946eaa271cae46a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3431952663, "max_line_length": 117, "alphanum_fraction": 0.6505671423, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4671756508349179}} {"text": "## --------------------\n## --------------------\n## --------------------\n## This file contains functions mainly for cross validation of Adaptive Penalized Tensor Decomposition.\n## Most function are only suitable for three dimension tensor. For higher-order tensor, codes should be modified adaptively.\n## --------------------\n## --------------------\n## --------------------\n\n\n## --------------------\n## Initialization for cross validation.\n## --------------------\nprepare_adaptive_adj <- function(tnsr, num_components, Niter = 1500, tol = 1e-05, year = 5, trace = FALSE, ku, kv, kw, splits = 10) {\n original <- tnsr\n Test <- tnsr[, , (dim(tnsr)[3] - year + 1):dim(tnsr)[3]]\n V1 <- list()\n S1 <- list()\n In1 <- list()\n mean1 <- list()\n sd1 <- list()\n tnsr <- tnsr[, , 1:(dim(tnsr)[3] - year)]\n for (m in 1:splits) {\n message(\"Training on years: \", paste(1:(dim(tnsr)[3] - splits - year + m), collapse = \"+\"))\n message(\"Test on years: \", paste((dim(tnsr)[3] - splits - year + m + 1):((dim(tnsr)[3] - splits - year + m + 1) + year - 1), collapse = \"+\"))\n\n temp_s <- tnsr@data[, , 1:(dim(tnsr)[3] - splits - year + m)]\n S1[[m]] <- as.tensor((temp_s - array(mean(temp_s), dim = dim(temp_s))) / sd(temp_s))\n mean1[[m]] <- c(mean(temp_s))\n sd1[[m]] <- c(sd(temp_s))\n\n V1[[m]] <- as.tensor(tnsr@data[, , (dim(tnsr)[3] - splits - year + m + 1):((dim(tnsr)[3] - splits - year + m + 1) + year - 1)])\n\n make_init <- gen_startvals(num_components, S1[[m]])\n\n message(\"Fitting unpenalized tensor...\")\n In1[[m]] <- multiple_tf_simple(\n tnsr = S1[[m]], d_hat = NULL, num_components = num_components,\n u_init = make_init$u, v_init = make_init$v, w_init = make_init$w,\n Niter = Niter, tol = tol,\n c1 = rep(0, num_components), c2 = rep(0, num_components), c3 = rep(0, num_components),\n ku = ku, kv = kv, kw = kw, trace = trace\n )\n message(\"Fitting completed.\")\n }\n\n ## generate D\n Dut <- list()\n Dvt <- list()\n Dwt <- list()\n for (m in 1:splits) {\n Dut[[m]] <- create_D(In1[[m]]$u, ord = (ku + 1))\n Dvt[[m]] <- create_D(In1[[m]]$v, ord = (kv + 1))\n Dwt[[m]] <- create_D(In1[[m]]$w, ord = (kw + 1))\n }\n\n\n return(list(\n Dut = Dut, Dvt = Dvt, Dwt = Dwt, In1 = In1, S1 = S1, V1 = V1, year = year,\n num_components = num_components, mean1 = mean1, sd1 = sd1, Test = Test, original = original\n ))\n}\n\n\n## --------------------\n## Function for cross validation.\n## --------------------\nmultiple_cv_adaptive_adj <- function(init, grid, ku = NULL, kv = NULL, kw = NULL, tol = 5e-05, Niter_small = 1500, splits = 10) {\n\n # trian data\n # input tenor should be training +validation tensor\n # third dimension should be year dimension\n\n tstart <- Sys.time()\n S1 <- init$S1\n V1 <- init$V1\n Dut <- init$Dut\n Dvt <- init$Dvt\n Dwt <- init$Dwt\n num_components <- init$num_components\n year <- init$year\n In1 <- init$In1\n mean1 <- init$mean1\n sd1 <- init$sd1\n\n sfInit(parallel = TRUE, cpus = 6)\n # load\n sfLibrary(rTensor)\n sfLibrary(genlasso)\n sfLibrary(forecast)\n sfLibrary(mgcv) # gam\n sfLibrary(Hmisc)\n sfExport(\n \"multiple_D_adaptive\", \"PTD_D\", \"In1\", \"tol\", \"product\", \"S1\", \"cal_pmse_gam_adj\",\n \"cal_pmse_arima_adj\", \"cal_pmse_linearextra_adj\", \"num_components\", \"V1\", \"year\", \"Niter_small\", \"Dut\", \"Dvt\", \"Dwt\", \"mean1\", \"sd1\"\n )\n\n best <- 0\n meanPMSE_gam <- meanPMSE_linextrap <- meanPMSE_arima <- NULL # record each combination's mean of the prediction RMSEs (averge of 10 )\n allPMSE_gam <- allPMSE_linextrap <- allPMSE_arima <- NULL\n\n for (i in 1:nrow(grid)) {\n message(\"Tuning parameters: \", paste(grid[i, ], collapse = \"/\"))\n sfExport(\"i\", \"grid\")\n\n parallel1 <- function(m, num_components, In1, grid, Niter_small, tol, Dut, Dvt, Dwt) {\n temp <- multiple_D_adaptive(\n tnsr = S1[[m]], num_components = num_components, d_hat = In1[[m]]$d,\n u_init = In1[[m]]$u, v_init = In1[[m]]$v, w_init = In1[[m]]$w,\n c1 = rep(grid[i, 1], num_components), c2 = rep(grid[i, 2], num_components), c3 = rep(grid[i, 3], num_components),\n Niter = Niter_small, tol = tol, Du = Dut[[m]], Dv = Dvt[[m]], Dw = Dwt[[m]], trace = FALSE\n )\n }\n\n tempresult <- sfLapply(1:splits, parallel1, num_components, In1, grid, Niter_small, tol, Dut, Dvt, Dwt)\n sfExport(\"tempresult\")\n\n temprmse_gam <- as.numeric(sfLapply(1:splits, cal_pmse_gam_adj, year = year))\n temprmse_linextrap <- as.numeric(sfLapply(1:splits, cal_pmse_linearextra_adj, year = year))\n temprmse_arima <- as.numeric(sfLapply(1:splits, cal_pmse_arima_adj, year = year))\n allPMSE_gam <- rbind(allPMSE_gam, temprmse_gam)\n allPMSE_arima <- rbind(allPMSE_arima, temprmse_arima)\n allPMSE_linextrap <- rbind(allPMSE_linextrap, temprmse_linextrap)\n\n # bias and variance\n meanPMSE_gam <- c(meanPMSE_gam, mean(temprmse_gam))\n meanPMSE_linextrap <- c(meanPMSE_linextrap, mean(temprmse_linextrap))\n meanPMSE_arima <- c(meanPMSE_arima, mean(temprmse_arima))\n\n # print(meanPMSE_gam)\n # print(meanPMSE_arima)\n # print(meanPMSE_linextrap)\n }\n\n ## stop parallel\n sfStop()\n tend <- Sys.time()\n message(\"Fitting completed!\")\n\n colnames(grid) <- c(\"U\", \"V\", \"W\")\n performance <- data.frame(grid,\n meanPMSE_gam = meanPMSE_gam, meanPMSE_linextrap = meanPMSE_linextrap, meanPMSE_arima = meanPMSE_arima,\n mean_diffunpenPMSE_gam = meanPMSE_gam - meanPMSE_gam[1], mean_diffunpenPMSE_linextrap = meanPMSE_linextrap - meanPMSE_linextrap[1],\n mean_diffunpenPMSE_arima = meanPMSE_arima - meanPMSE_arima[1]\n )\n performance$sd_diffunpenPMSE_gam <- apply(t(t(allPMSE_gam) - allPMSE_gam[1, ]), 1, sd)\n performance$sd_diffunpenPMSE_arima <- apply(t(t(allPMSE_arima) - allPMSE_arima[1, ]), 1, sd)\n performance$sd_diffunpenPMSE_linextrap <- apply(t(t(allPMSE_linextrap) - allPMSE_linextrap[1, ]), 1, sd)\n\n out <- list(\n best_parameters_gam = grid[which.min(performance$meanPMSE_gam), ],\n best_parameters_linextrap = grid[which.min(performance$meanPMSE_linextrap), ],\n best_parameters_arima = grid[which.min(performance$meanPMSE_arima), ],\n performance = performance, init = init, time = tend - tstart\n )\n return(out)\n}", "meta": {"hexsha": "4f43c4e4b0d122c4e12a530792c5f81aa34e078a", "size": 6509, "ext": "r", "lang": "R", "max_stars_repo_path": "APTD-CV.r", "max_stars_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_stars_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "APTD-CV.r", "max_issues_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_issues_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APTD-CV.r", "max_forks_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_forks_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4585987261, "max_line_length": 149, "alphanum_fraction": 0.5884160393, "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4671266161898022}} {"text": "seasonalize <- function(arr, maxes = TRUE){\n # this function finds the max or min by climatological season (DJF, MAM, JJA, SON), assuming a 3-d array with month as the second dimension\n\n if(maxes) FUN <- max else FUN <- min\n \n nSeas <- 4\n seasonIndices <- list(DJF = c(1, 2, 12), MAM = 3:5, JJA = 6:8, SON = 9:11)\n dec <- 12\n nYr <- dim(arr)[1]\n \n arr[2:nYr, dec, ] <- arr[1:(nYr - 1), dec, ]\n arr[1, dec, ] <- NA\n\n tmp <- array(NA, c(nYr, nSeas, dim(arr)[3]))\n for(j in 1:nSeas){\n tmp[ , j, ] <- apply(arr[, seasonIndices[[j]], , drop = FALSE], c(1, 3), FUN, na.rm = FALSE)\n }\n return(tmp)\n}\n\nis.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol\n\nvalidateIndices <- function(model, nVar){\n if(min(model) < 0 | max(model) > nVar)\n return(FALSE)\n if(sum(is.wholenumber(model)) < length(model))\n return(FALSE)\n if(length(unique(model)) != length(model))\n return(FALSE)\n return(TRUE)\n}\n\nnormalize <- function(vec, shift = NULL, lower = NULL, upper = NULL){\n if(is.null(shift))\n shift <- mean(vec)\n if(is.null(lower))\n lower <- min(vec)\n if(is.null(upper))\n upper <- max(vec)\n (vec - shift) / (upper - lower)\n}\n\nreturnValue <- function(fit, rvInterval = 20, rvCovariates = NULL){\n\n if(!(class(fit) == 'gev.fit' | class(fit) == 'pp.fit'))\n stop('Function only handles gev.fit and pp.fit objects')\n\n# if(!identical(fit$link[[1]], identity) || !identical(shlink, identity) || == 'gev.fit' | class(fit) == 'pp.fit'))\n # stop('Function only handles gev.fit and pp.fit objects')\n \n links = substring(fit$link, 3, nchar(fit$link) - 1)\n links = unlist(strsplit(links, \", \"))\n\n if(links[1] != \"identity\" || links[3] != \"identity\" || !(links[2] %in% c(\"identity\", \"exp\")))\n stop(\"Function only computes return values for identity link functions for location and shape and for identity or exponential link functions for scale\")\n\n locationIndices <- 1:(length(fit$model[[1]]) + 1)\n pos = 1 + max(locationIndices)\n scaleIndices <- pos:(pos+length(fit$model[[2]]))\n pos = 1 + max(scaleIndices)\n shapeIndices <- pos:(pos+length(fit$model[[3]]))\n \n location <- eval(as.name(links[1]))(sum(c(1, rvCovariates[fit$model[[1]]]) * fit$mle[locationIndices]))\n scale <- eval(as.name(links[2]))(sum(c(1, rvCovariates[fit$model[[2]]]) * fit$mle[scaleIndices]))\n shape <- eval(as.name(links[3]))(sum(c(1, rvCovariates[fit$model[[3]]]) * fit$mle[shapeIndices]))\n\n yp <- -log(1 - 1/rvInterval)\n ypshape <- yp^(-shape)\n zp <- location - (scale/shape) * (1 - ypshape)\n\n if(links[2] == \"identity\"){\n scaleTerm = 1\n } else{ # exponential link\n scaleTerm = scale\n }\n \n grad <- c(c(1, rvCovariates[fit$model[[1]]]),\n -(scaleTerm/shape) * (1 - ypshape) * c(1, rvCovariates[fit$model[[2]]]),\n ((scale/shape^2) * (1 - ypshape) - (scale/shape) * ypshape * log(yp)) * c(1, rvCovariates[fit$model[[3]]]))\n\n se <- sqrt(t(grad) %*% fit$cov %*% grad)\n \n return(c(zp, se))\n}\n\n# difference in return values for single time series, different covariate values\nreturnValueDiff <- function(fit, rvInterval = 20, rvCovariates = NULL){\n if(!(class(fit) == 'gev.fit' || class(fit) == 'pp.fit'))\n stop('Function only handles gev.fit and pp.fit objects')\n \n links = substring(fit$link, 3, nchar(fit$link) - 1)\n links = unlist(strsplit(links, \", \"))\n \n if(links[1] != \"identity\" || links[3] != \"identity\" || !(links[2] %in% c(\"identity\", \"exp\")))\n stop(\"Function only computes return value differences for identity link functions for location and shape and for identity or exponential link functions for scale\")\n\n locationIndices <- 1:(length(fit$model[[1]]) + 1)\n pos = 1 + max(locationIndices)\n scaleIndices <- pos:(pos+length(fit$model[[2]]))\n pos = 1 + max(scaleIndices)\n shapeIndices <- pos:(pos+length(fit$model[[3]]))\n \n location <- eval(as.name(links[1]))(cbind(rep(1, 2), rvCovariates[ , fit$model[[1]]]) %*% fit$mle[locationIndices])\n scale <- eval(as.name(links[2]))(cbind(rep(1, 2), rvCovariates[ , fit$model[[2]]]) %*% fit$mle[scaleIndices])\n shape <- eval(as.name(links[3]))(cbind(rep(1, 2), rvCovariates[ , fit$model[[3]]]) %*% fit$mle[shapeIndices])\n \n yp <- -log(1 - 1/rvInterval)\n ypshape <- yp^(-shape)\n zpDiff <- diff(location - (scale/shape) * (1 - ypshape))\n\n if(links[2] == \"identity\"){\n scaleTerm = rep(1, 2)\n } else{ # exponential link\n scaleTerm = rep(scale, 2)\n }\n\n grad <- c(0, rvCovariates[2, fit$model[[1]]] - rvCovariates[1, fit$model[[1]]],\n -(scaleTerm[2]/shape[2]) * (1 - ypshape[2]) * c(1, rvCovariates[2, fit$model[[2]]]) +\n (scaleTerm[1]/shape[1]) * (1 - ypshape[1]) * c(1, rvCovariates[1, fit$model[[2]]]),\n ((scale[2]/shape[2]^2) * (1 - ypshape[2]) - (scale[2]/shape[2]) * ypshape[2] * log(yp) ) * c(1, rvCovariates[2, fit$model[[3]]]) -\n ((scale[1]/shape[1]^2) * (1 - ypshape[1]) - (scale[1]/shape[1]) * ypshape[1] * log(yp) ) * c(1, rvCovariates[1, fit$model[[3]]]))\n \n se <- sqrt(t(grad) %*% fit$cov %*% grad)\n \n return(c(zpDiff, se))\n}\n\nremoveRuns <- function(vals, days, maxes = TRUE){\n n <- length(vals)\n if(maxes) FUN <- max else FUN <- min\n if(n > 1){\n checkBack <- c(TRUE, days[2:n] - days[1:(n-1)] != 1)\n checkFwd <- c(days[1:(n-1)] - days[2:n] == -1, FALSE)\n seqStarts <- which(checkBack & checkFwd)\n for(start in seqStarts){\n pos = start\n while(pos < n && days[pos + 1] - days[start] == pos + 1 - start) pos <- pos + 1\n tmp <- vals[start:pos]\n jitter = rnorm(length(tmp), 0, 1e-12) # amounts to randomly choosing a max when values are equal\n tmp[tmp + jitter < FUN(tmp + jitter)] <- NA\n vals[start:pos] <- tmp\n }\n }\n return(vals)\n}\n\n# alternative: function for removing multiple exceedances in blockLen-day windows; surprisingly this is much slower\nwithinBlockScreenAlt <- function(vals, days, blockLen = 10, maxes = TRUE){\n n <- length(vals)\n if(n > 1){\n jitter = rnorm(n, 0, 1e-12) # randomly choose which value in block to retain when there are ties\n if(maxes) FUN <- max else FUN <- min\n block <- data.frame(block = cut(days, seq(0, max(days)+blockLen, by = blockLen)))\n tmp <- tapply(vals + jitter, block, FUN)\n blockExtrema <- data.frame(block = names(tmp), extrema = tmp)\n comparators = merge(block, blockExtrema, all.x = TRUE, all.y = FALSE)\n vals[vals + jitter < comparators$extrema] = NA\n }\n return(vals)\n}\n\nwithinBlockScreen <- function(vals, days, blockLen = 10, maxes = TRUE){\n if(!identical(days, sort(days)))\n stop('data must be sorted by days in ascending order')\n n <- length(vals)\n if(n > 1){\n i <- 1\n while(i < length(vals)){\n start <- i\n while( (days[i+1]-1) %/% blockLen == (days[i]-1) %/% blockLen && i < length(vals)){\n i <- i + 1\n }\n if(i > start){\n jitter = rnorm(i - start + 1, 0, 1e-12)\n tmp = vals[start:i]\n tmp[tmp + jitter < max(tmp + jitter)] = NA\n vals[start:i] = tmp\n }\n i = i + 1\n }\n }\n return(vals)\n}\n\nlik.ratio.test = function(fit1, fit2){\n if(!(class(fit1) %in% c(\"gev.fit\", \"pp.fit\")) ||\n !(class(fit2) %in% c(\"gev.fit\", \"pp.fit\")))\n stop(\"Fit objects must be of class 'gev.fit' or 'pp.fit'\")\n dev = 2 * abs(fit1$nllh - fit2$nllh)\n df = abs(length(unlist(fit1$model)) - length(unlist(fit2$model)))\n return(list(df = df, negLogLik = c(fit1$nllh, fit2$nllh), chisq = dev, p = 1 - pchisq(dev, df)))\n}\n\n\n\n\n\n#linkManip = function(mulink, siglink, shlink)\n# return(deparse(substitute(c(mulink, siglink, shlink))))\n", "meta": {"hexsha": "60b0cf68adb6ef5e8c0f44e1b827d99200321b3d", "size": 7494, "ext": "r", "lang": "R", "max_stars_repo_path": "operators/ExtremeValueAnalysis/r_src/auxil.r", "max_stars_repo_name": "ahota/visit_ospray", "max_stars_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "operators/ExtremeValueAnalysis/r_src/auxil.r", "max_issues_repo_name": "ahota/visit_ospray", "max_issues_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "operators/ExtremeValueAnalysis/r_src/auxil.r", "max_forks_repo_name": "ahota/visit_ospray", "max_forks_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.47, "max_line_length": 167, "alphanum_fraction": 0.6051507873, "num_tokens": 2513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46697962320081565}} {"text": "## Functions for ecological model\n\ndate2doy <- function(yr, mo, dy){\n yr <- as.character(yr)\n mo <- as.character(mo)\n dy <- as.character(dy)\n \n dt <- paste(c(yr,'-',mo,'-',dy), collapse='')\n doy <- strftime(dt, format='%j')\n return(doy)\n}\n\ndefine_global_variables <- function(){\n \n # Site constants\n PAR2SWIR <<- 0.43 # PAR to shortwave radiation ratio\n STD_MERAD <<- -75.0 # Time zone longitude\n LATI <<- 35.9736 # Site latitude (CHANGE TO MMS)\n LONGI <<- -79.1004 # Site longitude (CHANGE TO MMS)\n hs <<- 20.0 # Screen height\n h2 <<- 16.2 # Default canopy height\n PA <<- 101325.0 # Air pressure in Pa\n CP <<- 1010.0 # Specific heat of air (J kg-1 K-1)\n CA <<- 410.0 # Atmospheric CO2 concentration (ppm)\n \n # Physical constants\n SO <<- 1367.0 # Solar constant (W m-2)\n \n # Leaf constants\n alpha_par <<- 0.80\n alpha_nir <<- 0.20\n rho_s <<- 0.10\n x <<- 1.0 # Leaf angle distribution parameter\n omega <<- 1.0 # Clumping index\n m <<- 8.0 # Ball-Berry model slope\n g1_blayer <<- 0.005 # Leaf boundary layer conductance in m/s\n g0 <<- 0.010 # Parameter in Leuning's gs function in mol m-2 s-1\n \n # Soil constants\n Ksat <<- 0.6 # Saturated conductance (m day-1)\n wilting_p <<- 0.08 # Wilting poit soil water content (unitless)\n porosity <<- 0.54 # Porosity at depth zero (unitless)\n p1 <<- 0.478 # Air entry pressure in meters of water\n p2 <<- 0.186 # Pore size index (unitless)\n p_0 <<- 4000.0 # Porosity decay in m-1\n m_z <<- 0.24 # Saturated conductivity decay parameter (in m-1)\n soil_depth <<- 0.325 # Soil depth in rooting zone\n \n}\n\ncanopy_aerodynamic_resistance <- function(u_h, h, h_o){\n h_u <- 2.0\n cn <- 0.002 # wind attenuation coefficient\n \n # Compute zero plane displacement\n d_o <- 0.7 * h_o\n \n # Compute the roughness length\n zo_o <- 0.1 * h_o\n u_o <- compute_toc_wind(u_h, h, h_o)\n u_m <- (u_o * exp(cn * (0.5 * h_o)/h_o - 1))\n u_m <- sapply(u_m, function(x) max(x,0))\n \n if(h 0){\n Ksat_average <- Ksat_decay* Ksat *(1.0-exp(-1.0*depth_s/Ksat_decay))\n } else Ksat_average <- Ksat\n \n S <- max(0,min(Sr,1))\n \n # Plug everything into the equation for max infiltration\n potential_exfiltration <- S ^ ((1.0 / (2.0*pore_size_index))+2.0) * \n sqrt((8.0 * porosity_average * \n Ksat_average * psi_air_entry) / \n (3.0 * (1.0 + 3.0 * pore_size_index) * \n (1.0 + 4.0 * pore_size_index)))\n \n potential_exfiltration = min(0.001, potential_exfiltration)\n pe_wm2 = potential_exfiltration * 1e6 * 597.3 * 4.18 / (24.0*3600.0)\n return(pe_wm2)\n}\n\ncompute_psn_parameters <- function(t, Kb, L_sunlit, L_shaded){\n # Local static variables\n Kc25 <- 404.0 # (ubar) MM const carboxylase, 25 deg C\n q10Kc <- 2.1 # (DIM) Q_10 for kc\n Ko25 <- 248.0 # (mbar) MM const oxygenase, 25 deg C\n q10Ko <- 1.2 # (DIM) Q_10 for ko\n act25 <- 3.6 # (umol/mgRubisco/min) Rubisco activity\n q10act <- 2.4 # (DIM) Q_10 for Rubisco activity\n Kn <- 0.52 # extinction coefficient for Nitrogen distribution\n cica <- 0.67 # Ci to Ca ratio \n alpha <- 0.10 # quantum yield efficiency\n \n L <- L_sunlit + L_shaded\n \n # Calculate atmospheric O2 in Pa, assumes 21% O2 by volume\n O2 <- 0.21 * PA\n \n # Correct kinetic constants for temperature, and do unit conversions\n Ko <- Ko25 * q10Ko^((t-25.0)/10.0)\n Ko <- Ko * 100.0 # mbar --> Pa\n \n Kc <- Kc25 * (1.8*q10Kc)^((t-25.0)/10.0) / q10Kc\n Kc[t>15.0] <- Kc25 * q10Kc^((t[t>15.0]-25.0)/10.0)\n act <- act25 * (1.8*q10act)^((t-25.0)/10.0) / q10act\n act[t>15.0] <- act25 * q10act^((t[t>15.0]-25.0)/10.0)\n \n Kc <- Kc * 0.10 # ubar --> Pa\n act <- act * 1e6/60.0 # umol/mg/min --> umol/kg/s\n \n # Calculate gamma (Pa), assumes Vomax/Vcmax = 0.21\n gamma <- 0.5 * 0.21 * Kc * O2 / Ko\n \n # Calculate Vmax from leaf nitrogen data and Rubisco activity\n Vmax25 <- 59.0 # umol/m2leaf/s at the top of the canopy (Lai et al, 2002, PCE, 25:1095-1119)\n \n Vmax25_canopy <- L * Vmax25 * (1.0 - exp(-L*Kn)) / (Kn*L)\n Vmax25_sunlit <- L * Vmax25 * (1.0 - exp(-Kn-Kb*L)) / (Kn+Kb*L)\n Vmax25_shaded <- (Vmax25_canopy - Vmax25_sunlit) / L_shaded\n Vmax25_sunlit <- Vmax25_sunlit / L_sunlit\n \n Vmax_sunlit <- Vmax25_sunlit * exp(0.051*(t-25.0))/(1.0+exp(0.205*(t-41.0)))\n Vmax_shaded <- Vmax25_shaded * exp(0.051*(t-25.0))/(1.0+exp(0.205*(t-41.0)))\n \n Rd_sunlit <- 0.015 * Vmax_sunlit\n Rd_shaded <- 0.015 * Vmax_shaded\n \n ppe <- 1.0 / (alpha*(4.0*cica*CA+2.0*gamma)/(cica*CA-gamma))\n \n psn_para <- data.frame(gamma=gamma,\n Vmax_sunlit=Vmax_sunlit,\n Vmax_shaded=Vmax_shaded,\n Ko=Ko,\n Kc=Kc,\n O2=O2,\n Rd_sunlit=Rd_sunlit,\n Rd_shaded=Rd_shaded,\n ppe=ppe)\n \n return(psn_para)\n}\n\ncompute_soil_surface_resistance <- function(theta){\n gs <- 1.0 / (-83000.0 * theta + 16100.0)\n gs[theta > 0.185] <- 0.001429\n \n rs <- 1.0 / gs\n return(rs)\n}\n\ncompute_sun_angles <- function(lat, lon, yr, mo, dt, hr, mi){\n solar_time <- hr + mi/60.0 + (lon-STD_MERAD)/15.0\n hangle <- (12.0-solar_time)*15.0*pi/180.0\n \n # Compute Julian day\n jday <- as.numeric(mapply(date2doy, yr=yr, mo=mo, dy=dt))\n \n # Sun declination angle\n declangle <- 23.45 * sin(2.0*pi*(284.0+jday)/365.0) * pi/180.0\n \n # sin(sun_elevation)\n sinh <- sin(lat*pi/180.0)*sin(declangle)+cos(lat*pi/180.0)*cos(declangle)*cos(hangle)\n \n zenith <- acos(sinh)\n azimuth <- asin(cos(declangle)*sin(hangle)/cos(pi/2.0-zenith))\n \n out <- data.frame(jday = jday, zenith = zenith, sun_decl = declangle, hourangle = hangle)\n return(out)\n}\n\ncompute_toc_down_rad <- function(par, sun_zenith, jday){\n tau_t <- (par/4.55)*(1.0/PAR2SWIR)/(SO*(1.0+0.033*cos(2.0*pi*(jday-10.0)/365.0)))\n \n # Constants from Weiss & Norman 1985, Eq. 12\n A <- 0.9\n B <- 0.7\n C <- 0.88\n D <- 0.68\n \n # Cosine of the solar zenith angle\n cos_theta <- cos(sun_zenith)\n cos_theta[cos_theta<0] <- 0 \n \n # Potential visible (V) and NIR (N) radiation at top of atmosphere\n S_V <- 0.473*1367.0*(1.0+0.033*cos(2.0*pi*(jday-10)/365))\n S_N <- 0.527*1367.0*(1.0+0.033*cos(2.0*pi*(jday-10)/365))\n \n # Potential direct visible on a horizontal surface\n R_DV <- S_V*exp(-0.185/cos_theta)*cos_theta\n \n # Potential diffuse visible on a horizontal surface\n R_dV <- 0.4*(S_V-R_DV)*cos_theta\n \n # Total potential visible radiation on a horizontal surface\n R_V <- R_DV + R_dV\n \n # Absorbed NIR by atmospheric water vapor\n cos_theta_noZero <- cos_theta\n cos_theta_noZero[cos_theta==0] <- 0.0000000000000001 # avoid division by zero\n R_aN <- S_N * 10^(-1.195+0.4459*log10(1.0/cos_theta_noZero)-0.0345*(log10(1.0/cos_theta_noZero)^2.0))\n \n # Potential direct NIR on a horizontal surface\n R_DN <- (S_N*exp(-0.06/cos_theta)-R_aN)*cos_theta\n R_DN[R_DN<0] <- 0 # Can't have negative direct radiation\n \n # Potetial diffuse NIR on a horizontal surface\n R_dN <- 0.6*(S_N-R_DN-R_aN)*cos_theta\n \n # Total potential NIR on a horizontal surface\n R_N <- R_DN + R_dN\n \n # Ratio of actual total radiation to potential total radiation on the ground\n RATIO <- (par/4.55)*(1.0/PAR2SWIR) / (R_V+R_N)\n \n # Actual fraction of direct visible radiation\n RATIO[RATIO>A] <- A\n f_DV <- (R_DV/(R_V*0.928)) * (1.0 - ((A-RATIO)/B) ^ (2.0/3.0))\n f_DV[R_V==0] <- 0\n \n # Actual fraction of direct NIR radiation\n RATIO[RATIO>C] <- C\n f_DN <- (R_DN/R_N) * (1.0 - ((C-RATIO)/D) ^ (2.0/3.0))\n f_DN[R_N==0] <- 0\n \n rad <- data.frame(par_D = f_DV * par/4.55,\n par_d = par/4.55 - f_DV * par/4.55,\n nir_D = f_DN * (par/4.55) * ((1-PAR2SWIR)/PAR2SWIR),\n nir_d = (par/4.55) * ((1-PAR2SWIR)/PAR2SWIR) - f_DN * (par/4.55) * ((1-PAR2SWIR)/PAR2SWIR),\n cloud = max(1.0-tau_t/0.7, 0))\n \n return(rad)\n \n}\n\ncompute_toc_wind <- function(u_h, h, z){\n # Returns wind speed at height z in stratum\n # from RHESSys, which was from BGC 4.11.\n \n # Compute winds\n d_o <- 0.63 * z\n z_o <- 0.1 * z\n \n # Wind speed at toc log decrease from screen height to toc\n u_z <- u_h * log((z-d_o)/z_o) / log((h-d_o)/z_o)\n return(u_z)\n}\n\npenman_monteith <- function(Tair, Rnet, gs, ga, vpda){\n # Calculate forest canopy ET using penman-monteith equation\n \n # dt: delta t, a small temperature increase\n # rho: air density (kg/m2)\n # lhvap: latent heat of water (J/kg)\n # s: Slope of saturated vapor pressure - temp\n # es: Saturated vapor pressure at t2 in Pa\n # ET: Evapotranspiration in W/m2\n # gamma: Psychrometric constant\n # z0: Surface roughness\n # d0: Zero plane displacement\n \n # Density of air (rho) as a f'n of air temp\n rho <- 1.292 - (0.00428*Tair)\n\n # Latent heat of vaporization as a f'n of air temp\n lhvap = 2.5023e6 - 2430.54*Tair\n \n # Saturation vapor pressures at Tair (Pa)\n es <- 610.7 * exp(17.38 * Tair / ( 239.0 + Tair))\n \n # Slope of es-T curve at Tair (Pa/deg C) (from Campbell & Norman 1998)\n s <- 17.38*239.0*es / (239.0+Tair)^2\n \n # Calculate gamma\n gamma <- CP * PA / ( 0.622*lhvap )\n \n # Evaporation in W/m2\n ET <- ((s*Rnet) + (rho*CP*vpda*ga)) / (gamma*(1.0 + ga/gs) +s)\n}\n\n", "meta": {"hexsha": "4b36b44c5d83ad34c921a14111cfa7c4a9a68de2", "size": 14608, "ext": "r", "lang": "R", "max_stars_repo_path": "eco_model.r", "max_stars_repo_name": "mpdannenberg/geog-4470", "max_stars_repo_head_hexsha": "93bcc6a42ac52ec1d0c39cae274926994dfabefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eco_model.r", "max_issues_repo_name": "mpdannenberg/geog-4470", "max_issues_repo_head_hexsha": "93bcc6a42ac52ec1d0c39cae274926994dfabefa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eco_model.r", "max_forks_repo_name": "mpdannenberg/geog-4470", "max_forks_repo_head_hexsha": "93bcc6a42ac52ec1d0c39cae274926994dfabefa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0497737557, "max_line_length": 126, "alphanum_fraction": 0.5985761227, "num_tokens": 5617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4668874101467932}} {"text": "#' convert_P.r\n#' For phosphorus, but general two step linear converter.\n#' Lets say you want to convert a value, A, to a different, value, C.\n#' You have data relating A to B, and B to C.\n#' This will take those datasets, and a vector of A values you want to convert.\n#' It will return a list, where \"mean\" is the mean predicted value of c, given a, and \"sd\" is the predictions standard deviation.\n#'\n#' @param to_convert vector of values to convert from a->c\n#' @param d1 dataframe that relates a to b, a in the first column, b in the second.\n#' @param d2 dataframe that relates b to c, b in the first column, c in the second.\n#' @param n.sim number of simulations to generate mean and sd from. 1000 is default and fine.\n#'\n#' @return returns a list where mean is the mean predicted value of c, given a, and sd is the predictions standard deviation.\n#' @export\n#'\n#' @examples\n#' #phosphorus data converter.\n#' a <- runif(100, 0, 1)\n#' b <- a*1.2 + rnorm(length(a), sd = 0.1)\n#' c <- b*0.9 + rnorm(length(b), sd = 0.1)\n#' d1 <- data.frame(a,b)\n#' d2 <- data.frame(b,c)\n#' to_convert <- runif(25, 0, 1)\n#' convert_P(to_convert,d1,d2)\nconvert_P <- function(to_convert,d1,d2,n.sim=1000, log10_flip = F){\n #setup predictors for JAGS.----\n y1 <- d1[,2]\n x1 <- d1[,1]\n x1 <- cbind(rep(1,length(x1)),x1)\n y2 <- d2[,2]\n x2 <- d2[,1]\n x2 <- cbind(rep(1,length(x2)),x2)\n \n #JAGS data object.\n jd <- list(N = length(y1), N.pred = ncol(x1),\n y1=y1, y2=y2, x1=x1, x2=x2)\n \n #Define JAGS model.----\n jags.model = \"\n model{\n #covariate parameter priors.\n for(k in 1:N.pred){\n m1[k] ~ dnorm(0,0.001)\n m2[k] ~ dnorm(0,0.001)\n }\n #data model precision priors.\n tau1 <- pow(sigma1, -2)\n sigma1 ~ dunif(0, 100)\n tau2 <- pow(sigma2, -2)\n sigma2 ~ dunif(0, 100)\n \n #regression models.\n for(i in 1:N){\n mu1[i] <- inprod(x1[i,], m1)\n mu2[i] <- inprod(x2[i,], m2)\n y1[i] ~ dnorm(mu1[i], tau1)\n y2[i] ~ dnorm(mu2[i], tau2)\n }\n } #end JAGS model loop.\n \"\n \n #Fit JAGS model.----\n cat('Fitting JAGS model...\\n')\n suppressWarnings(\n jags.out <- run.jags(jags.model,\n data=jd,\n n.chains=3,\n adapt = 500,\n burnin = 1000,\n sample = 1000,\n monitor=c('m1','m2'),\n method = 'rjags')\n )\n jout <- summary(jags.out)\n \n #grab mcmc of model parameters.\n mcmc <- do.call(rbind, jags.out$mcmc)\n \n #convert to_convert data from a to c, propagating uncertainty!----\n convert.out <- list()\n for(i in 1:n.sim){\n par <- mcmc[sample(nrow(mcmc),1),]\n b <- par[2]*to_convert + par[1]\n c <- par[4]*b + par[3]\n convert.out[[i]] <- c\n }\n \n #wrap up output to return.----\n convert.out <- do.call(cbind, convert.out)\n #log10 variable?\n suppressWarnings(\n if(log10_flip == T){\n convert.out <- log10(convert.out)\n }\n )\n mu <- rowMeans(convert.out, na.rm = T)\n mu.sd <- apply(convert.out, 1, sd, na.rm = T)\n output <- list(mu, mu.sd)\n names(output) <- c('mean','sd')\n \n #return output, end function.----\n return(output)\n} #end function.\n", "meta": {"hexsha": "8a06bd532480035d479e1cf6efac9165e04f88dd", "size": 3181, "ext": "r", "lang": "R", "max_stars_repo_path": "NEFI_functions/convert_P.r", "max_stars_repo_name": "colinaverill/NEFI_microbe", "max_stars_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-13T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T17:13:54.000Z", "max_issues_repo_path": "NEFI_functions/convert_P.r", "max_issues_repo_name": "colinaverill/NEFI_microbe", "max_issues_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NEFI_functions/convert_P.r", "max_forks_repo_name": "colinaverill/NEFI_microbe", "max_forks_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-21T20:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T16:09:44.000Z", "avg_line_length": 30.5865384615, "max_line_length": 135, "alphanum_fraction": 0.5771769884, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46680585083232656}} {"text": "################################################################################\n# Part of the R/EpiILM package\n#\n# AUTHORS:\n# Vineetha Warriyar. K. V. ,\n# Waleed Almutiry , and\n# Rob Deardon \n#\n#\n# Algorithm based on:\n# Deardon R, Brooks, S. P., Grenfell, B. T., Keeling, M. J., Tildesley,\n# M. J., Savill, N. J., Shaw, D. J., Woolhouse, M. E. (2010).\n# Inference for individual level models of infectious diseases in large\n# populations. Statistica Sinica, 20, 239-261.\n#\n#\n# Free software under the terms of the GNU General Public License, version 2,\n# a copy of which is available at http://www.r-project.org/Licenses/.\n################################################################################\n\nepilike <- function(object, tmin = NULL, tmax, sus.par, trans.par = NULL,\n beta = NULL, spark = NULL, Sformula = NULL, Tformula = NULL) {\n\nif (!is(object, \"epidata\")) {\n stop(\"The object must be in a class of \\\"epidata\\\"\", call. = FALSE)\n} else {\n\n # Error checks for input arguments\n if (any(is.null(object$type) | !(object$type %in% c(\"SI\", \"SIR\"))) == TRUE) {\n stop(\"epilike: Specify type as \\\"SI\\\" or \\\"SIR\\\" \", call. = FALSE)\n }\n\n ns <- length(sus.par)\n if (!is.null(trans.par)){\n nt <- length(trans.par)\n flag.trans <- 1\n phi <- trans.par\n } else if (is.null(trans.par)) {\n nt <- 1\n flag.trans <- 0\n phi <- 1\n trans.par <- 1\n }\n\n if (!is.vector(object$inftime)) {\n stop('epilike: inftime is not a vector')\n }\n n <- length(object$inftime)\n\n if (all(is.null(object$contact) & is.null(object$XYcoordinates)) == TRUE) {\n stop('epilike: Specify contact network or x, y coordinates')\n }\n\n if (all(is.null(object$remtime) & object$type == \"SIR\") == TRUE) {\n stop(' epilike: Specify removal times')\n }\n\n if(object$type == \"SIR\") {\n infperiod <- object$remtime - object$inftime\n }\n\n if (is.null(tmin)) {\n tmin <- 1\n }\n if (is.null(spark)) {\n spark <- 0\n }\n\n if (is.null(object$contact)) {\n ni <- length(beta)\n if (is.null(beta)) {\n stop(\"epilike: A scalar value of the spatial parameter beta must be specified\", call. = FALSE)\n }\n if (ni != 1) {\n stop(\"epilike: The input of beta has more than one value while the considered distance-based ILM needs only one spatial parameter, beta.\", call. = FALSE)\n }\n } else {\n if (length(object$contact)/(n * n) == 1) {\n ni <- 1\n if (is.null(beta)) {\n beta <- 1\n } else {\n stop(\"epilike: As the model has only one contact network, The model does not need a network parameter beta, beta must be assigned to its default values = NULL\", call. = FALSE)\n }\n } else if (length(object$contact)/(n * n) > 1) {\n ni <- length(beta)\n if (is.null(beta)) {\n stop(\"epilike: A vector values of the network parameters beta must be specified\", call. = FALSE)\n }\n if (length(object$contact)/(n * n) != ni) {\n stop('epilike: Dimension of beta and the number of contact networks are not matching')\n }\n }\n network <- array(object$contact, c(n, n, ni))\n }\n\n # formula for susceptibility function\n \tif (!is.null(Sformula)) {\n \t\tcovmat.sus <- model.matrix(Sformula)\n\n \t\tif (all((ncol(covmat.sus) == length(all.vars(Sformula))) & (ns != length(all.vars(Sformula)))) == TRUE) {\n \t\t\tstop(\"epilike: Check Sformula (no intercept term) and the dimension of susceptibility parameters\", call. = FALSE)\n \t\t} else if (all((ncol(covmat.sus) > length(all.vars(Sformula))) & (ns != ncol(covmat.sus))) == TRUE) {\n \t\t\tstop(\"epilike: Check Sformula (intercept term) and the dimension of susceptibility parameters\", call. = FALSE)\n \t\t}\n \t} else {\n \t\tif (ns == 1) {\n \t\t\tcovmat.sus <- matrix(1.0, nrow = n, ncol = ns)\n \t\t}\n \t}\n\n # formula for transmissibility function\n if (flag.trans == 1) {\n if (is.null(Tformula)) {\n stop(\"epilike: Tformula is missing. It has to be specified with no intercept term and number of columns equal to the length of trans.par\", call. = FALSE)\n } else if (!is.null(Tformula)) {\n \t\tcovmat.trans <- model.matrix(Tformula)\n\n \t\tif (all((ncol(covmat.trans) == length(all.vars(Tformula))) & (nt != length(all.vars(Tformula)))) == TRUE) {\n \t\t\tstop(\"epilike: Check Tformula. It has to be with no intercept term and number of columns equal to the length of trans.par\", call. = FALSE)\n \t\t}\n }\n } else if (flag.trans == 0) {\n \tcovmat.trans <- matrix(1.0, nrow = n, ncol = nt)\n }\n\n# Calling fortran subroutines for Purely Spatial models : SI and SIR\n\n if (all((object$type == \"SI\") & is.null(object$contact)) == TRUE) {\n\n tmp1 <- .Fortran(\"like\",\n x = as.vector(object$XYcoordinates[,1], mode = \"double\"),\n y = as.vector(object$XYcoordinates[,2], mode = \"double\"),\n tau = as.vector(object$inftime, mode = \"integer\"),\n n = as.integer(n),\n tmin = as.integer(tmin),\n tmax = as.integer(tmax),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n alpha = as.vector(sus.par, mode = \"double\"),\n phi = as.vector(trans.par, mode = \"double\"),\n beta = as.vector(beta, mode = \"double\"),\n spark = as.double(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n val = as.double(0))\n\n } else if (all((object$type == \"SIR\") & is.null(object$contact)) == TRUE) {\n\n tmp1 <- .Fortran(\"likesir\",\n x = as.vector(object$XYcoordinates[,1], mode = \"double\"),\n y = as.vector(object$XYcoordinates[,2], mode = \"double\"),\n tau = as.vector(object$inftime, mode = \"integer\"),\n lambda = as.vector(infperiod, mode = \"integer\"),\n n = as.integer(n),\n tmin = as.integer(tmin),\n tmax = as.integer(tmax),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n alpha = as.vector(sus.par, mode = \"double\"),\n phi = as.vector(trans.par, mode = \"double\"),\n beta = as.vector(beta, mode = \"double\"),\n spark = as.double(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n val = as.double(0))\n\n } else if (all((object$type == \"SI\") & !is.null(object$contact)) == TRUE) {\n tmp1 <- .Fortran(\"likecon\",\n tau = as.vector(object$inftime, mode = \"integer\"),\n n = as.integer(n),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n tmin = as.integer(tmin),\n tmax = as.integer(tmax),\n alpha = as.vector(sus.par, mode = \"double\"),\n phi = as.vector(trans.par, mode = \"double\"),\n beta = as.vector(beta, mode = \"double\"),\n spark = as.double(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n network = as.vector(network),\n val = as.double(0))\n\n } else if (all((object$type == \"SIR\") & !is.null(object$contact)) == TRUE) {\n\n # Calling fortran subroutines for Contact network models: SI and SIR\n\n if (length(object$contact)/(n * n) != ni) {\n stop('epilike: Dimension of beta and the number of contact networks are not matching')\n }\n network <- array(object$contact, c(n, n, ni))\n\n tmp1 <- .Fortran(\"likeconsir\",\n tau = as.vector(object$inftime, mode = \"integer\"),\n lambda = as.vector(infperiod, mode = \"integer\"),\n n = as.integer(n),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n tmin = as.integer(tmin),\n tmax = as.integer(tmax),\n alpha = as.vector(sus.par, mode = \"double\"),\n phi = as.vector(trans.par, mode = \"double\"),\n beta = as.vector(beta, mode = \"double\"),\n spark = as.double(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n network = as.vector(network),\n val = as.double(0))\n }\n return(tmp1$val)\n}# End of function\n}\n", "meta": {"hexsha": "9bb3a2095d5e674a64a3a9dc8b92baa00bbcd7f7", "size": 9229, "ext": "r", "lang": "R", "max_stars_repo_path": "R/epilike.r", "max_stars_repo_name": "waleedalmutiry/EpiILM", "max_stars_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_stars_repo_licenses": ["Intel"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-30T03:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:15:25.000Z", "max_issues_repo_path": "R/epilike.r", "max_issues_repo_name": "waleedalmutiry/EpiILM", "max_issues_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/epilike.r", "max_forks_repo_name": "waleedalmutiry/EpiILM", "max_forks_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-01T20:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T17:44:20.000Z", "avg_line_length": 42.3348623853, "max_line_length": 183, "alphanum_fraction": 0.5264925777, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4667802099398684}} {"text": "#' Multivariate metropolis (i.e., metropolis within gibbs) sampler\n#' @param target Target function (returning log unnormalised posterior density);\n#' \tthis function should take the parameter as its first argument and a data list as its second\n#' @param initial Initial parameter vector\n#' @param data Data to pass to the target\n#' @param iter Number of iterations\n#' @param scale Scale vector for the proposal distributions, if NA, the algorithm will adaptively\n#' \t\tchoose scales\n#' @param n_adapt Number of iterations for adaptation, if needed\n#' @param ... Additional named parameters to pass to m_adapt\n#' \n#' @return A list, with three components: 'chain' is the markov chain, 'scale' \n#' \t\tis the scale parameter used, and 'accept' is the acceptance rate\nmetropolis = function(target, initial, data, iter = 1000, scale = NA, ...) {\n\n\t# check that the target distribution is defined at the initial value\n\tif(!is.finite(target(initial, data)))\n\t\tstop(\"Target distribution undefined at the initial value, choose better inits\")\n\n\t# adaptation, if needed\n\tif(any(is.na(scale)))\n\t\tscale = m_adapt(target, initial, data, ...)\n\n\n\t# do the sampling\n\tresult = m_sample(target, initial, data, scale, iter)\n\t\n\t# save the scale as well, because this allows resuming the chain\n\tresult$scale = scale\n\treturn(result)\n}\n\n\n#' Worker function to actually do the sampling\n#' @param target Target function (returning log unnormalised posterior density);\n#' \tthis function should take the parameter as its first argument and a data list as its second\n#' @param state Initial state vector (parameter values)\n#' @param data Data to pass to the target\n#' @param scale Scale for the proposal distributions\n#' @param iter Number of iterations\nm_sample = function(target, state, data, scale, iter) {\n\t# number of parameters\n\tk = length(state)\n\n\t# set up the markov chain\n\tchain = matrix(NA, nrow=iter, ncol=k)\n\tcolnames(chain) = names(state)\n\n\n\t# keep track of how many times we accept the proposals\n\t# the acceptance rate is an important diagnostic\n\taccept = rep(0, k)\n\n\n\tfor(i in 1:(iter)) {\n\t\t# for multivariate problems, it's helpful to keep track of the previous state as well\n\t\tprev_state = state\n\n\t\t# for each iteration, we need to randomize the order of parameters\n\t\tjj = sample(k)\n\n\t\t# loop over parameters one at a time\n\t\tfor(j in jj) {\n\t\t\t# propose a value and accept/reject, updating the current state with the new value\n\t\t\tstate = m_propose(state, scale, target, data, j)\n\t\t\tif(state[j] != prev_state[j]) {\n\t\t\t\t# if the value changed, that was an acceptance, increment accept variable\n\t\t\t\taccept[j] = accept[j] + 1\n\t\t\t}\n\t\t}\n\t\t# after we have proposed for each parameter, update the chain\n\t\tchain[i, ] = state\n\t}\n\treturn(list(chain = chain, accept = accept/iter))\n}\n\n\n\n#' Runs the adaptation phase of the metropolis sampler\n#' @param target Target function\n#' @param state Initial vector of k parameter values\n#' @param data Data to pass to the target\n#' @param chunk_size Number of iterations in each chunk before adapting\n#' @param max_chunk Maximum number of chunks before stopping adaptation\n#' \t\tor divide if the acceptance rate is too small; should be a vector of length k\n#' @param accept_range Target range of acceptance rates\n#' @param scale Optional initial guess for the scale vector, default 1\n#' @param scale_step Optional, how large the adaptation steps are, default 1.1\n#' @return Scale parameter after adaptation\nm_adapt = function(target, state, data, chunk_size = 100, max_chunk = 100, \n\t\t\taccept_range = c(0.2, 0.4), scale, scale_step) {\n\tk = length(state)\n\taccept_rate = rep(0, k)\n\tif(missing(scale))\n\t\tscale = rep(1, k)\n\tif(missing(scale_step)) {\n\t\tscale_step = rep(1.1, k)\n\t} else if(any(scale_step <= 1)) {\n\t\tstop(\"Scale step must be greater than one\")\n\t}\n\tnchunk = 0\n\twhile(nchunk < max_chunk & (any(accept_rate < min(accept_range)) | \n\t\t\t\t\t\t\tany(accept_rate > max(accept_range)))) {\n\t\tchunk = m_sample(target, state, data, scale, iter = chunk_size)\n\t\taccept_rate = chunk$accept\n\t\tstate = chunk$chain[nrow(chunk$chain),]\n\n\t\tfor(j in 1:k) {\n\t\t\tif(accept_rate[j] < min(accept_range)) {\n\t\t\t\tscale[j] = scale[j] / scale_step[j]\n\t\t\t} else if(accept_rate[j] > min(accept_range)) {\n\t\t\t\tscale[j] = scale[j] * scale_step[j]\n\t\t\t}\n\t\t}\n\t\tnchunk = nchunk + 1\n\t}\n\tcat(\"Finished adaptation after\", nchunk, \"chunks of\", chunk_size, \n\t\t\"iterations; acceptance rate:\\n\", \" \", accept_rate, \"\\n\")\n\treturn(scale)\n}\n\n\n\n#' Propose and select candidate values for the metropolis-hastings algorithm\n#' @param state Current state of the chain\n#' @param scale Scale of the proposal distribution\n#' @param target Target distribution density function\n#' @param data Data for the target distribution\n#' @param j Index of the state/scale vectors to propose, others will be held constant\n#' @return New value in the chain\nm_propose <- function(state, scale, target, data, j) {\n\t# choose a candidate value from the proposal distribution (rnorm)\n\tcandidate = state\n\tcandidate[j] = rnorm(1, state[j], scale[j])\n\n\t# compute the log posterior density at the current state and the candidate value\n\tld_cand = target(candidate, data)\n\tld_current = target(state, data)\n\n\t# compute the acceptance probability r, making sure the density is finite\n\t# r is the ratio of densities: (d_cand / d_current)\n\t# because r should be the exponential of the difference of log densities\n\tif(!is.finite(ld_cand)) {\n\t\tr = 0\n\t} else {\n\t\tr = exp(ld_cand - ld_current)\n\t}\n\n\t# now choose a value such that the chance of choosing d_cand is equal to r\n\t# the easiest way is to draw a random uniform number U on (0,1) and compare it to r\n\t# pr(U < r) = r (acceptance), pr(U >= r) = 1 - r (rejection)\n\t# could also use sample() to do this\n\tU = runif(1)\n\tif(U < r) {\n\t\tval = candidate\n\t} else {\n\t\tval = state\n\t}\n\treturn(val)\n}\n\n\n#' Computes a multivariate hpdi interval\n#' \n#' Assumes a unimodal posterior distribution\n#' @param samples A matrix of mcmc samples\n#' @param posterior A function returning the log unnormalized posterior density\n#' @param data The data used to compute the samples\n#' @param density The (minimum) probability density contained in the interval\nhpdi = function(samples, posterior, data, density = 0.9) {\n\n\t# compute the indices of all possible intervals\n\tn = nrow(samples)\n\tn_include = ceiling(density * n)\n\tlower = 1:(n - n_include)\n\tupper = lower + n_include\n\n\t# sort the samples by their posterior density\n\tdens = apply(samples, 1, posterior, data = data)\n\tind = order(dens)\n\tdens = dens[ind]\n\tsamples = samples[ind, ]\n\n\t# compute the width for each variable, then the area in the parameter dimension\n\tarea = mapply(function(l, u, samp) \n\t\tprod(apply(samp, 2, function(x) x[u[i]] - x[l[i]])), \n\t\tl = lower, u = upper, moreArgs = list(samp = samples))\n\n\ti = which.min(area)\n\tcbind(samples[lower[i], ], samples[upper[i], ])\n}\n", "meta": {"hexsha": "2d90d13673915021a8a1bd3d84b15ebfada673e8", "size": 6804, "ext": "r", "lang": "R", "max_stars_repo_path": "r/mh.r", "max_stars_repo_name": "mtalluto/vu_advanced_statistics", "max_stars_repo_head_hexsha": "a15820c6aa36cc8a109f2dd60c6424f616e15265", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r/mh.r", "max_issues_repo_name": "mtalluto/vu_advanced_statistics", "max_issues_repo_head_hexsha": "a15820c6aa36cc8a109f2dd60c6424f616e15265", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r/mh.r", "max_forks_repo_name": "mtalluto/vu_advanced_statistics", "max_forks_repo_head_hexsha": "a15820c6aa36cc8a109f2dd60c6424f616e15265", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4375, "max_line_length": 97, "alphanum_fraction": 0.7134038801, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.46599489204816236}} {"text": "## --------------------\n## --------------------\n## --------------------\n## This file contains some basic functions for implementing Adaptive Penalized Tensor Decomposition.\n## Most function are only suitable for three dimension tensor. For higher-order tensor, codes should be modified adaptively.\n## --------------------\n## --------------------\n## --------------------\n\n\n## --------------------\n## inital values\n## k @int \n## --------------------\ninits <- function(k) {\n return(t(as.matrix(rnorm(k, 0, 1))))\n}\n\n## --------------------\n## tensor product\n## --------------------\nproduct <- function(X, ind, u, v, w) {\n u <- t(as.matrix(u))\n v <- t(as.matrix(v))\n w <- t(as.matrix(w))\n\n\n if (length(ind) == 2) {\n lizt <- list(\"mat2\" = u, \"mat3\" = v)\n u <- ttl(X, lizt, ms = ind)\n return(as.vector(u@data))\n }\n\n lizt <- list(\"mat\" = u, \"mat2\" = v, \"mat3\" = w)\n u <- ttl(X, lizt, ms = ind)\n return(as.vector(u@data))\n}\n\n## --------------------\n## generate inital value for tensor decompostion if initial value is null.\n## --------------------\ngen_startvals <- function(num_factors, tnsr) {\n u <- matrix(inits(dim(tnsr)[1] * num_factors), nrow = num_factors)\n v <- matrix(inits(dim(tnsr)[2] * num_factors), nrow = num_factors)\n w <- matrix(inits(dim(tnsr)[3] * num_factors), nrow = num_factors)\n for (i in 1:num_factors) {\n u[i, ] <- u[i, ] / norm(as.matrix(u[i, ]), \"F\")\n }\n for (i in 1:num_factors) {\n v[i, ] <- v[i, ] / norm(as.matrix(v[i, ]), \"F\")\n }\n for (i in 1:num_factors) {\n w[i, ] <- w[i, ] / norm(as.matrix(w[i, ]), \"F\")\n }\n\n return(list(u = u, v = v, w = w))\n}\n\n## --------------------\n## generate mortality tensor.\n## --------------------\ngenerate_mortality_tensor <- function(x, log = TRUE, std = TRUE) {\n x <- as.data.table(x)\n len <- ncol(x)\n circu_m <- data.matrix(x[Cause == \"Circulatory system\"][, (len - 18):len])\n c_m <- data.matrix(x[Cause == \"Cancer\"][, (len - 18):len])\n r_m <- data.matrix(x[Cause == \"Respiratory system\"][, (len - 18):len])\n e_m <- data.matrix(x[Cause == \"External causes\"][, (len - 18):len])\n i_m <- data.matrix(x[Cause == \"Infectious and parasitic diseases\"][, (len - 18):len])\n o_m <- data.matrix(x[Cause == \"Others\"][, (len - 18):len])\n ## define the tensor and apply log transformation\n if (log) {\n m_tensor <- array(NA, dim = c(6, 19, (nrow(x) / 6)))\n m_tensor[1, , ] <- t(log(circu_m))\n m_tensor[2, , ] <- t(log(c_m))\n m_tensor[3, , ] <- t(log(r_m))\n m_tensor[4, , ] <- t(log(e_m))\n m_tensor[5, , ] <- t(log(i_m))\n m_tensor[6, , ] <- t(log(o_m))\n } else {\n m_tensor <- array(NA, dim = c(6, 19, (nrow(x) / 6)))\n m_tensor[1, , ] <- t(circu_m)\n m_tensor[2, , ] <- t(c_m)\n m_tensor[3, , ] <- t(r_m)\n m_tensor[4, , ] <- t(e_m)\n m_tensor[5, , ] <- t(i_m)\n m_tensor[6, , ] <- t(o_m)\n }\n ###\n if (std) {\n tensor1 <- (m_tensor - array(mean(m_tensor), dim = dim(m_tensor))) / sd(m_tensor)\n return(as.tensor(tensor1))\n } else {\n tensor1 <- m_tensor\n return(as.tensor(tensor1))\n }\n}", "meta": {"hexsha": "c12c87b8de739aadb2a57703836673101b5b3daa", "size": 3187, "ext": "r", "lang": "R", "max_stars_repo_path": "Basic.r", "max_stars_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_stars_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basic.r", "max_issues_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_issues_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basic.r", "max_forks_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_forks_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8556701031, "max_line_length": 124, "alphanum_fraction": 0.4841543772, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4658969779216003}} {"text": "holes_liu_dlh <- function(space, data, sidesmall, reorder='yes') {\r\n ## Finds MHR (maximal empty hyper-rectangle) in a defined space\r\n ## Inputs should potentially be transposed and scaled if it is desired that:\r\n ## (1) an extent at a low value is equal to an extent at a high value\r\n ## (e.g., pressure = 200, 400, 800, 1600 should be input as\r\n ## log(pressure) if holes at 200 and 1600 should be considered\r\n ## the same distance from 400 and 800, respectively)\r\n ## (2) an extent in 1 parameter is considered equal to the\r\n ## same extent in another parameter (e.g., scale from 0 to 1)\r\n ##\r\n ## Input: data = dataframe containing datapoints\r\n ## format: 1st column = name of datapoint\r\n ## nth column = parameter values\r\n ## space = 2 row dataframe defining region of interest\r\n ## format: same as for data except name of \"datapoint\"\r\n ## in is SL in 1st row for the lower bound\r\n ## and SU in 2nd row for the upper bound\r\n ## sidesmall = MHR is too small to consider if\r\n ## volume < sidesmall^(# of parameters)\r\n ## reorder = reorder list of MHRs from largest to smallest\r\n ## Output: MHR = sorted list of candidate MHRs from largest to smallest\r\n ## MHRdropped = sorted list of deleted because of being too small or unbounded\r\n ## MHRreplaced = list of MHRs deleted because a datapoint exists inside it so not empty\r\n ## volumesmall = sidesmall^(# of parameters)\r\n\r\n ## ## debug\r\n ## browser()\r\n\r\n ## ## debug\r\n ## space <- spaces\r\n ## data <- dfs\r\n ## sidesmall <- 7\r\n ## reorder <- 'yes'\r\n\r\n ## rename data to df for use within function\r\n df <- data\r\n\r\n ## number of parameters\r\n nparam <- ncol(space) - 1\r\n end <- nparam * 2\r\n \r\n ## Define first MHR h as the entire space and insert into the set of MHRs t\r\n ## MHR to be defined using lower and upper bounds\r\n ## hL <- data.frame(t(rep('SL', nparam)), stringsAsFactors=FALSE)\r\n ## names(hL) <- names(space[2:(nparam+1)])\r\n hL <- space[1, 2:(nparam+1)]\r\n names(hL) <- paste(names(hL), \"_l\", sep=\"\")\r\n ## hU <- data.frame(t(rep('SU', nparam)), stringsAsFactors=FALSE)\r\n ## names(hU) <- names(space[2:(nparam+1)])\r\n hU <- space[2, 2:(nparam+1)]\r\n names(hU) <- paste(names(hU), \"_u\", sep=\"\")\r\n h <- cbind(hL,hU)\r\n ## add a list of additional bounding points on the MHR\r\n ## that may be needed to keep from inappropriately throwing out an MHR\r\n ## h$bounds <- list(bounds = as.character(h[1,]))\r\n ## h$bounds <- list(bounds = 'NA')\r\n t <- h\r\n\r\n ## define size for an MHR that is too small to consider\r\n volumespace <- size(hlocation(h, df, space))\r\n volumesmall <- sidesmall^nparam\r\n if (volumesmall > volumespace/4 ) {\r\n volumesmall <- volumespace/4\r\n cat('\\n**** WARNING: sidesmall too big so reduced to 1/4 of space of interest ****\\n')\r\n }\r\n \r\n ## initialize variables and dataframes\r\n hcount <- 1\r\n treplaced <- delete(t, t[1,], end)\r\n tdropped <- treplaced\r\n\r\n ## For each point in database, search whether it is in t\r\n cat('number of datapoints', nrow(df),'\\n')\r\n for (irow in 1:nrow(df)) {\r\n ##browser()\r\n ## if (irow >= 6) browser()\r\n pname <- as.character(df$name[irow])\r\n cat('starting datapoint', pname,'; number of MHRs =',nrow(t),'\\n')\r\n ## print(pname)\r\n ## identify list of MHRs (each is an h) in the set of MHRs t that contain x\r\n ## for loop will modify t so need a temporary dataframe tprev with the previous values of t\r\n ## that the for loop can work through\r\n tprev <- t\r\n for ( hi in 1:nrow(tprev) ) {\r\n ## cat('irow=',irow,'; hi=',hi,'; jdim=',jdim,'\\n')\r\n ## if (irow==12 & hi==130 & jdim==2) browser()\r\n h <- tprev[hi,]\r\n testloc <- ContainmentSearch(h, pname, df, space)$location\r\n if (testloc == 'on boundary') {\r\n ## insert x into set of bounding points in that surface\r\n ## t[hi,]$bounds[[1]] <- append(h$bounds[[1]], pname)\r\n ## ignore because point on boundary does not cause MHR to subdivide\r\n\r\n } else if (testloc == 'inside') {\r\n\r\n ## delete MHR h from collection of MHRs t\r\n t <- delete(t, h, end)\r\n\r\n ## add MHR h to list of deleted MHRs for later tracing if needed\r\n treplaced <- insert(treplaced, h)\r\n\r\n ## break MHR h into 2 separate smaller MHRs along each parameter\r\n ## add the two new MHRs, ha and hb, to the set of MHRs t\r\n ## for each dimension\r\n for (jdim in 1:nparam) {\r\n ## print(pname)\r\n ## print(jdim)\r\n ## start with the MHR of interest\r\n ha <- h\r\n hb <- h\r\n ## print(h)\r\n\r\n ## split h in each dimension, jdim\r\n ## first assign location to the split location\r\n datapoint <- df[df$name == pname,]\r\n ha[jdim+nparam] <- datapoint[1 + jdim]\r\n hb[jdim] <- datapoint[1 + jdim]\r\n\r\n ## identify name of the parent MHR\r\n parent <- stri_split_fixed(str = row.names(h), pattern = \"_\", n = 2)[[1]][1]\r\n \r\n ## add new MHR ha if big enough and not completely contained in an existing MHR\r\n haloc <- hlocation(ha, df, space)\r\n sizeha <- size(haloc)\r\n ## if (pname == 'point3' & jdim == 2) browser()\r\n ## name the MHR\r\n hcount <- hcount+1\r\n row.names(ha) <- paste(hcount, '_jdim', jdim, \"L\", \"_parent_\", parent, sep=\"\")\r\n ## add MHR to t if big enough and drop if too small\r\n if ( sizeha >= volumesmall ) {\r\n if ( nrow(t) == 0 ) {\r\n ## t is empty so add ha\r\n t <- rbind(t, ha)\r\n } else if ( inexisting(t, haloc) == 'no' ) {\r\n ## add ha because it is not fully contained inside another MHR\r\n t <- rbind(t, ha)\r\n }\r\n } else {\r\n ## drop the MHR\r\n tdropped <- rbind(tdropped, ha) \r\n }\r\n\r\n ## add new MHR ha if big enough and not completely contained in an existing MHR\r\n hbloc <- hlocation(hb, df, space)\r\n sizehb <- size(hbloc)\r\n hcount <- hcount+1\r\n row.names(hb) <- paste(hcount, '_jdim', jdim, \"U\", \"_parent_\", parent, sep=\"\")\r\n if ( sizehb >= volumesmall ) {\r\n if ( nrow(t) == 0 ) {\r\n t <- rbind(t, hb)\r\n } else if ( inexisting(t, hbloc) == 'no' ) {\r\n t <- rbind(t, hb)\r\n }\r\n } else {\r\n tdropped <- rbind(tdropped, hb) \r\n }\r\n \r\n }\r\n } \r\n ## else testloc == 'outside' so look at the next MHR in t\r\n }\r\n }\r\n\r\n ## identify location of each side of MHRs\r\n ## strip off the boundary column for later lapply function\r\n tloc <- t[1:end]\r\n for (i in 1:nrow(tloc)) {\r\n ## tloc <- apply(t, 1, function(h) hlocation(h, df, space))\r\n h <- tloc[i,]\r\n tloc[i,] <- as.numeric( hlocation(h, df, space) )\r\n }\r\n tloc\r\n ## tloc was still all character for some reason so need to convert to numeric\r\n tloc[] <- lapply(tloc, as.numeric) \r\n\r\n ## add column of MHR sizes\r\n tloc$size <- size(tloc)\r\n t$size <- tloc$size\r\n\r\n ## reorder by size\r\n if (reorder == 'yes') {\r\n tloc <- tloc [order(tloc$size, decreasing=TRUE),]\r\n t <- t [order(t$size, decreasing=TRUE),]\r\n }\r\n\r\n ## do the same for the dataframe of MHRs that were too small\r\n if (nrow(tdropped) > 0) {\r\n tlocdropped <- tdropped\r\n for (i in 1:nrow(tlocdropped)) {\r\n h <- tlocdropped[i,]\r\n tlocdropped[i,] <- as.numeric( hlocation(h, df, space) )\r\n }\r\n tlocdropped[] <- lapply(tlocdropped, as.numeric) # tlocdropped was all character\r\n tdropped$size <- size(tlocdropped)\r\n if (reorder == 'yes') tdropped <- tdropped[order(tdropped$size, decreasing=TRUE),]\r\n }\r\n\r\n return(list(MHRloc=tloc, MHR=t, MHRdropped=tdropped,\r\n MHRreplaced=treplaced, volumesmall=volumesmall))\r\n \r\n}\r\n", "meta": {"hexsha": "0d9a2dcb3ca9f8a639546926284634114f000b0e", "size": 9092, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/holes_liu_dlh.r", "max_stars_repo_name": "TECComputing/R-setup", "max_stars_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/holes_liu_dlh.r", "max_issues_repo_name": "TECComputing/R-setup", "max_issues_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/holes_liu_dlh.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-16T12:06:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T12:06:21.000Z", "avg_line_length": 45.0099009901, "max_line_length": 100, "alphanum_fraction": 0.4926308843, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.46550417671004457}} {"text": "## --------------------\n## --------------------\n## --------------------\n## These codes implement the MLR for short-term forecast(5 year). For mid-term, long-term or other dataset, these should be modified adaptively.\n## --------------------\n## --------------------\n## --------------------\nrm(list = ls())\nlibrary(nnet)\nlibrary(tidyverse)\n\nlibrary(reshape2)\nlibrary(data.table)\nlibrary(rTensor)\nset.seed(082020)\n\n## --------------------\n## Data attributes\n## --------------------\npopm <- fread(\"population_male.csv\")\nusam <- fread(\"mortality rate for male with comparability ratio.csv\")\ncolnames(popm)[4:22] <- c(\n \"infant\", \"1-4\",\n \"5-9\", \"10-14\",\n \"15-19\", \"20-24\",\n \"25-29\", \"30-34\",\n \"35-39\", \"40-44\",\n \"45-49\", \"50-54\",\n \"55-59\", \"60-64\",\n \"65-69\", \"70-74\",\n \"75-79\", \"80-84\",\n \"85+\"\n)\ncolnames(usam)[4:22] <- c(\n \"infant\", \"1-4\",\n \"5-9\", \"10-14\",\n \"15-19\", \"20-24\",\n \"25-29\", \"30-34\",\n \"35-39\", \"40-44\",\n \"45-49\", \"50-54\",\n \"55-59\", \"60-64\",\n \"65-69\", \"70-74\",\n \"75-79\", \"80-84\",\n \"85+\"\n)\n\n###### process population data\npopn <- reshape2::melt(popm[, c(2, 4:22)], id.vars = c(\"Year\"))\ncolnames(popn) <- c(\"Year\", \"agegroups\", \"pop\")\npopn <- setorder(popn, \"Year\")\npopn$Year <- popn$Year - 1949\n\n\n###### process mortality rate\ncir <- usam[Cause == \"Circulatory system\"][, c(2, 4:22)]\ncir1 <- melt(cir, id.vars = \"Year\")\nsetorder(cir1, \"Year\", \"variable\", \"value\")\ncolnames(cir1) <- c(\"Year\", \"agegroups\", \"Circulatory system\")\ncir1$Year <- cir1$Year - 1949\n\ncan <- usam[Cause == \"Cancer\"][, c(2, 4:22)]\ncan1 <- melt(can, id.vars = \"Year\")\nsetorder(can1, \"Year\", \"variable\", \"value\")\ncolnames(can1) <- c(\"Year\", \"agegroups\", \"Cancer\")\ncan1$Year <- can1$Year - 1949\n\nrs <- usam[Cause == \"Respiratory system\"][, c(2, 4:22)]\nrs1 <- melt(rs, id.vars = \"Year\")\nsetorder(rs1, \"Year\", \"variable\", \"value\")\ncolnames(rs1) <- c(\"Year\", \"agegroups\", \"Respiratory system\")\nrs1$Year <- rs1$Year - 1949\n\niapd <- usam[Cause == \"Infectious and parasitic diseases\"][, c(2, 4:22)]\niapd1 <- melt(iapd, id.vars = \"Year\")\nsetorder(iapd1, \"Year\", \"variable\", \"value\")\ncolnames(iapd1) <- c(\"Year\", \"agegroups\", \"Infectious and parasitic diseases\")\niapd1$Year <- iapd1$Year - 1949\n\nec <- usam[Cause == \"External causes\"][, c(2, 4:22)]\nec1 <- melt(ec, id.vars = \"Year\")\nsetorder(ec1, \"Year\", \"variable\", \"value\")\ncolnames(ec1) <- c(\"Year\", \"agegroups\", \"External causes\")\nec1$Year <- ec1$Year - 1949\n\noth <- usam[Cause == \"Others\"][, c(2, 4:22)]\noth1 <- melt(oth, id.vars = \"Year\")\nsetorder(oth1, \"Year\", \"variable\", \"value\")\ncolnames(oth1) <- c(\"Year\", \"agegroups\", \"Others\")\noth1$Year <- oth1$Year - 1949\n\nprobs <- cbind(cir1, can1[, 3], rs1[, 3], iapd1[, 3], ec1[, 3], oth1[, 3])\nsur1 <- oth1\ncolnames(sur1) <- c(\"Year\", \"agegroups\", \"Survival\")\nsur1$Survival <- 1 - rowSums(probs[, 3:8])\nprobs <- cbind(sur1, probs[, 3:8])\ncolnames(probs)[5:9] <- c(\"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\")\n\n##### counts\nresp <- left_join(probs, popn, by = c(\"Year\", \"agegroups\"))\nhead(resp)\n\nresp2 <- (resp[, 3:9] * resp$pop) %>%\n round() %>%\n as.matrix()\n\n(rowSums(resp2) - resp$pop) %>%\n summary() ## Sanity check. All of these should be very close to zero\nrownames(probs) <- rownames(resp) <- rownames(resp2) <- rownames(popn) <- NULL\n\n## --------------------\n## Fit multinomial logistic regression and compare results\n## --------------------\nyears <- (1:58) %>%\n scale(center = FALSE, scale = FALSE)\nagegroups <- c(\n \"infant\", \"1-4\",\n \"5-9\", \"10-14\",\n \"15-19\", \"20-24\",\n \"25-29\", \"30-34\",\n \"35-39\", \"40-44\",\n \"45-49\", \"50-54\",\n \"55-59\", \"60-64\",\n \"65-69\", \"70-74\",\n \"75-79\", \"80-84\",\n \"85+\"\n)\ndat <- data.frame(years = rep(years, each = length(unique(resp$agegroups))), agegroups = rep(agegroups, length(unique(resp$Year))))\nhead(dat)\n\nmake_offset <- matrix(resp$pop, nrow = nrow(probs), ncol = ncol(resp2))\n# simplest\nfit_mlr1s <- multinom(resp2[1:1007, ] ~ years + agegroups + offset(make_offset[1:1007, ]), data = dat[1:1007, ], maxit = 1000)\n# single\nfit_mlr1 <- multinom(resp2[1:1007, ] ~ years + agegroups + years:agegroups + offset(make_offset[1:1007, ]), data = dat[1:1007, ], maxit = 1000)\n# quadratic\nfit_mlr2 <- multinom(resp2[1:1007, ] ~ years + agegroups + I(years):agegroups + I(years^2) + I(years^2):agegroups + offset(make_offset[1:1007, ]), data = dat[1:1007, ], maxit = 1000)\n# cubic\nfit_mlr3 <- multinom(resp2[1:1007, ] ~ years + agegroups + I(years^2) + I(years^2):agegroups + I(years):agegroups + I(years^3) + I(years^3):agegroups + offset(make_offset[1:1007, ]), data = dat[1:1007, ], maxit = 5000)\n\nsummary(fit_mlr1s)\nsummary(fit_mlr1)\nsummary(fit_mlr2)\nsummary(fit_mlr3)\n\ncoefs1s <- coef(fit_mlr1s)\ncoefs1 <- coef(fit_mlr1)\ncoefs2 <- coef(fit_mlr2)\ncoefs3 <- coef(fit_mlr3)\n\n## --------------------\n## --------------------\n## fit\n## --------------------\n## --------------------\nfit_dat <- data.frame(years = rep(c(1:53), each = length(unique(resp$agegroups))), agegroups = rep(agegroups, 53))\nX_fit1s <- model.matrix(~ years + agegroups, data = fit_dat)\nX_fit1 <- model.matrix(~ years + agegroups + years:agegroups, data = fit_dat)\nX_fit2 <- model.matrix(~ years + agegroups + I(years):agegroups + I(years^2) + I(years^2):agegroups, data = fit_dat)\nX_fit3 <- model.matrix(~ years + agegroups + I(years^2) + I(years^2):agegroups + I(years):agegroups + I(years^3) + I(years^3):agegroups, data = fit_dat)\n\n\n## --------------------\n## simplest\n## --------------------\nfit_probs1s <- tcrossprod(X_fit1s, coefs1s) %>%\n exp()\nfit_probs1s <- cbind(1 / (1 + rowSums(fit_probs1s)), fit_probs1s / (1 + rowSums(fit_probs1s)))\ncolnames(fit_probs1s)[1] <- \"Survival\"\nfit_probs1s <- cbind(fit_dat, fit_probs1s[, 2:7])\ncolnames(fit_probs1s)[1] <- \"Year\"\n\ndf_wide1s <- as.data.table(fit_probs1s) %>% data.table::dcast(Year ~ agegroups, value.var = colnames(as.data.table(fit_probs1s))[3:8])\n\nfit1s <- df_wide1s %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\nfit1s <- fit1s[, colnames(usam[, c(2:22)])]\n\n## --------------------\n## single\n## --------------------\nfit_probs1 <- tcrossprod(X_fit1, coefs1) %>%\n exp()\nfit_probs1 <- cbind(1 / (1 + rowSums(fit_probs1)), fit_probs1 / (1 + rowSums(fit_probs1)))\ncolnames(fit_probs1)[1] <- \"Survival\"\nfit_probs1 <- cbind(fit_dat, fit_probs1[, 2:7])\ncolnames(fit_probs1)[1] <- \"Year\"\n\ndf_wide1 <- as.data.table(fit_probs1) %>% data.table::dcast(Year ~ agegroups, value.var = colnames(as.data.table(fit_probs1))[3:8])\n\nfit1 <- df_wide1 %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\nfit1 <- fit1[, colnames(usam[, c(2:22)])]\n##### difference for single\nfnorm(generate_mortality_tensor(fit1) - generate_mortality_tensor(usam[1:(53 * 6), ]))\n\n## --------------------\n## quadratic\n## --------------------\nfit_probs2 <- tcrossprod(X_fit2, coefs2) %>%\n exp()\nfit_probs2 <- cbind(1 / (1 + rowSums(fit_probs2)), fit_probs2 / (1 + rowSums(fit_probs2)))\ncolnames(fit_probs2)[1] <- \"Survival\"\nfit_probs2 <- cbind(fit_dat, fit_probs2[, 2:7])\ncolnames(fit_probs2)[1] <- \"Year\"\n\ndf_wide2 <- as.data.table(fit_probs2) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\nfit2 <- df_wide2 %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\nfit2 <- fit2[, colnames(usam[, c(2:22)])]\n##### difference for quadratic\nfnorm(generate_mortality_tensor(fit2) - generate_mortality_tensor(usam[1:(53 * 6), ]))\n\n\n## --------------------\n## cubic\n## --------------------\nfit_probs3 <- tcrossprod(X_fit3, coefs3) %>%\n exp()\nfit_probs3 <- cbind(1 / (1 + rowSums(fit_probs3)), fit_probs3 / (1 + rowSums(fit_probs3)))\ncolnames(fit_probs3)[1] <- \"Survival\"\nfit_probs3 <- cbind(fit_dat, fit_probs3[, 2:7])\ncolnames(fit_probs3)[1] <- \"Year\"\n\ndf_wide3 <- as.data.table(fit_probs3) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\nfit3 <- df_wide3 %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\nfit3 <- fit3[, colnames(usam[, c(2:22)])]\n##### difference for quadratic\nfnorm(generate_mortality_tensor(fit3) - generate_mortality_tensor(usam[1:(53 * 6), ]))\n\n\n## --------------------\n## --------------------\n## predict\n## --------------------\n## --------------------\npre_dat <- data.frame(years = rep(c(54:58), each = length(unique(resp$agegroups))), agegroups = rep(agegroups, 5))\nX_pred1s <- model.matrix(~ years + agegroups, data = pre_dat)\nX_pred1 <- model.matrix(~ years + agegroups + years:agegroups, data = pre_dat)\nX_pred2 <- model.matrix(~ years + agegroups + I(years):agegroups + I(years^2) + I(years^2):agegroups, data = pre_dat)\nX_pred3 <- model.matrix(~ years + agegroups + I(years^2) + I(years^2):agegroups + I(years):agegroups + I(years^3) + I(years^3):agegroups, data = pre_dat)\n\n## --------------------\n## simplest\n## --------------------\npred_probs1s <- tcrossprod(X_pred1s, coefs1s) %>%\n exp()\npred_probs1s <- cbind(1 / (1 + rowSums(pred_probs1s)), pred_probs1s / (1 + rowSums(pred_probs1s)))\ncolnames(pred_probs1s)[1] <- \"Survival\"\npred_probs1s <- cbind(pre_dat, pred_probs1s[, 2:7])\ncolnames(pred_probs1s)[1] <- \"Year\"\n\ndf_wide1ps <- as.data.table(pred_probs1s) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\npred1s <- df_wide1ps %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\npred1s <- pred1s[, colnames(usam[, c(2:22)])]\n##### difference\nfnorm(generate_mortality_tensor(pred1s) - generate_mortality_tensor(usam[(53 * 6 + 1):(58 * 6), ]))\n\n\n## --------------------\n## single\n## --------------------\npred_probs1 <- tcrossprod(X_pred1, coefs1) %>%\n exp()\npred_probs1 <- cbind(1 / (1 + rowSums(pred_probs1)), pred_probs1 / (1 + rowSums(pred_probs1)))\ncolnames(pred_probs1)[1] <- \"Survival\"\npred_probs1 <- cbind(pre_dat, pred_probs1[, 2:7])\ncolnames(pred_probs1)[1] <- \"Year\"\n\ndf_wide1p <- as.data.table(pred_probs1) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\npred1 <- df_wide1p %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\npred1 <- pred1[, colnames(usam[, c(2:22)])]\n##### difference\nfnorm(generate_mortality_tensor(pred1) - generate_mortality_tensor(usam[(53 * 6 + 1):(58 * 6), ]))\n\n\n\n## --------------------\n## quadratic\n## --------------------\npred_probs2 <- tcrossprod(X_pred2, coefs2) %>%\n exp()\npred_probs2 <- cbind(1 / (1 + rowSums(pred_probs2)), pred_probs2 / (1 + rowSums(pred_probs2)))\ncolnames(pred_probs2)[1] <- \"Survival\"\npred_probs2 <- cbind(pre_dat, pred_probs2[, 2:7])\ncolnames(pred_probs2)[1] <- \"Year\"\n\ndf_wide2p <- as.data.table(pred_probs2) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\npred2 <- df_wide2p %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\npred2 <- pred2[, colnames(usam[, c(2:22)])]\n##### difference\nfnorm(generate_mortality_tensor(pred2) - generate_mortality_tensor(usam[(53 * 6 + 1):(58 * 6), ]))\n\n## --------------------\n## cubic\n## --------------------\n\npred_probs3 <- tcrossprod(X_pred3, coefs3) %>%\n exp()\npred_probs3 <- cbind(1 / (1 + rowSums(pred_probs3)), pred_probs3 / (1 + rowSums(pred_probs3)))\ncolnames(pred_probs3)[1] <- \"Survival\"\npred_probs3 <- cbind(pre_dat, pred_probs3[, 2:7])\ncolnames(pred_probs3)[1] <- \"Year\"\n\ndf_wide3p <- as.data.table(pred_probs3) %>% data.table::dcast(Year ~ agegroups, value.var = c(\"Circulatory system\", \"Cancer\", \"Respiratory system\", \"Infectious and parasitic diseases\", \"External causes\", \"Others\"))\n\npred3 <- df_wide3p %>%\n gather(variable, value, -Year) %>%\n mutate(\n Cause = sub(\"_.*\", \"\", variable),\n variable = sub(\".*_\", \"\", variable)\n ) %>%\n spread(variable, value)\n\npred3 <- pred3[, colnames(usam[, c(2:22)])]\n##### difference\nfnorm(generate_mortality_tensor(pred3) - generate_mortality_tensor(usam[(53 * 6 + 1):(58 * 6), ]))", "meta": {"hexsha": "bc288e6e8f51aa4e11e7e0f3cdf06796a8ad631f", "size": 13090, "ext": "r", "lang": "R", "max_stars_repo_path": "MLR.r", "max_stars_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_stars_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MLR.r", "max_issues_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_issues_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MLR.r", "max_forks_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_forks_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6675749319, "max_line_length": 218, "alphanum_fraction": 0.5990832697, "num_tokens": 4283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46544473547256127}} {"text": "# This is a primal-dual log barrier form of the\n# interior point LP solver of Lustig, Marsten and Shanno ORSA J Opt 1992.\n# It is a projected Newton primal-dual logarithmic barrier method which uses\n# the predictor-corrector approach of Mehrotra for the mu steps.\n# For the sake of brevity we will call it a Frisch-Newton algorithm.\n# The primary difference between this code and the previous version fna.r is\n# that we assume a feasible starting point so p,d,b feasibility gaps = 0.\n# Problem:\n# \tmin c'x s.t. Ax=b, 0<=x<=u\n# \n# The linear system we are trying to solve at each interation is:\n# \t\t Adx = 0\n# \t dx + ds = 0\n# \tA'dy -dw +dz = 0\n# \t Xdz + Zdx = me - XZe - DXDZe\n# \t Sdw + Wds = me - SWe - DSDWe \n# But the algorithm proceeds in two steps the first of which is to solve:\n# \t\t Adx = 0\n# \t dx + ds = 0\n# \tA'dy -dw +dz = 0\n# \t Xdz + Zdx = - XZe \n# \t Sdw + Wds = - SWe\n# and then to make some refinement of mu and modify the implied Newton step.\n# Denote dx,dy,dw,ds,dz as the steps for the respective variables x,y,w,s,z, and\n# the corresponding upper case letters are the diagonal matrices respectively.\n# \n# To illustrate the use of the function we include a calling routine to\n# compute solutions to the linear quantile regression estimation problem.\n# See the associated S function rqfn for details on the calling sequence.\n# On input:\n# \ta is the p by n matrix X'\n# \ty is the n-vector of responses\n# \tu is the n-vector of upper bounds \n# d is an n-vector of ones\n# wn is an n-vector of ones in the first n elements\n# \tbeta is a scaling constant, conventionally .99995\n# \teps is a convergence tolerance, conventionally 1d-07\n# On output:\n# \ta,y are unaltered\n# \twp contains the solution coefficient vector in the first p elements\n# \twn contains the residual vector in the first n elements\n# \n# \nsubroutine rqfn(n,p,a,y,rhs,d,u,beta,eps,wn,wp,aa,nit,info)\ninteger n,p,info,nit(3)\ndouble precision a(p,n),y(n),rhs(p),d(n),u(n),wn(n,10),wp(p,p+3),aa(p,p)\ndouble precision one,beta,eps\nparameter( one = 1.0d0)\ncall fna(n,p,a,y,rhs,d,u,beta,eps,wn(1,1),wn(1,2),\n\twp(1,1),wn(1,3),wn(1,4),wn(1,5), wn(1,6),\n\twp(1,2),wn(1,7),wn(1,8),wn(1,9),wn(1,10),wp(1,3), wp(1,4),aa,nit,info)\nreturn\nend\nsubroutine fna(n,p,a,c,b,d,u,beta,eps,x,s,y,z,w,\n\t\tdx,ds,dy,dz,dw,dsdw,dxdz,rhs,ada,aa,nit,info)\n\ninteger n,p,pp,i,info,nit(3)\ndouble precision a(p,n),c(n),b(p)\ndouble precision zero,one,mone,big,ddot,dmax1,dmin1,dasum\ndouble precision deltap,deltad,beta,eps,cx,by,uw,uz,mu,mua,acomp,rdg,g\ndouble precision x(n),u(n),s(n),y(p),z(n),w(n),d(n),rhs(p),ada(p,p)\ndouble precision aa(p,p),dx(n),ds(n),dy(p),dz(n),dw(n),dxdz(n),dsdw(n)\n\nparameter( zero = 0.0d0)\nparameter( half = 0.5d0)\nparameter( one = 1.0d0)\nparameter( mone = -1.0d0)\nparameter( big = 1.0d+20)\n\n# Initialization: We try to follow the notation of LMS\n# On input we require:\n# \n# \tc = n-vector of marginal costs (-y in the rq problem)\n# \ta = p by n matrix of linear constraints (x' in rq)\n# \tb = p-vector of rhs ((1-tau)x'e in rq)\n# u = upper bound vector ( e in rq)\n# \tbeta = barrier parameter, LMS recommend .99995\n# \teps = convergence tolerance, LMS recommend 10d-8\n# \t\n# \tthe integer vector nit returns iteration counts\n# \tthe integer info contains an error code from the Cholesky in stepy\n# \t\tinfo = 0 is fine\n# \t\tinfo < 0 invalid argument to dposv \n# \t\tinfo > 0 singular matrix\nnit(1)=0\nnit(2)=0\nnit(3)=n\npp=p*p\n# Start at the OLS estimate for the parameters\ncall dgemv('N',p,n,one,a,p,c,1,zero,y,1)\ncall stepy(n,p,a,d,y,aa,info)\nif(info != 0) return\n# Save sqrt of aa' for future use for confidence band\ndo i=1,p{\n\tdo j=1,p\n\t\tada(i,j)=zero\n ada(i,i)=one\n\t}\ncall dtrtrs('U','T','N',p,p,aa,p,ada,p,info)\ncall dcopy(pp,ada,1,aa,1)\n# put current residual vector in s (temporarily)\ncall dcopy(n,c,1,s,1)\ncall dgemv('T',p,n,mone,a,p,y,1,one,s,1)\n# Initialize remaining variables\n# N.B. x must be initialized on input: for rq as (one-tau) in call coordinates\ndo i=1,n{\n\td(i)=one\n\tif(dabs(s(i)) < eps){\n\t\tz(i) = dmax1( s(i),zero) + eps\n\t\tw(i) = dmax1(-s(i),zero) + eps\n\t\t}\n\telse {\n\t\tz(i) = dmax1( s(i),zero)\n\t\tw(i) = dmax1(-s(i),zero) \n\t\t}\n\ts(i)=u(i)-x(i)\n\t}\ncx = ddot(n,c,1,x,1)\nby = ddot(p,b,1,y,1)\nuw = dasum(n,w,1)\nuz = dasum(n,z,1)\n# rdg = (cx - by + uw)/(one + dabs( by - uw))\n# rdg = (cx - by + uw)/(one + uz + uw)\nrdg = (cx - by + uw)\nwhile(rdg > eps) {\n\tnit(1)=nit(1)+1\n\tdo i =1,n{\n\t\td(i) = one/(z(i)/x(i) + w(i)/s(i))\n\t\tds(i)=z(i)-w(i)\n\t\tdx(i)=d(i)*ds(i)\n\t\t}\n\tcall dgemv('N',p,n,one,a,p,dx,1,zero,dy,1)#rhs\n\tcall dcopy(p,dy,1,rhs,1)#save rhs\n\tcall stepy(n,p,a,d,dy,ada,info)\n\tif(info != 0) return\n\tcall dgemv('T',p,n,one,a,p,dy,1,mone,ds,1)\n\tdeltap=big\n\tdeltad=big\n\tdo i=1,n{\n\t\tdx(i)=d(i)*ds(i)\n\t\tds(i)=-dx(i)\n\t\tdz(i)=-z(i)*(dx(i)/x(i) + one)\n\t\tdw(i)=w(i)*(dx(i)/s(i) - one)\n\t\tdxdz(i)=dx(i)*dz(i)\n\t\tdsdw(i)=ds(i)*dw(i)\n\t\tif(dx(i)<0)deltap=dmin1(deltap,-x(i)/dx(i))\n\t\tif(ds(i)<0)deltap=dmin1(deltap,-s(i)/ds(i))\n\t\tif(dz(i)<0)deltad=dmin1(deltad,-z(i)/dz(i))\n\t\tif(dw(i)<0)deltad=dmin1(deltad,-w(i)/dw(i))\n\t\t}\n\tdeltap=dmin1(beta*deltap,one)\n\tdeltad=dmin1(beta*deltad,one)\n\tif(deltap*deltad1) mu=(g/dfloat(n))*(g/acomp)**2\n\t\t#else mu=acomp/(dfloat(n)**2)\n\t\tdo i=1,n{\n\t\t\tdz(i)=d(i)*(mu*(1/s(i)-1/x(i))+\n\t\t\t\tdx(i)*dz(i)/x(i)-ds(i)*dw(i)/s(i))\n\t\t\t}\n\t\tcall dswap(p,rhs,1,dy,1)\n\t\tcall dgemv('N',p,n,one,a,p,dz,1,one,dy,1)#new rhs\n\t\tcall dpotrs('U',p,1,ada,p,dy,p,info)\n\t\tcall daxpy(p,mone,dy,1,rhs,1)#rhs=ddy\n\t\tcall dgemv('T',p,n,one,a,p,rhs,1,zero,dw,1)#dw=A'ddy\n\t\tdeltap=big\n\t\tdeltad=big\n\t\tdo i=1,n{\n\t\t\tdx(i)=dx(i)-dz(i)-d(i)*dw(i)\n\t\t\tds(i)=-dx(i)\n\t\t\tdz(i)=mu/x(i) - z(i)*dx(i)/x(i) - z(i) - dxdz(i)/x(i)\n\t\t\tdw(i)=mu/s(i) - w(i)*ds(i)/s(i) - w(i) - dsdw(i)/s(i)\n\t\t\tif(dx(i)<0)deltap=dmin1(deltap,-x(i)/dx(i))\n\t\t\telse deltap=dmin1(deltap,-s(i)/ds(i))\n\t\t\tif(dz(i)<0)deltad=dmin1(deltad,-z(i)/dz(i))\n\t\t\tif(dw(i)<0)deltad=dmin1(deltad,-w(i)/dw(i))\n\t\t\t}\n\t\tdeltap=dmin1(beta*deltap,one)\n\t\tdeltad=dmin1(beta*deltad,one)\n\t\t}\n\tcall daxpy(n,deltap,dx,1,x,1)\n\tcall daxpy(n,deltap,ds,1,s,1)\n\tcall daxpy(p,deltad,dy,1,y,1)\n\tcall daxpy(n,deltad,dz,1,z,1)\n\tcall daxpy(n,deltad,dw,1,w,1)\n\tcx=ddot(n,c,1,x,1)\n\tby=ddot(p,b,1,y,1)\n\tuw = dasum(n,w,1)\n\tuz = dasum(n,z,1)\n\t#rdg=(cx-by+uw)/(one+dabs(by-uw))\n\t#rdg=(cx-by+uw)/(one+uz+uw)\n\trdg=(cx-by+uw)\n\t}\n# return residuals in the vector x\ncall daxpy(n,mone,w,1,z,1)\ncall dswap(n,z,1,x,1)\nreturn\nend\n", "meta": {"hexsha": "d67114f55d7b75a54827a7aeabb9a48dfd0d4982", "size": 6674, "ext": "r", "lang": "R", "max_stars_repo_path": "fortran/ratfor/rqfn.r", "max_stars_repo_name": "mhoward2718/quantreg", "max_stars_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-02T22:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T22:15:54.000Z", "max_issues_repo_path": "fortran/ratfor/rqfn.r", "max_issues_repo_name": "mhoward2718/quantreg", "max_issues_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fortran/ratfor/rqfn.r", "max_forks_repo_name": "mhoward2718/quantreg", "max_forks_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9330143541, "max_line_length": 80, "alphanum_fraction": 0.6317051244, "num_tokens": 2772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4653742947104924}} {"text": "require(Matrix)\nholidays.Sweden <- as.Date(c(\"2020-04-10\",\"2020-04-13\",\"2020-05-01\",\"2020-05-21\",\"2020-06-19\",\"2020-06-20\"))\n\n##\n# sample reported deaths after rep.day (if Inf) predicit day\n# assuming Multionimal distribution\n#\n# samples - (int) how many samples should be done for each N (cheap)\n# deaths - (N x 1) true number of deaths each day\n# P - (N x N) matrix of probabilites (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# alpha - (N x 1) stepsizes\n# true.dat - (int) how many days after recording should one sample\n##\nsample.deaths <- function(samples, deaths, P, Reported, alpha, true.day = 0,\n use.prior=FALSE,\n prior=NULL){\n\n N <- length(deaths)\n acc <- rep(0,N)\n for(i in 1:N){\n if(i > true.day){\n P_i = P[i,i:N]\n Reported_i = Reported[i,i:N]\n index = is.na(Reported_i)==F\n P_i = P_i[index]\n Reported_i = Reported_i[index]\n lik_i <- loglikDeathsGivenProb(deaths[i], P_i, Reported_i)\n if(use.prior==T)\n lik_i <- lik_i + prior(deaths[i], i)\n for(j in 1:samples){\n death_star <- sample((deaths[i]-alpha[i]):(deaths[i]+alpha[i]), 1)\n lik_star <- loglikDeathsGivenProb(death_star, P_i, Reported_i)\n if(use.prior==T)\n lik_star <- lik_star + prior(death_star, i)\n if(is.nan(lik_star))\n next\n\n if(log(runif(1)) < lik_star-lik_i){\n lik_i = lik_star\n deaths[i] <- death_star\n acc[i] = acc[i] + 1\n }\n }\n }\n }\n return(list(deaths=deaths, acc = acc))\n}\n\n\n##\n# sample reported deaths after rep.day (if Inf) predicit day using Beta binomial dist\n#\n# samples - (int) how many samples should be done for each N (cheap)\n# deaths - (N x 1) true number of deaths each day\n# alpha - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# beta - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# alpha.MCMC - (N x 1) stepsizes\n# true.dat - (int) how many days after recording should one sample\n# prior - (function) should return log of prior density (use N and i)\n##\nsample.deathsBB <- function(samples, deaths, alpha, beta, Reported, alpha.MCMC, true.day = 0 ,\n use.prior=FALSE,\n prior=NULL){\n\n N <- length(deaths)\n acc <- rep(0,N)\n for(i in 1:N){\n if(i > true.day){\n alpha_i = alpha[i,i:N]\n beta_i = beta[i,i:N]\n Reported_i = Reported[i,i:N]\n index = is.na(Reported_i)==F\n alpha_i = alpha_i[index]\n beta_i = beta_i[index]\n Reported_i = Reported_i[index]\n if(length(Reported_i)>0){\n lik_i <- loglikDeathsGivenProbBB(deaths[i],alpha_i , beta_i, Reported_i)\n }else{\n lik_i <- 0\n }\n if(use.prior==T)\n lik_i <- lik_i + prior(deaths[i], i)\n for(j in 1:samples){\n death_star <- sample((deaths[i]-alpha.MCMC[i]):(deaths[i]+alpha.MCMC[i]), 1)\n if(length(Reported_i)>0){\n lik_star <- loglikDeathsGivenProbBB(death_star, alpha_i , beta_i, Reported_i)\n }else{\n lik_star <- 0\n }\n if(use.prior==T)\n lik_star <- lik_star + prior(death_star, i)\n if(is.nan(lik_star))\n next\n if(log(runif(1)) < lik_star-lik_i){\n lik_i = lik_star\n deaths[i] <- death_star\n acc[i] = acc[i] + 1\n }\n }\n }\n }\n return(list(deaths=deaths, acc = acc))\n}\n\n##\n# sample reported deaths after rep.day (if Inf) predicit day using Beta binomial dist\n#\n# samples - (int) how many samples should be done for each N (cheap)\n# deaths - (N x 1) true number of deaths each day\n# alpha - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# beta - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# alpha.MCMC - (N x 1) stepsizes\n# true.dat - (int) how many days after recording should one sample\n# prior - (function) should return log of prior density (use N and i)\n##\nsample.deathsBB_bi <- function(samples, deaths, alpha, beta, Reported, alpha.MCMC, true.day = 0 ,\n p_null,\n pi_null,\n use.prior=FALSE,\n prior=NULL){\n\n N <- length(deaths)\n acc <- rep(0,N)\n for(i in 1:N){\n if(i > true.day){\n alpha_i = alpha[i,i:N]\n beta_i = beta[i,i:N]\n Reported_i = Reported[i,i:N]\n index = is.na(Reported_i)==F\n alpha_i = alpha_i[index]\n beta_i = beta_i[index]\n Reported_i = Reported_i[index]\n if(length(Reported_i)>0){\n lik_i <- loglikDeathsGivenProbBB_bi(deaths[i],alpha_i , beta_i, pi_null,p_null, Reported_i)\n }else{\n lik_i <- 0\n }\n if(use.prior==T)\n lik_i <- lik_i + prior(deaths[i], i)\n for(j in 1:samples){\n death_star <- sample((deaths[i]-alpha.MCMC[i]):(deaths[i]+alpha.MCMC[i]), 1)\n if(length(Reported_i)>0){\n lik_star <- loglikDeathsGivenProbBB_bi(death_star, alpha_i , beta_i, pi_null,p_null, Reported_i)\n }else{\n lik_star <- 0\n }\n if(use.prior==T)\n lik_star <- lik_star + prior(death_star, i)\n if(is.nan(lik_star))\n next\n if(log(runif(1)) < lik_star-lik_i){\n lik_i = lik_star\n deaths[i] <- death_star\n acc[i] = acc[i] + 1\n }\n }\n }\n }\n return(list(deaths=deaths, acc = acc))\n}\n\n\n##\n# sample reported deaths after rep.day (if Inf) predicit day using Beta binomial dist\n#\n# samples - (int) how many samples should be done for each N (cheap)\n# deaths - (N x 1) true number of deaths each day\n# alpha - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# beta - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# alpha.MCMC - (N x 1) stepsizes\n# true.dat - (int) how many days after recording should one sample\n# prior - (function) should return log of prior density (use N and i)\n##\nsample.deathsBB_negbin <- function(samples, deaths, alpha, beta, Reported, alpha.MCMC, true.day = 0 ,\n theta,\n phi){\n\n N <- length(deaths)\n acc <- rep(0,N)\n for(i in 1:N){\n if(i > true.day){\n alpha_i = alpha[i,i:N]\n beta_i = beta[i,i:N]\n Reported_i = Reported[i,i:N]\n index = is.na(Reported_i)==F\n alpha_i = alpha_i[index]\n beta_i = beta_i[index]\n Reported_i = Reported_i[index]\n if(length(Reported_i)>0){\n lik_i <- loglikDeathsGivenProbBB(deaths[i],alpha_i , beta_i, Reported_i)\n }else{\n lik_i <- 0\n }\n lik_i <- lik_i + dnegbin(deaths[i], theta[i],phi)\n for(j in 1:samples){\n death_star <- sample((deaths[i]-alpha.MCMC[i]):(deaths[i]+alpha.MCMC[i]), 1)\n if(length(Reported_i)>0){\n lik_star <- loglikDeathsGivenProbBB(death_star, alpha_i , beta_i, Reported_i)\n }else{\n lik_star <- 0\n }\n lik_star <- lik_star + dnegbin(death_star, theta[i],phi)\n if(is.nan(lik_star))\n next\n if(log(runif(1)) < lik_star-lik_i){\n lik_i = lik_star\n deaths[i] <- death_star\n acc[i] = acc[i] + 1\n }\n }\n }\n }\n return(list(deaths=deaths, acc = acc))\n}\n\n\n##\n# sample reported deaths after rep.day (if Inf) predicit day using Beta binomial dist\n#\n# samples - (int) how many samples should be done for each N (cheap)\n# deaths - (N x 1) true number of deaths each day\n# alpha - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# beta - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# alpha.MCMC - (N x 1) stepsizes\n# lag - (int) how many days after recording should one sample\n# prior - (function) should return log of prior density (use N and i)\n##\nsample.deathsBB.lag <- function(samples, deaths, alpha, beta, Reported, alpha.MCMC, lag ,\n dates,\n use.prior=FALSE,\n prior=NULL){\n\n N <- length(deaths)\n acc <- rep(0,N)\n holidays <- weekdays(dates)%in%c(\"Sunday\",\"Saturday\") | c(dates)%in%c(holidays.Sweden)\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:N]==F)==(lag+1))-1\n if(k==0){\n alpha_i = alpha[i,i:N]\n beta_i = beta[i,i:N]\n Reported_i = Reported[i,i:N]\n index = is.na(Reported_i)==F\n alpha_i = alpha_i[index]\n beta_i = beta_i[index]\n Reported_i = Reported_i[index]\n if(length(Reported_i)>0){\n lik_i <- loglikDeathsGivenProbBB(deaths[i],alpha_i , beta_i, Reported_i)\n }else{\n lik_i <- 0\n }\n if(use.prior==T)\n lik_i <- lik_i + prior(deaths[i], i)\n for(j in 1:samples){\n death_star <- sample((deaths[i]-alpha.MCMC[i]):(deaths[i]+alpha.MCMC[i]), 1)\n if(length(Reported_i)>0){\n lik_star <- loglikDeathsGivenProbBB(death_star, alpha_i , beta_i, Reported_i)\n }else{\n lik_star <- 0\n }\n if(use.prior==T)\n lik_star <- lik_star + prior(death_star, i)\n if(is.nan(lik_star))\n next\n if(log(runif(1)) < lik_star-lik_i){\n lik_i = lik_star\n deaths[i] <- death_star\n acc[i] = acc[i] + 1\n }\n }\n }\n }\n return(list(deaths=deaths, acc = acc))\n}\n\n##\n# fill report using binimoal beta\n#\n#\n##\nfill.ReportBB <- function(deaths, Alpha, Beta, Reported, maxusage.day){\n N <- length(deaths)\n N_2 <- dim(Alpha)[2]\n for(i in 1:N){\n Alpha_i = Alpha[i,i:N_2]\n Beta_i = Beta[i,i:N_2]\n Reported_i = Reported[i,i:N_2]\n index = is.na(Reported_i)==T\n for(j in min(which(index)):length(Reported_i)){\n p <- rbeta(1, Alpha_i[j], Beta_i[j])\n\n if(i> maxusage.day){\n if(j==1){\n Reported_i[j] <- rbinom(1, size=deaths[i] , prob = p)\n }else if(deaths[i] - Reported_i[j-1]>0){\n Reported_i[j] <- rbinom(1, size=deaths[i] - Reported_i[j-1], prob = p) + Reported_i[j-1]\n }else{Reported_i[j] <- Reported_i[j-1]}\n }else{\n Reported_i[j] <- Reported_i[j-1]\n }\n }\n Reported[i,i:N_2] = Reported_i\n }\n return(Reported)\n}\n\n\n##\n# fill report using binimoal beta up to lag\n#\n# deaths - (N x 1) number of estimated deaths\n# Alpha - (N x m) parameter for Beta Bin\n# Beta - (N x m) parameter for Beta Bin\n# dates - (m x 1) dates reported\n# Reported - (N x m) reported so far and na for non reported\n# lag - (int) lag = 0 is only first non-holiday, lag = 1 two non holidays\n##\nfill.ReportBB.lag <- function(deaths, Alpha, Beta, Reported, dates, lag){\n N <- length(deaths)\n m <- dim(Alpha)[2]\n holidays <- weekdays(dates)%in%c(\"Sunday\",\"Saturday\") | c(dates)%in%c(holidays.Sweden)\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:m]==F)==(lag+1))-1\n if(k==0)\n k <- m - i\n Alpha_i = Alpha[i,i:(i+k)]\n Beta_i = Beta[i,i:(i+k)]\n Reported_i = Reported[i,i:(i+k)]\n index = is.na(Reported_i)==T\n if(sum(index)==0)\n next\n\n for(j in min(which(index)):length(Reported_i)){\n p <- rbeta(1, Alpha_i[j], Beta_i[j])\n if(deaths[i] - Reported_i[j-1]>0){\n if(j==(k+1)){\n Reported_i[j] <- deaths[i]\n }else{\n Reported_i[j] <- rbinom(1, size=deaths[i] - Reported_i[j-1], prob = p) + Reported_i[j-1]\n }\n }else{Reported_i[j] <- Reported_i[j-1]}\n\n }\n Reported[i,i:(i+k)] = Reported_i\n }\n return(Reported)\n}\n\n##\n# fill report using binimoal beta post lag\n#\n# deaths - (N x 1) number of estimated deaths\n# Alpha - (N x m) parameter for Beta Bin\n# Beta - (N x m) parameter for Beta Bin\n# dates - (m x 1) dates reported\n# Reported - (N x m) reported so far and na for non reported\n# lag - (int) lag = 0 is only first non-holiday, lag = 1 two non holidays\n##\nfill.ReportBB.postlag <- function(deaths, Alpha, Beta, Reported, dates, lag){\n N <- length(deaths)\n m <- dim(Alpha)[2]\n holidays <- weekdays(dates)%in%c(\"Sunday\",\"Saturday\") | c(dates)%in%c(holidays.Sweden)\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:m]==F)==(lag+1))-1\n if(k==0)\n k <- m - i\n if(k+i >= m)\n next\n\n death_i <- deaths[i] + Reported[i,(i+k)]\n # use i instead of i+1 to get the latest size\n Alpha_i = Alpha[i,(i+k):m]\n Beta_i = Beta[i,(i+k):m]\n Reported_i = Reported[i,(i+k):m]\n index = is.na(Reported_i)==T\n if(sum(index)==0)\n next\n\n for(j in min(which(index)):length(Reported_i)){\n p <- rbeta(1, Alpha_i[j], Beta_i[j])\n rep_prev <- Reported_i[j-1]\n if( death_i - rep_prev>0 ){\n Reported_i[j] <- rbinom(1, size=death_i - rep_prev, prob = p) + rep_prev\n }else{Reported_i[j] <- rep_prev}\n\n }\n Reported[i,(i+k):m] = Reported_i\n }\n return(Reported)\n}\n\n##\n# fill report using binimoal beta post lag\n#\n# deaths - (N x 1) number of estimated deaths\n# Alpha - (N x m) parameter for Beta Bin\n# Beta - (N x m) parameter for Beta Bin\n# dates - (m x 1) dates reported\n# Reported - (N x m) reported so far and na for non reported\n# lag - (int) lag = 0 is only first non-holiday, lag = 1 two non holidays\n##\nfill.ReportBB.postlag_bi <- function(deaths,\n Alpha,\n Beta,\n pi_null,\n p_null,\n Reported,\n dates,\n lag){\n N <- length(deaths)\n m <- dim(Alpha)[2]\n holidays <- weekdays(dates)%in%c(\"Sunday\",\"Saturday\") | c(dates)%in%c(holidays.Sweden)\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:m]==F)==(lag+1))-1\n if(k==0)\n k <- m - i\n if(k+i >= m)\n next\n\n death_i <- deaths[i] + Reported[i,(i+k)]\n # use i instead of i+1 to get the latest size\n Alpha_i = Alpha[i,(i+k):m]\n Beta_i = Beta[i,(i+k):m]\n Reported_i = Reported[i,(i+k):m]\n index = is.na(Reported_i)==T\n if(sum(index)==0)\n next\n\n for(j in min(which(index)):length(Reported_i)){\n if(runif(1) >pi_null){\n p <- rbeta(1, Alpha_i[j], Beta_i[j])\n }else{\n p <- p_null\n }\n rep_prev <- Reported_i[j-1]\n if( death_i - rep_prev>0 ){\n Reported_i[j] <- rbinom(1, size=death_i - rep_prev, prob = p) + rep_prev\n }else{Reported_i[j] <- rep_prev}\n\n }\n Reported[i,(i+k):m] = Reported_i\n }\n return(Reported)\n}\n\n\n\n##\n# fill report\n#\n#\n##\nfill.Report <- function(deaths, P, Reported, maxusage.day){\n N <- length(deaths)\n N_2 <- dim(P)[2]\n for(i in 1:N){\n P_i = P[i,i:N_2]\n Reported_i = Reported[i,i:N_2]\n index = is.na(Reported_i)==T\n for(j in min(which(index)):length(Reported_i)){\n Reported_i[j] <- rbinom(1, size=deaths[i] - Reported_i[j-1], prob = P_i[j]) + Reported_i[j-1]\n if(i> maxusage.day){\n Reported_i[j] <- rbinom(1, size=deaths[i] - Reported_i[j-1], prob = P_i[j]) + Reported_i[j-1]\n }else{\n Reported_i[j] <- Reported_i[j-1]\n }\n }\n Reported[i,i:N_2] = Reported_i\n }\n return(Reported)\n}\n###\n#\n# posterior sampling of deaths given Prob vec\n#\n# P - (N x N) probability matrix over probability of detecting reminder\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# Predict.day - (int) which day to of reporting to predict\n# sim - (2 x 1) MCMC samples inner loop and outer loop\n# alpha - (N x 1) stepsizes\n#\n###\ndeath.givenProb <- function(P, Reported ,Predict.day = Inf,sim=c(2000,10), alpha = NULL){\n\n N <- dim(P)[1]\n if(is.null(alpha))\n alpha <- rep(4, N)\n\n deaths <- matrix(NA, nrow=sim[1], ncol = N)\n deaths_est <- apply(Reported, 1, max, na.rm=T)\n\n burnin = ceiling(0.3*sim[1])\n for(i in 1:(sim[1] + burnin -1)){\n\n res <- sample.deaths(sim[2],deaths_est, P, Reported, alpha,rep.day=Predict.day)\n deaths_est <- res$deaths\n if(i < burnin){\n alpha[res$acc/sim[2] > 0.3] <- alpha[res$acc/sim[2] > 0.3] +1\n alpha[res$acc/sim[2] < 0.3] <- alpha[res$acc/sim[2] < 0.3] -1\n alpha[alpha<1] <- 1\n }else{\n deaths[i - burnin +1,] = deaths_est\n }\n }\n return(deaths)\n}\n\n\n\n\n##\n# log liklihood of obseving report given death and prob\n# deaths - (int) true number of deaths\n# p - (n x 1) probability of report\n# report - (n x 1) reported deaths culmative each date\n##\nloglikDeathsGivenProb <- function(death, p, report){\n\n if(death < max(report,na.rm=T))\n return(-Inf)\n n <- length(p)\n if(is.na(report[1])){\n #we dont have data from day one\n\n ndeaths <- diff(report[is.na(report)==F])\n report_adj <- report[1:(n-1)]\n report_adj <- report_adj[is.na(report_adj)==F]\n }else{\n ndeaths <- c(report[1],diff(report))\n if(n>1){\n report_adj <- c(0, report[1:(n-1)])\n }else{\n report_adj <- 0\n }\n }\n\n ndeaths[ndeaths <0 ] = 0\n\n return(sum(dbinom(ndeaths, death - report_adj, prob = p[is.na(p)==F], log=T )))\n}\n\n##\n# build holiday covariates vector for holiday\n#\n##\n# holidays - (N x 1) true if day is holiday false else\n##\nbuildXholiday <- function(N,holidays){\n ##\n # base matrix\n ##\n index_base <- t(matrix(rep(holidays,N),ncol = N))\n\n index_base <- index_base[upper.tri(index_base,diag=T)]\n index_base <- 1* index_base\n #sparse matrix\n i_base <- 1:length(index_base)\n i_base <- i_base[index_base==1]\n return(sparseMatrix(j=rep(1,length(i_base)),i=i_base, dims=c(length(index_base), 1)))\n}\n\nbuildXall <- function(N){\n ##\n # base matrix\n ##\n index_base <- t(matrix(1:N^2,ncol = N, nrow=N))\n\n index_base <- index_base[upper.tri(index_base,diag=T)]\n #sparse matrix\n i_base <- 1:length(index_base)\n j_base <- 1:length(index_base)\n return(sparseMatrix(j=j_base,i=j_base))\n}\n\n\n##\n# build day mixed effect matrix\n# nDayEffects - number of speical days effect (1- first day, 2- first + second day)\n# N - number of days\n# nDayEffects - how many day covariate effect to create\n##\nbuildXmixeddayeffect <- function(N, nDayEffects = 1){\n\n index = rep(0,N)\n index[nDayEffects] = 1\n index_days <- toeplitz(index)\n index_days <- index_days[upper.tri(index_days,diag=T)]\n j_ <- 1:sum(index_days[index_days>0])\n i_base <- 1:length(index_days)\n i_ <- i_base[index_days>0]\n return(sparseMatrix(i=i_,j=j_ , dims=c(length(index_days), sum(index_days[index_days>0]))) )\n}\n##\n# building an X matrix such that each day has a fixed effect\n#\n##\nbuildXday <- function(N){\n ##\n # base matrix\n ##\n index_base <- t(matrix(rep(1:N,N),ncol = N))\n index_base <- index_base[upper.tri(index_base,diag=T)]\n #sparse matrix\n j_base <- 1:length(index_base)\n #adding mean effect\n j_ <- c(index_base, rep(N+1,length(index_base)))\n i_ <- c(j_base, 1:length(index_base))\n #day effects\n if(nDayEffects > 0){\n index_days <- toeplitz(c( N+1 + (1:nDayEffects), rep(0,N -nDayEffects)))\n index_days <- index_days[upper.tri(index_days,diag=T)]\n j_ <- c(j_, index_days[index_days>0])\n i_ <- c(i_, j_base[index_days>0])\n }\n return(sparseMatrix(i=i_,j=j_))\n}\n##\n#' split data before and after lag\n#'\n#'\n#' Reported - (N x N) number of reported deaths\n#' dates - (N x 1) dates of reporting\n#' lag - (int) how long after to report (lag = 0 is only first non-holiday, lag = 1 two non holidays,\n#' dates_not_reported - (N x 1) dayes with no reporting in\n#'\n##\nsplitlag <- function(Reported_T, dates, lag,\n dates_not_reported){\n\n holidays <- weekdays(dates)%in%c(\"Sunday\",\"Saturday\") | c(dates)%in%c(holidays.Sweden)\n N <- dim(Reported_T)[1]\n N2 <- dim(Reported_T)[2]\n Reported_O = Reported_T\n day_completed <- rep(1,N)\n for(i in 1:N){\n # which day is lag +1 number of days before holiday\n k <- which.max(cumsum(holidays[i:N2]==F)==(lag+1))-1\n if(k==0)\n k <- N2-i\n Reported_O[i, i:min(i+k, N2)] <- NA\n if(k+i0){\n death.rem[k, index] <- deaths[k]\n }\n }\n if(maxusage.day>0){\n for(i in 1:length(death.rem)){\n if(i + maxusage.day - 1 < N ){\n death.rem[i,(i+maxusage.day):N] = NA\n newreport[i,(i+maxusage.day):N] = NA\n }\n }\n }\n #removing small bugs in reporting\n newreport[death.rem <0 & is.na(death.rem)==F] = 0\n death.rem[death.rem <0& is.na(death.rem)==F] = 0\n index <- (death.rem< newreport) & is.na(death.rem) ==F & is.na(newreport)==F\n newreport[index] =death.rem[index]\n return(list(death.remain = death.rem, report.new = newreport))\n}\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim Bin(deaths[upper.tri], logit(X\\beta))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n#' $hessian - Hessian of the likelihood\n##\nloglikProb <- function(beta, death.remain, report.new, X){\n\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X <- X[index,]\n p = as.vector(1/(1+exp(-X%*%beta)))\n y <- y[index]\n n <- n[index]\n lik <- sum(dbinom(y,size = n, prob = as.vector(p), log = T))\n\n grad <- as.vector(t(X)%*%as.vector(y-n*p))\n\n Hessian <- -t(X)%*%diag(as.vector(n*p*(1-p)))%*%X\n Hessian <- diag(diag(Hessian))\n\n return(list(loglik = lik, grad = grad, Hessian = Hessian))\n}\nloglikPrior <- function(beta, n, sigma, res){\n n <- length(sigma)\n res$grad[1:n] <- res$grad[1:n]-beta[1:n]/(sigma^2)\n diag(res$Hessian) <- diag(res$Hessian) - c(1/sigma^2, rep(0,length(beta)-n))\n res$loglik <- res$loglik -sum(beta[1:n]^2/(2*sigma^2))\n return(res)\n}\n\nloglik <- function(beta,death.remain, report.new, X, sigma){\n res <- loglikProb(beta, death.remain, report.new, X)\n res <- loglikPrior(beta, n, sigma, res)\n return(res)\n}\n\n\n#####\n##\n# beta binomial part\n##\n#####\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB_mixedeffect_bi <- function(beta, death.remain, report.new, X_mu, X_M, X_mixed, sigma_mixed){\n\n p <- dim(X_mu)[2]\n p1 <- dim(X_M)[2]\n p2 <- dim(X_mixed)[2]\n beta_mu <- beta[1:p]\n beta_M <- beta[p + (1:p1)]\n beta_mixed <- beta[p + p1 + (1:p2)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X_mu <- X_mu[index,]\n X_mixed <- X_mixed[index,]\n X_M <- X_M[index,]\n mu <- 1/(1+exp(-X_mu%*%beta_mu - X_mixed%*%beta_mixed))\n M <- exp(X_M%*%beta_M)\n\n alpha <- M * mu\n beta <- M * (1-mu)\n y <- y[index]\n n <- n[index]\n\n if(max(beta)>120)\n return(list(loglik = -Inf, grad = 0))\n\n\n lik <- sum(dBB(y, size = n, alpha = alpha, beta = beta, log.p=T))\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0))\n\n ##\n #\n # mixed effect\n ##\n lik <- lik - (0.5/sigma_mixed^2) * sum(beta_mixed^2)\n ##\n # prior\n ##\n #lik <- lik - sum(exp(beta_M))\n grad_lik <- grad_dBB(y, size = n, alpha = alpha, beta = beta)\n\n grad_mu <- (M*mu * (1-mu) * grad_lik$grad_alpha)\n grad_mu <- (grad_mu - (M * mu * (1-mu) * grad_lik$grad_beta))\n grad_mixed <- t(X_mixed)%*%grad_mu - (1/sigma_mixed^2) * beta_mixed\n grad_mu <- t(X_mu)%*%grad_mu\n grad_M <- (M*mu * grad_lik$grad_alpha)\n grad_M <- grad_M + (M * (1-mu) * grad_lik$grad_beta)\n grad_M <- t(X_M)%*%grad_M #- exp(beta_M)\n grad = c(as.vector(grad_mu),as.vector(grad_M),as.vector(grad_mixed))\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0))\n return(list(loglik = lik, grad = grad))\n}\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB_bi <- function(beta, death.remain, report.new, X_mu, X_M, pi_null, p_null, z){\n\n p <- dim(X_mu)[2]\n p1 <- dim(X_M)[2]\n beta_mu <- beta[1:p]\n beta_M <- beta[p + (1:p1)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X_mu <- X_mu[index,]\n X_M <- X_M[index,]\n mu <- 1/(1+exp(-X_mu%*%beta_mu ))\n M <- exp(X_M%*%beta_M)\n\n alpha <- M * mu\n beta <- M * (1-mu)\n y <- y[index]\n n <- n[index]\n\n if(is.na(z[1]))\n z = rep(0,length(y))\n index_z <- z==0\n y_lik <- y[index_z]\n n_lik <- n[index_z]\n alpha_lik <- alpha[index_z]\n beta_lik <- beta[index_z]\n mu_lik <- mu[index_z]\n M_lik <- M[index_z]\n if(max(beta)>100)\n return(list(loglik = -Inf, grad = 0))\n\n\n lik_obs <- dBB(y, size = n, alpha = alpha, beta = beta, log.p=T)\n lik <- sum(lik_obs)\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0))\n\n ##\n # prior\n ##\n lik <- lik\n grad_lik <- grad_dBB(y_lik, size = n_lik, alpha = alpha_lik, beta = beta_lik)\n\n grad_mu <- (M_lik*mu_lik * (1-mu_lik) * grad_lik$grad_alpha)\n grad_mu <- (grad_mu - (M_lik * mu_lik * (1-mu_lik) * grad_lik$grad_beta))\n grad_mu <- t(X_mu[index_z==T,])%*%grad_mu\n grad_M <- (M_lik*mu_lik * grad_lik$grad_alpha)\n grad_M <- grad_M + (M_lik * (1-mu_lik) * grad_lik$grad_beta)\n grad_M <- t(X_M[index_z==T,])%*%grad_M\n grad = c(as.vector(grad_mu),as.vector(grad_M))\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0))\n\n\n ##\n # sample mixture\n ##\n lik_null <- dbinom(y, n, p_null, log=T)\n p_null <- log(pi_null) + lik_null\n p_full <- log(1-pi_null) + lik_obs\n p_max <- apply(cbind(p_null,p_full),1, max)\n p0 <- exp(p_null - p_max)\n p0 <- p0/(p0 + exp(p_full-p_max))\n z <- as.vector(1* (runif(length(p0)) <= p0))\n pi <- rbeta(1, 5+ sum(z==1), 5 + sum(z==0))\n p <- rbeta(1, 1 + sum(y[z==1]), 20+ sum(n[z==1])-sum(y[z==1]))\n\n return(list(loglik = lik, grad = grad, p_null= p, pi_null = pi, z = z))\n}\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB3 <- function(beta, death.remain, report.new, X_mu, X_M){\n\n p <- dim(X_mu)[2]\n p1 <- dim(X_M)[2]\n beta_mu <- beta[1:p]\n beta_M <- beta[p + (1:p1)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X_mu <- X_mu[index,]\n X_M <- X_M[index,]\n mu <- 1/(1+exp(-X_mu%*%beta_mu ))\n M <- exp(X_M%*%beta_M)\n\n alpha <- M * mu\n beta <- M * (1-mu)\n y <- y[index]\n n <- n[index]\n\n lik <- sum(dBB(y, size = n, alpha = alpha, beta = beta, log.p=T))\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0))\n\n ##\n # prior\n ##\n lik <- lik - sum(exp(beta_M))\n grad_lik <- grad_dBB(y, size = n, alpha = alpha, beta = beta)\n\n grad_mu <- (M*mu * (1-mu) * grad_lik$grad_alpha)\n grad_mu <- (grad_mu - (M * mu * (1-mu) * grad_lik$grad_beta))\n grad_mu <- t(X_mu)%*%grad_mu\n grad_M <- (M*mu * grad_lik$grad_alpha)\n grad_M <- grad_M + (M * (1-mu) * grad_lik$grad_beta)\n grad_M <- t(X_M)%*%grad_M - exp(beta_M)\n grad = c(as.vector(grad_mu),as.vector(grad_M))\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0))\n return(list(loglik = lik, grad = grad))\n}\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB_param2 <- function(beta, death.remain, report.new, X, calcH=F){\n\n p <- dim(X)[2]\n beta_1 <- beta[1:p]\n beta_2 <- beta[(p+1):(2*p)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X <- X[index,]\n mu <- 1/(1+exp(-X%*%beta_1))\n M <- exp(X%*%beta_2)\n\n alpha <- M * mu\n beta <- M * (1-mu)\n y <- y[index]\n n <- n[index]\n\n if(max(beta)>120)\n return(list(loglik = -Inf, grad = 0))\n\n\n\n lik <- sum(dBB(y, size = n, alpha = alpha, beta = beta, log.p=T))\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0))\n\n lik <- lik #- 2*sum(exp(beta_2))\n grad_lik <- grad_dBB(y, size = n, alpha = alpha, beta = beta)\n\n grad_mu <- (M*mu * (1-mu) * grad_lik$grad_alpha)\n grad_mu <- t(X)%*%(grad_mu - (M * mu * (1-mu) * grad_lik$grad_beta))\n grad_M <- (M*mu * grad_lik$grad_alpha)\n grad_M <- grad_M + (M * (1-mu) * grad_lik$grad_beta)\n grad_M <- t(X)%*%grad_M #- 2*exp(beta_2)\n grad = c(as.vector(grad_mu),as.vector(grad_M))\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0))\n return(list(loglik = lik, grad = grad))\n}\n\n\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB_mixedeffect <- function(beta, death.remain, report.new, X_mu, X_M, X_mixed, sigma_mixed){\n\n p <- dim(X_mu)[2]\n p1 <- dim(X_M)[2]\n p2 <- dim(X_mixed)[2]\n beta_mu <- beta[1:p]\n beta_M <- beta[p + (1:p1)]\n beta_mixed <- beta[p + p1 + (1:p2)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X_mu <- X_mu[index,]\n X_mixed <- X_mixed[index,]\n X_M <- X_M[index,]\n mu <- 1/(1+exp(-X_mu%*%beta_mu - X_mixed%*%beta_mixed))\n M <- exp(X_M%*%beta_M)\n\n alpha <- M * mu\n beta <- M * (1-mu)\n y <- y[index]\n n <- n[index]\n\n if(max(beta)>120)\n return(list(loglik = -Inf, grad = 0))\n\n\n lik <- sum(dBB(y, size = n, alpha = alpha, beta = beta, log.p=T))\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0))\n\n ##\n #\n # mixed effect\n ##\n lik <- lik - (0.5/sigma_mixed^2) * sum(beta_mixed^2)\n ##\n # prior\n ##\n #lik <- lik - sum(exp(beta_M))\n grad_lik <- grad_dBB(y, size = n, alpha = alpha, beta = beta)\n\n grad_mu <- (M*mu * (1-mu) * grad_lik$grad_alpha)\n grad_mu <- (grad_mu - (M * mu * (1-mu) * grad_lik$grad_beta))\n grad_mixed <- t(X_mixed)%*%grad_mu - (1/sigma_mixed^2) * beta_mixed\n grad_mu <- t(X_mu)%*%grad_mu\n grad_M <- (M*mu * grad_lik$grad_alpha)\n grad_M <- grad_M + (M * (1-mu) * grad_lik$grad_beta)\n grad_M <- t(X_M)%*%grad_M #- exp(beta_M)\n grad = c(as.vector(grad_mu),as.vector(grad_M),as.vector(grad_mixed))\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0))\n return(list(loglik = lik, grad = grad))\n}\n\n\n##\n# likelihood observations given deaths and probabilites\n# model is:\n# newreport[upper.tri] \\sim BB(deaths[upper.tri], exp(X\\beta_1), exp(X\\beta_2))\n#\n#' @return obj - list\n#' $loglik - logliklihood\n#' $grad - gradient\n##\nloglikProbBB <- function(beta, death.remain, report.new, X, calcH=F){\n\n p <- dim(X)[2]\n beta_1 <- beta[1:p]\n beta_2 <- beta[(p+1):(2*p)]\n N <- dim(report.new)[1]\n\n index <- upper.tri(death.remain,diag = T)\n y = report.new[index]\n n = death.remain[index]\n index = is.na(y)==F & is.na(n)==F\n X <- X[index,]\n alpha <- exp(X%*%beta_1)\n beta <- exp(X%*%beta_2) #unfortunate name\n if(min(1/(alpha+beta)) <10^-3)\n return(list(loglik = -Inf, grad = 0, Hessian = 0))\n y <- y[index]\n n <- n[index]\n\n lik <- sum(dBB(y, size = n, alpha = alpha, beta = beta, log.p=T))\n if(is.na(lik))\n return(list(loglik = -Inf, grad = 0, Hessian = 0))\n\n grad_lik <- grad_dBB(y, size = n, alpha = alpha, beta = beta)\n grad_alpha <- as.vector(t(X)%*%(alpha*grad_lik$grad_alpha))\n grad_beta <- as.vector(t(X)%*%(beta*grad_lik$grad_beta))\n if(calcH){\n H_ <- Hessian_dBB(y, size = n, alpha = alpha, beta = beta)\n H_12 <- t(X)%*%diag(as.vector(alpha*beta*H_$grad_alpha_beta))%*%X\n H_11 <- t(X)%*%diag(as.vector(alpha^2*H_$grad_alpha_alpha))%*%X\n H_22 <- t(X)%*%diag(as.vector(beta^2*H_$grad_beta_beta))%*%X\n Hessian <- rbind(cbind(H_11, H_12) ,\n cbind(H_12, H_22) )\n Hessian <- diag(diag(Hessian) )\n diag(Hessian) <- diag(Hessian)\n }else{\n Hessian =NULL\n }\n grad = c(grad_alpha,grad_beta)\n if(sum(is.na(grad))>0)\n return(list(loglik = -Inf, grad = 0, Hessian = 0))\n return(list(loglik = lik, grad = grad, Hessian = Hessian))\n}\n##\n# PRobability of beta binomial\n##\ndBB<- function(x, size, alpha, beta, log.p = F){\n const = lgamma(size + 1) - lgamma(x + 1) -\n lgamma(size - x + 1)\n ld <- const +\n lgamma(x + alpha) + lgamma(size - x + beta) -\n lgamma(size + alpha + beta) +\n lgamma(alpha + beta) -\n lgamma(alpha) - lgamma(beta)\n if(log.p==F){\n return(exp(ld))\n }\n return(ld)\n}\n##\n# gradient of log of probability beta binomial\n# return list,\n# [[1]] grad alpha\n# [[2]] grad beta\n##\ngrad_dBB<- function(x, size, alpha, beta){\n grad_alpha <- digamma(x + alpha) -\n digamma(size + alpha + beta) +\n digamma(alpha + beta) -\n digamma(alpha)\n grad_beta <- digamma(size - x + beta) -\n digamma(size + alpha + beta) +\n digamma(alpha + beta) -\n digamma(beta)\n return(list(grad_alpha = grad_alpha,\n grad_beta = grad_beta ))\n}\n##\n# Hessian of log of probability beta binomial\n# return list,\n# [[1]] grad alpha\n# [[2]] grad beta\n##\nHessian_dBB<- function(x, size, alpha, beta){\n grad_alpha_alpha <- trigamma(x + alpha) -\n trigamma(size + alpha + beta) +\n trigamma(alpha + beta) -\n trigamma(alpha)\n grad_beta_beta <- trigamma(size - x + beta) -\n trigamma(size + alpha + beta) +\n trigamma(alpha + beta) -\n trigamma(beta)\n\n grad_alpha_beta <- -trigamma(size + alpha + beta) +\n trigamma(alpha + beta)\n return(list(grad_alpha_alpha = grad_alpha_alpha,\n grad_beta_beta = grad_beta_beta,\n grad_alpha_beta = grad_alpha_beta))\n}\n\n##\n# log liklihood of obseving report given death and prob\n# density is Beta binomial\n# deaths - (int) true number of deaths\n# alpha - (n x 1) bb parameter 1\n# beta - (n x 1) bb parameter 2\n# report - (n x 1) reported deaths culmative each date\n##\nloglikDeathsGivenProbBB <- function(death, alpha, beta, report){\n\n if(death < max(report,na.rm=T))\n return(-Inf)\n n <- length(alpha)\n if(is.na(report[1])){\n #we dont have data from day one\n\n ndeaths <- diff(report[is.na(report)==F])\n report_adj <- report[1:(n-1)]\n report_adj <- report_adj[is.na(report_adj)==F]\n }else{\n ndeaths <- c(report[1],diff(report))\n if(n>1){\n report_adj <- c(0, report[1:(n-1)])\n }else{\n report_adj <- 0\n }\n }\n\n ndeaths[ndeaths <0 ] = 0\n\n return(sum(dBB(x =ndeaths,\n size = death - report_adj,\n alpha = alpha[is.na(alpha)==F],\n beta = beta[is.na(alpha)==F],\n log.p=T)))\n}\n\n\n##\n# log liklihood of obseving report given death and prob\n# density is Beta binomial\n# deaths - (int) true number of deaths\n# alpha - (n x 1) bb parameter 1\n# beta - (n x 1) bb parameter 2\n# report - (n x 1) reported deaths culmative each date\n##\nloglikDeathsGivenProbBB_bi <- function(death, alpha, beta, pi_null,p_null,report){\n\n if(death < max(report,na.rm=T))\n return(-Inf)\n n <- length(alpha)\n if(is.na(report[1])){\n #we dont have data from day one\n\n ndeaths <- diff(report[is.na(report)==F])\n report_adj <- report[1:(n-1)]\n report_adj <- report_adj[is.na(report_adj)==F]\n }else{\n ndeaths <- c(report[1],diff(report))\n if(n>1){\n report_adj <- c(0, report[1:(n-1)])\n }else{\n report_adj <- 0\n }\n }\n\n ndeaths[ndeaths <0 ] = 0\n p <- rep(0, length(ndeaths))\n\n log1 <- dBB(x =ndeaths,\n size = death - report_adj,\n alpha = alpha[is.na(alpha)==F],\n beta = beta[is.na(alpha)==F],\n log.p=T)\n #p_ <- rep(0,length(log1))\n #p_[1:min(2,length(ndeaths))] =log1[1:min(2,length(ndeaths))]\n #if(length(ndeaths)>2){\n # p1 <- log(1-pi_null) + log1[3:length(ndeaths)]\n # p2 <- log(pi_null) + dbinom(ndeaths[3:length(ndeaths)], death - report_adj[3:length(ndeaths)],prob=p_null,log = T)\n # p_[3:length(ndeaths)] <- log( exp(p1) + exp(p2))\n #}\n p1 <- log(1-pi_null) + log1\n p2 <- log(pi_null) + dbinom(ndeaths, death - report_adj,prob=p_null,log = T)\n p_ <- log( exp(p1) + exp(p2))\n return(sum(p_))\n}\n\n###\n#\n# posterior sampling of deaths given Prob vec\n#\n# alpha - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# beta - (N x N) matrix of beta binom parameter (only upper triangular part relevant)\n# Reported - (N x N) matrix of reported deaths cumlative (only upper triangular relevant)\n# Predict.day - (int) which day to of reporting to predict\n# sim - (2 x 1) MCMC samples inner loop and outer loop\n# alpha - (N x 1) stepsizes\n# prior - (function) prior for N (needs use N and i)\n#\n###\ndeath.givenParamBB <- function(alpha, beta, Reported,Predict.day = Inf,sim=c(2000,10), alpha.MCMC = NULL,\n use.prior=F,\n prior=NULL){\n\n N <- dim(alpha)[1]\n if(is.null(alpha.MCMC))\n alpha.MCMC <- rep(4, N)\n\n deaths <- matrix(NA, nrow=sim[1], ncol = N)\n deaths_est <- apply(Reported, 1, max, na.rm=T)\n\n burnin = ceiling(0.3*sim[1])\n for(i in 1:(sim[1] + burnin -1)){\n res <- sample.deathsBB(sim[2],\n deaths_est,\n alpha,\n beta,\n Reported,\n alpha.MCMC,\n rep.day=Predict.day,\n use.prior=use.prior,\n prior= prior)\n deaths_est <- res$deaths\n if(i < burnin){\n alpha.MCMC[res$acc/sim[2] > 0.3] <- alpha.MCMC[res$acc/sim[2] > 0.3] +1\n alpha.MCMC[res$acc/sim[2] < 0.3] <- alpha.MCMC[res$acc/sim[2] < 0.3] -1\n alpha.MCMC[alpha.MCMC<1] <- 1\n }else{\n deaths[i - burnin +1,] = deaths_est\n }\n }\n return(deaths)\n}\n\n###\n#' setup up data uk covarites data,\n#' @param dates_report - (N x 1) which days are reports on\n#' @param predict.day - (int) how many days back are predictied\n#' @param unique.prob - (int) how many lags have there own probability\n##\n\n\n##\n# buidling the X matrix\n#\n#\n# unique.prob - (int) how many of days shall we have unique probabilites\n##\nsetup_data <- function(N, Predict.day, dates_report, unique.prob=NULL){\n\n X <- buildXdayeffect(N,Predict.day)\n #holidays and weekends\n\n result$dates_report <- as.Date(dates_report)\n\n if(is.null(unique.prob)==F)\n X <- cbind(X[,1:unique.prob,drop=F],rowSums(X[,1:unique.prob,drop=F])==0)\n\n holidays <- weekdays(dates_report)%in%c(\"Sunday\",\"Saturday\") | c(dates_report)%in%c(holidays.Sweden)\n holiday.yesterday <- weekdays(dates_report - 1)%in%c(\"Sunday\",\"Saturday\") |\n (result$dates_report-1)%in%c(holidays.Sweden)\n Xhol <- buildXholiday(N,holidays - (holiday.yesterday*holidays==T))\n Xhol.sunday <- buildXholiday(N,holiday.yesterday*holidays==T)\n Xhol.yesterday <-buildXholiday(N,holiday.yesterday - (holiday.yesterday*holidays==T) )\n\n X_dim <- dim(X)[2]\n X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday, (Xhol+Xhol.sunday)*X[,1])\n colnames(X) <- c(paste('lag_',0:(X_dim-1),sep=''),'holiday','sunday','holiday_yesterday','lag0_hol')\n return(X)\n}\n\n##\n# buidling the X matrix\n#\n#\n# unique.prob - (int) how many of days shall we have unique probabilites\n##\nsetup_data_lag <- function(N, Predict.day, dates_report, unique.prob=NULL){\n\n X <- buildXdayeffect(N,Predict.day)\n #holidays and weekends\n\n result$dates_report <- as.Date(dates_report)\n\n if(is.null(unique.prob)==F)\n X <- cbind(X[,1:unique.prob,drop=F],rowSums(X[,1:unique.prob,drop=F])==0)\n\n holidays <- weekdays(dates_report)%in%c(\"Sunday\",\"Saturday\") | c(dates_report)%in%c(holidays.Sweden)\n holiday.yesterday <- weekdays(dates_report - 1)%in%c(\"Sunday\",\"Saturday\") |\n (result$dates_report-1)%in%c(holidays.Sweden)\n Xhol <- buildXholiday(N,holidays - (holiday.yesterday*holidays==T))\n Xhol.sunday <- buildXholiday(N,holiday.yesterday*holidays==T)\n Xhol.yesterday <-buildXholiday(N,holiday.yesterday - (holiday.yesterday*holidays==T) )\n X.Wednesday <-buildXholiday(N, weekdays(dates_report)%in%c('Wednesday') )\n #X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday, Xhol*X[,1],X.Wednesday-X.Wednesday*Xhol)\n X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday, Xhol*X[,1])\n\n return(X)\n}\n##\n# buidling the X matrix\n#\n#\n# unique.prob - (int) how many of days shall we have unique probabilites\n##\nsetup_data_postlag <- function(N, lag, Predict.day, dates_report, unique.prob=NULL){\n if(Predict.day==0){\n X <- matrix(1, nrow=N*(N+1)/2, ncol=1+lag+2)\n unique.prob= NULL\n }else{\n X <- buildXdayeffect(N,Predict.day+lag+2)\n }\n if(lag>0)\n X <- X[,-(1:(lag+2)),drop=F]\n #holidays and weekends\n\n result$dates_report <- as.Date(dates_report)\n\n if(is.null(unique.prob)==F)\n X <- cbind(X[,1:unique.prob,drop=F],rowSums(X[,1:unique.prob,drop=F])==0)\n\n holidays <- weekdays(dates_report)%in%c(\"Sunday\",\"Saturday\") | c(dates_report)%in%c(holidays.Sweden)\n holiday.yesterday <- weekdays(dates_report - 1)%in%c(\"Sunday\",\"Saturday\") |\n (result$dates_report-1)%in%c(holidays.Sweden)\n Xhol <- buildXholiday(N,holidays - (holiday.yesterday*holidays==T))\n Xhol.sunday <- buildXholiday(N,holiday.yesterday*holidays==T)\n Xhol.yesterday <-buildXholiday(N,holiday.yesterday - (holiday.yesterday*holidays==T) )\n #X.Wednesday <-buildXholiday(N, weekdays(dates_report)%in%c('Wednesday') )\n #X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday, Xhol*X[,1],X.Wednesday-X.Wednesday*Xhol)\n X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday)\n\n return(X)\n}\n\n##\n# buidling the X matrix\n#\n#\n# unique.prob - (int) how many of days shall we have unique probabilites\n##\nsetup_data_postlag2 <- function(N, lag, params, dates_report){\n if(params==0){\n X <- matrix(1, nrow=N*(N+1)/2, ncol=1)\n unique.prob= 0\n }else{\n X_ <- matrix(0, nrow=N, ncol = N)\n holidays <- weekdays(dates_report)%in%c(\"Sunday\",\"Saturday\") | c(dates_report)%in%c(holidays.Sweden)\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:N]==F)==(lag+1))-1\n for(p in 1:params){\n if((i+k +p) <= N)\n X_[i,(i+k +p)] <- p\n }\n }\n X_ <- X_[upper.tri(X_,diag=T)]\n j_ <- X_[X_>0]\n i_base <- 1:length(X_)\n i_ <- i_base[X_>0]\n X <- sparseMatrix(i=i_,j=j_ , dims=c(length(X_), max(j_)) )\n unique.prob = max(j_)\n }\n\n\n\n #holidays and weekends\n\n result$dates_report <- as.Date(dates_report)\n\n if(unique.prob)\n X <- cbind(X[,1:unique.prob,drop=F],rowSums(X[,1:unique.prob,drop=F])==0)\n\n holidays <- weekdays(dates_report)%in%c(\"Sunday\",\"Saturday\") | c(dates_report)%in%c(holidays.Sweden)\n holiday.yesterday <- weekdays(dates_report - 1)%in%c(\"Sunday\",\"Saturday\") |\n (result$dates_report-1)%in%c(holidays.Sweden)\n Xhol <- buildXholiday(N,holidays - (holiday.yesterday*holidays==T))\n Xhol.sunday <- buildXholiday(N,holiday.yesterday*holidays==T)\n Xhol.yesterday <-buildXholiday(N,holiday.yesterday - (holiday.yesterday*holidays==T) )\n X <- cbind(X, Xhol, Xhol.sunday, Xhol.yesterday)\n\n return(X)\n}\n\nsetup_data_mixture_cov <- function(N, lag, dates_report){\n\n X_ <- matrix(0, nrow=N, ncol = N)\n holidays <- weekdays(dates_report)%in%c(\"Sunday\")\n for(i in 1:N){\n k <- which.max(cumsum(holidays[i:N]==F)==(lag+1))-1\n if(i+k < N)\n X_[i,(i+k+1):N] = (i+k+1):N\n }\n X_[,holidays==T]=0\n return(X_)\n}\nsetup_all_days <- function(N){\n\n X_ <- matrix(0, nrow=N, ncol = N)\n for(i in 1:N){\n X_[i,i:N] = i:N\n }\n X <- X_[upper.tri(X_,diag=T)]\n return(X)\n}\n\n\nsetup_data_mixed_effect <- function(N, lag, dates_report){\n X_ <- setup_data_mixture_cov(N, lag, dates_report)\n X_ <- X_[upper.tri(X_,diag=T)]\n X_ <- as.integer(factor(X_))-1\n X <- matrix(0, nrow=length(X_), ncol = max(X_))\n for(i in 1:max(X_)){\n X[,i] <- X_==i\n }\n return(X)\n}\n", "meta": {"hexsha": "feea2119b436fbd4888ec54f5e2cd181d987dd82", "size": 48194, "ext": "r", "lang": "R", "max_stars_repo_path": "src/util/util.r", "max_stars_repo_name": "adamaltmejd/covid_reporting_delay_prediction", "max_stars_repo_head_hexsha": "d518e978b296fca3d99089c01f3d56ac09dc8e17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/util.r", "max_issues_repo_name": "adamaltmejd/covid_reporting_delay_prediction", "max_issues_repo_head_hexsha": "d518e978b296fca3d99089c01f3d56ac09dc8e17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/util.r", "max_forks_repo_name": "adamaltmejd/covid_reporting_delay_prediction", "max_forks_repo_head_hexsha": "d518e978b296fca3d99089c01f3d56ac09dc8e17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4832384567, "max_line_length": 119, "alphanum_fraction": 0.5904676931, "num_tokens": 15534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46489592420587755}} {"text": "## get redshift offsets from a data cube or stacked rss file\n\nregrid <- function(lambda.out, lib) {\n lambda.in <- lib$lambda\n nc <- ncol(lib)\n lib.out <- matrix(NA, length(lambda.out), nc)\n lib.out[,1] <- lambda.out\n for (i in 2:nc) {\n lib.out[,i] <- approx(lambda.in, lib[,i], xout=lambda.out)$y\n }\n colnames(lib.out) <- colnames(lib)\n data.frame(lib.out)\n}\n\n\ngetdz <- function(gdat, lib, snrthresh=5, nlthresh=2000, dzlim=0.003, searchinterval=1e-4) {\n dims <- dim(gdat$flux)\n nr <- dims[1]\n nc <- dims[2]\n dz <- matrix(NA, nr, nc)\n dz.err <- matrix(NA, nr, nc)\n z <- gdat$meta$z\n lambda <- gdat$lambda\n fmla <- as.formula(paste(\"f ~\", paste(names(lib)[-1], collapse=\"+\")))\n fn <- function(x) {\n lambda.out <- lambda/(1+z+x)\n lib.out <- regrid(lambda.out, lib)\n lfit <- lm(fmla, data=lib.out, weights=iv)\n deviance(lfit)\n }\n fn_v <- Vectorize(fn)\n z_search <- seq(-dzlim, dzlim, by=searchinterval)\n \n for (i in 1:nr) {\n for (j in 1:nc) {\n if (is.na(gdat$snr[i,j]) || gdat$snr[i,j]<=snrthresh) next\n f <- gdat$flux[i, j, ]\n if (length(which(!is.na(f))) < nlthresh) next\n iv <- gdat$ivar[i, j, ]\n dev_grid <- fn_v(z_search)\n z0 <- z_search[which.min(dev_grid)]\n bestz <- Rsolnp::solnp(pars=z0, fun=fn, \n LB=z0-searchinterval, UB=z0+searchinterval, \n control=list(trace=0))\n dz[i,j] <- bestz$pars\n dz.err[i,j] <- sqrt(2./bestz$hessian)\n }\n }\n list(dz=dz, dz.err=dz.err)\n}\n\n## peculiar velocity\n\nvrel <- function(z, zbar) {\n 299792.458*(z-zbar)/(1+zbar)\n}\n\n## simple 2D spatial interpolation\n\nfillpoly <- function(ra, dec, zvals, dxy=0.5) {\n ny <- max(round((max(dec)-min(dec))*3600/dxy), 100)\n nx <- ny\n allok <- complete.cases(ra, dec, zvals)\n zsurf <- akima::interp(x=ra[allok], y=dec[allok], z=zvals[allok], \n linear=FALSE, nx=nx, ny=ny)\n list(ra=zsurf$x, dec=zsurf$y, z=zsurf$z)\n}\n\n## an image function using ggplot2\n \nggimage <- function(zmat, x=NULL, y=NULL, col=viridis::viridis(256),\n xlab=NULL, ylab=NULL, legend=NULL, title=NULL,\n xrev=FALSE, yrev=FALSE, asp=1,\n addContour=FALSE, binwidth=NULL\n ) {\n require(ggplot2)\n if (is.null(x)) x <- 1:nrow(zmat)\n if (is.null(y)) y <- 1:ncol(zmat)\n if (!is.null(dim(x))) {\n x <- colMeans(x)\n y <- rowMeans(y)\n }\n xy <- expand.grid(x,y)\n df <- data.frame(cbind(xy, as.vector(zmat)))\n names(df) <- c(\"x\",\"y\",\"z\")\n g1 <- ggplot(df, aes(x=x, y=y, z=z)) + \n geom_raster(aes(fill=z)) + \n scale_fill_gradientn(colors=col, na.value=\"#FFFFFF00\") +\n coord_fixed(ratio = asp)\n if (addContour) {\n if (!is.null(binwidth)) {\n g1 <- g1 + geom_contour(binwidth=binwidth, na.rm=TRUE)\n } else {\n g1 <- g1 + geom_contour(na.rm=TRUE)\n }\n }\n if (xrev) g1 <- g1 + scale_x_reverse()\n if (yrev) g1 <- g1 + scale_y_reverse()\n if (!is.null(xlab)) {\n g1 <- g1 + xlab(xlab)\n }\n if (!is.null(ylab)) {\n g1 <- g1 + ylab(ylab)\n }\n if (!is.null(legend)) {\n g1 <- g1 + labs(fill=legend)\n }\n if (!is.null(title)) {\n g1 <- g1 + ggtitle(title)\n }\n g1\n}\n\nrainbow <- c(\"blue\", \"cyan\", \"green\", \"yellow\", \"red\")\n\n## disk galaxy rotation curve model\n\nvrot <- function(gdat.stack, dz.stack, phi.guess, sd.phi.guess=10,\n ci.guess=0.7, sd.ci.guess=0.1,\n sd.kc0=0.5,\n order=3, N_r=100,\n r_eff=1, remax=1.5, v_norm=100, PLOTS=TRUE,\n smodel=NULL,\n stanfile=\"vrot.stan\", stanfiledir=\".\", \n seed=220755, iter=2000, warmup=1000,\n chains=4, cores=4,\n control=list(adapt_delta=0.975, max_treedepth=15)) {\n require(rstan)\n require(ggplot2)\n v <- vrel(dz.stack$dz+gdat.stack$meta$z, gdat.stack$meta$z)\n v_sample <- v[!is.na(v)]\n dv <- (dz.stack$dz.err/dz.stack$dz)*v\n df <- data.frame(x=gdat.stack$xpos, y=gdat.stack$ypos, v=v, dv=dv)\n df <- df[complete.cases(df),]\n rmax <- max(sqrt(gdat.stack$xpos^2+gdat.stack$ypos^2)[!is.na(dz.stack$dz)])\n if (rmax %% 2 != 0) rmax = rmax+1\n r_norm <- r_eff*remax\n r_post <- seq(0, 0.99, length=N_r)*rmax/r_norm\n \n vlos_data <- list(order=order, N=nrow(df), x=df$x/r_norm, y=df$y/r_norm, \n v=df$v/v_norm, dv=df$dv/v_norm, \n phi0=cos(phi.guess*pi/180), sd_phi0=sin(phi.guess*pi/180)*sd.phi.guess*pi/180, \n si0 = sqrt(1-ci.guess^2), sd_si0=sd.ci.guess,\n sd_kc0 = sd.kc0,\n r_norm=r_norm, v_norm=v_norm,\n N_r=N_r, r_post=r_post)\n \n \n inits <- function(chain_id) {\n p <- phi.guess*pi/180\n si <- sqrt(1-ci.guess^2)\n list(phi=p, si=si, x_c=0., y_c=0., v_sys=0.)\n }\n if (!is.null(smodel)) {\n stanfit <- sampling(smodel, data=vlos_data, init=inits, seed=seed,\n iter=iter, warmup=warmup, control=control, chains=chains, cores=cores)\n } else {\n stanfit <- stan(file=file.path(stanfiledir, stanfile), data=vlos_data, init=inits, \n seed=seed, iter=iter, warmup=warmup, control=control, chains=chains, cores=cores)\n }\n post <- extract(stanfit)\n vf_obs <- fillpoly(gdat.stack$ra.f, gdat.stack$dec.f, v)\n v_model <- rep(NA, length(v))\n v_model[!is.na(v)] <- colMeans(post$v_model)*v_norm\n vf_model <- fillpoly(gdat.stack$ra.f, gdat.stack$dec.f, v_model)\n r_q <- apply(post$r*remax, 2, quantile, probs=c(0.025, 0.5, 0.975))\n rownames(r_q) <- paste(\"r\", rownames(r_q), sep=\"_\")\n v_r_q <- apply(post$v_rot*v_norm, 2, quantile, probs=c(0.025, 0.5, 0.975))\n rownames(v_r_q) <- paste(\"v_rot\", rownames(v_r_q), sep=\"_\")\n v_e_q <- apply(post$v_exp*v_norm, 2, quantile, probs=c(0.025, 0.5, 0.975))\n rownames(v_e_q) <- paste(\"v_exp\", rownames(v_e_q), sep=\"_\")\n df_v <- data.frame(cbind(t(r_q), t(v_r_q), t(v_e_q)))\n graphs <- list()\n i <- 1\n df <- data.frame(x=gdat.stack$xpos, y=gdat.stack$ypos, v=v)\n graphs[[i]] <- ggplot(df) + geom_point(aes(x=x, y=y, color=v), size=7) +\n scale_colour_gradientn(colors=rainbow, na.value=\"gray95\") +\n coord_fixed(ratio=1) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": observed fiber velocities\"))\n i <- i+1 \n graphs[[i]] <- ggimage(vf_obs$z, vf_obs$ra, vf_obs$dec, col=rainbow, asp=1/cos(pi*gdat.stack$meta$dec/180), addContour=T) + \n xlim(rev(range(gdat.stack$ra.f))) + ylim(range(gdat.stack$dec.f)) +\n xlab(expression(alpha)) + ylab(expression(delta)) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": observed velocity field\"))\n i <- i+1\n graphs[[i]] <- ggimage(vf_model$z, vf_model$ra, vf_model$dec, col=rainbow, asp=1/cos(pi*gdat.stack$meta$dec/180), addContour=T) + \n xlim(rev(range(gdat.stack$ra.f))) + ylim(range(gdat.stack$dec.f)) +\n xlab(expression(alpha)) + ylab(expression(delta)) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": model velocity field\"))\n if (exists(\"v_res\", post)) {\n v_res <- rep(NA, length(v))\n v_res[!is.na(v)] <- colMeans(post$v_res)*v_norm\n vf_res <- fillpoly(gdat.stack$ra.f, gdat.stack$dec.f, v_res)\n } else {\n vf_res <- list(z=vf_obs$z-vf_model$z, ra=vf_obs$ra, dec=vf_obs$dec)\n }\n i <- i+1\n graphs[[i]] <- ggimage(vf_res$z, vf_res$ra, vf_res$dec, asp=1/cos(pi*gdat.stack$meta$dec/180), addContour=T) + \n xlim(rev(range(gdat.stack$ra.f))) + ylim(range(gdat.stack$dec.f)) +\n xlab(expression(alpha)) + ylab(expression(delta)) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": residual velocity field\"))\n df1 <- data.frame(r=as.vector(abs(post$r))*remax, v_rot=as.vector(post$v_rot)*v_norm, v_exp=as.vector(post$v_exp)*v_norm)\n i <- i+1\n graphs[[i]] <- ggplot(df_v) + geom_point(aes(x=r_50., y=v_rot_50.)) +\n geom_errorbar(aes(x=r_50., ymin=v_rot_2.5., ymax=v_rot_97.5.)) +\n geom_errorbarh(aes(x=r_50., y=v_rot_50., xmin=r_2.5., xmax=r_97.5.)) +\n stat_density_2d(aes(x=r, y=v_rot, fill=..level..), data=df1, geom=\"polygon\", alpha=0.5, show.legend=FALSE) + \n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": joint distribution of r, v_rot\")) +\n xlab(expression(r/r[eff]))\n i <- i+1\n graphs[[i]] <- ggplot(df_v) + geom_point(aes(x=r_50., y=v_exp_50.)) +\n geom_errorbar(aes(x=r_50., ymin=v_exp_2.5., ymax=v_exp_97.5.)) +\n geom_errorbarh(aes(x=r_50., y=v_exp_50., xmin=r_2.5., xmax=r_97.5.)) +\n stat_density_2d(aes(x=r, y=v_exp, fill=..level..), data=df1, geom=\"polygon\", alpha=0.5, show.legend=FALSE) + \n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": joint distribution of r, v_exp\")) +\n xlab(expression(r/r[eff]))\n if(exists(\"vrot_post\", post)) {\n \t vq <- t(apply(v_norm * post$vrot_post, 2, quantile, probs=c(0.025, 0.5, 0.975)))\n \t df2 <- data.frame(r=r_post*remax, ymin=vq[,\"2.5%\"], ymed=vq[,\"50%\"], ymax=vq[,\"97.5%\"])\n i <- i+1\n \t graphs[[i]] <- ggplot(df2) + geom_line(aes(x=r, y=ymed)) + geom_ribbon(aes(x=r, ymin=ymin, ymax=ymax), alpha=0.5) +\n xlab(expression(r/r[eff]))\n } else {\n \t df2 <- NULL\n }\n if (PLOTS) {\n \t for (i in seq_along(graphs)) {\n \t \t x11()\n \t \t plot(graphs[[i]])\n \t }\n }\n list(stanfit=stanfit, r_eff=r_eff, remax=remax, v_norm=v_norm, vlos_data=vlos_data, \n v_sample=v_sample, vf_obs=vf_obs, vf_model=vf_model, vf_res=vf_res, df_v=df_v, df1=df1, df2=df2,\n graphs=graphs\n )\n}\n\n## disk galaxy rotation curve model -- gaussian process version\n \nvrot_gp <- function(gdat.stack, dz.stack, phi.guess, sd.phi.guess=10,\n ci.guess=0.7, sd.ci.guess=0.1,\n sd.kc0=0.5,\n order=3, N_xy=25^2,\n r_eff=1, remax=1.5, v_norm=100, PLOTS=TRUE,\n smodel=NULL,\n stanfile=\"vrot_gp.stan\", stanfiledir=\"~/vrot_stanmodels\", \n seed=220755, iter=1000, warmup=500,\n chains=4, cores=4,\n control=list(adapt_delta=0.9, max_treedepth=10)) {\n require(rstan)\n require(spmutils)\n require(ggplot2)\n require(akima)\n v <- vrel(dz.stack$dz+gdat.stack$meta$z, gdat.stack$meta$z)\n v_sample <- v[!is.na(v)]\n dv <- (dz.stack$dz.err/dz.stack$dz)*v\n df <- data.frame(x=gdat.stack$xpos, y=gdat.stack$ypos, v=v, dv=dv)\n allok <- complete.cases(df)\n df <- df[allok,]\n \n n_r <- round(sqrt(N_xy))\n N_xy <- n_r^2\n rho <- seq(1/n_r, 1, length=n_r)\n theta <- seq(0, (n_r-1)*2*pi/n_r, length=n_r)\n rt <- expand.grid(theta, rho)\n x_pred <- rt[,2]*cos(rt[,1])\n y_pred <- rt[,2]*sin(rt[,1])\n r_norm <- r_eff*remax\n \n vlos_data <- list(order=order, N=nrow(df), x=df$x/r_norm, y=df$y/r_norm, \n v=df$v/v_norm, dv=df$dv/v_norm, \n phi0=phi.guess*pi/180, sd_phi0=sd.phi.guess*pi/180, \n ci0 = ci.guess, sd_ci0=sd.ci.guess,\n sd_kc0 = sd.kc0,\n r_norm=r_norm, v_norm=v_norm,\n N_xy=N_xy, N_r=n_r, x_pred=x_pred, y_pred=y_pred\n )\n \n \n inits <- function(chain_id) {\n p <- phi.guess*pi/180\n ci <- ci.guess\n list(phi=p, cos_i=ci, x_c=0., y_c=0., v_sys=0.)\n }\n if (!is.null(smodel)) {\n stanfit <- sampling(smodel, data=vlos_data, init=inits, seed=seed,\n iter=iter, warmup=warmup, control=control, chains=chains, cores=cores)\n } else {\n stanfit <- stan(file=file.path(stanfiledir, stanfile), data=vlos_data, init=inits, \n seed=seed, iter=iter, warmup=warmup, control=control, chains=chains, cores=cores)\n }\n post <- extract(stanfit)\n graphs <- list()\n vf_model <- rep(NA, length(gdat.stack$xpos))\n vf_res <- rep(NA, length(gdat.stack$ypos))\n vf_model[allok] <- colMeans(post$vf_model)*v_norm\n vf_res[allok] <- colMeans(post$vf_res)*v_norm\n df <- data.frame(x=gdat.stack$xpos, y=gdat.stack$ypos, v=v, vf_model=vf_model, vf_res=vf_res)\n g <- 1\n graphs[[g]] <- ggplot(df) + geom_point(aes(x=x, y=y, color=v), size=7) +\n scale_colour_gradientn(colors=rainbow, na.value=\"gray95\") +\n coord_fixed(ratio=1) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": observed fiber velocities\"))\n g <- g+1\n df <- df[allok,]\n df1 <- akima::interp(x=df$x, y=df$y, z=df$vf_model, nx=200, ny=200)\n graphs[[g]] <- ggimage(df1$z, df1$x, df1$y, col=rainbow, xlab=\"x\", ylab=\"y\", legend=\"vf_model\", addContour=TRUE)\n g <- g+1\n df1 <- akima::interp(x=df$x, y=df$y, z=df$vf_res, nx=200, ny=200)\n graphs[[g]] <- ggimage(df1$z, df1$x, df1$y, xlab=\"x\", ylab=\"y\", legend=\"vf_res\", addContour=TRUE)\n \n v_pred <- colMeans(post$v_pred)\n sd_v_pred <- apply(post$v_pred, 2, sd)\n v_model <- colMeans(post$v_model)\n v_res <- colMeans(post$v_res)\n x <- x_pred*r_norm\n y <- y_pred*r_norm\n rho <- c(0, rho)*remax\n df <- akima::interp(x=x, y=y, z=v_pred, nx=200, ny=200)\n g <- g+1\n graphs[[g]] <- ggimage(df$z, df$x, df$y, col=rainbow, xlab=\"x\", ylab=\"y\", legend=\"v_pred\", addContour=TRUE)\n df <- akima::interp(x=x, y=y, z=v_model, nx=200, ny=200)\n g <- g+1\n graphs[[g]] <- ggimage(df$z, df$x, df$y, col=rainbow, xlab=\"x\", ylab=\"y\", legend=\"v_model\", addContour=TRUE)\n df <- akima::interp(x=x, y=y, z=v_res, nx=200, ny=200)\n g <- g+1\n graphs[[g]] <- ggimage(df$z, df$x, df$y, xlab=\"x\", ylab=\"y\", legend=\"v_res\", addContour=TRUE)\n df <- akima::interp(x=x, y=y, z=sd_v_pred, nx=200, ny=200)\n g <- g+1\n graphs[[g]] <- ggimage(df$z, df$x, df$y, xlab=\"x\", ylab=\"y\", legend=\"sd_v_pred\", addContour=TRUE)\n vrot_pred <- post$vrot_pred\n vexp_pred <- post$vexp_pred\n v_r_q <- data.frame(cbind(rho, t(apply(vrot_pred, 2, quantile, probs=c(.025, 0.5, 0.975)))))\n names(v_r_q) <- c(\"rho\", \"vr_025\", \"vr_500\", \"vr_975\")\n g <- g+1\n graphs[[g]] <- ggplot(v_r_q) + geom_line(aes(x=rho, y= vr_500)) + geom_ribbon(aes(x=rho, ymin=vr_025, ymax=vr_975), alpha=0.5) +\n xlab(expression(r/r[eff]))+ylab(expression(V[rot]))\n v_e_q <- data.frame(cbind(rho, t(apply(vexp_pred, 2, quantile, probs=c(.025, 0.5, 0.975)))))\n names(v_e_q) <- c(\"rho\", \"ve_025\", \"ve_500\", \"ve_975\")\n g <- g+1\n graphs[[g]] <- ggplot(v_e_q) + geom_line(aes(x=rho, y= ve_500)) + geom_ribbon(aes(x=rho, ymin=ve_025, ymax=ve_975), alpha=0.5) +\n xlab(expression(r/r[eff]))+ylab(expression(V[exp]))\n\n r_q <- apply(post$r*remax, 2, quantile, probs=c(0.025, 0.5, 0.975))\n rownames(r_q) <- paste(\"r\", rownames(r_q), sep=\"_\")\n v_r_q <- apply(post$v_rot*v_norm, 2, quantile, probs=c(0.025, 0.5, 0.975))\n rownames(v_r_q) <- paste(\"v_rot\", rownames(v_r_q), sep=\"_\")\n df_v <- data.frame(cbind(t(r_q), t(v_r_q)))\n df <- data.frame(r=as.vector(abs(post$r))*remax, v_rot=as.vector(post$v_rot)*v_norm)\n\n g <- g+1\n graphs[[g]] <- ggplot(df_v) + geom_point(aes(x=r_50., y=v_rot_50.)) +\n geom_errorbar(aes(x=r_50., ymin=v_rot_2.5., ymax=v_rot_97.5.)) +\n geom_errorbarh(aes(x=r_50., y=v_rot_50., xmin=r_2.5., xmax=r_97.5.)) +\n ggtitle(paste(\"mangaid\", gdat.stack$meta$mangaid, \": joint distribution of r, v_rot\")) +\n xlab(expression(r/r[eff])) + ylab(\"v (km/sec)\")\n if (PLOTS) {\n for (i in seq_along(graphs)) {\n x11()\n plot(graphs[[i]])\n }\n }\n\n list(stanfit=stanfit, r_eff=r_eff, remax=remax, v_norm=v_norm, vlos_data=vlos_data, \n v_sample=v_sample, x_pred=x_pred, y_pred=y_pred,\n graphs=graphs\n )\n}\n \n", "meta": {"hexsha": "c70b481b22eafd64a3d9ae1c25e4272032fd0269", "size": 15895, "ext": "r", "lang": "R", "max_stars_repo_path": "vrot.r", "max_stars_repo_name": "mlpeck/vrot_stanmodels", "max_stars_repo_head_hexsha": "7c4fbbd24d50aeeb475d7c3b7f323228e5666ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vrot.r", "max_issues_repo_name": "mlpeck/vrot_stanmodels", "max_issues_repo_head_hexsha": "7c4fbbd24d50aeeb475d7c3b7f323228e5666ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vrot.r", "max_forks_repo_name": "mlpeck/vrot_stanmodels", "max_forks_repo_head_hexsha": "7c4fbbd24d50aeeb475d7c3b7f323228e5666ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9594594595, "max_line_length": 132, "alphanum_fraction": 0.5703680403, "num_tokens": 5446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4643779065887792}} {"text": "#' sweep\n#' \n#' Sweep a vector through a float matrix.\n#' \n#' @details\n#' Note that if the length of \\code{STATS} does not recycle exactly across\n#' \\code{MARGIN}, the results here will differ slightly from the results of\n#' base R.\n#' \n#' @param x\n#' A float vector/matrix.\n#' @param MARGIN\n#' 1 (rows) or 2 (columns)\n#' @param STATS\n#' Vector to sweep out. \n#' @param FUN\n#' Sweeping function; must be one of \\code{\"+\"}, \\code{\"-\"}, \\code{\"*\"}, or\n#' \\code{\"/\"}. \n#' @param check.margin\n#' Should x/STATS margin lengths be checked?\n#' @param ...\n#' Theoretically these are additional arguments passed to an arbitrary function.\n#' However, we only support basic arithmetic, so they are ignored.\n#' \n#' @return\n#' A matrix of the same type as the highest precision input.\n#' \n#' @examples\n#' library(float)\n#' \n#' s = flrunif(10, 3)\n#' sweep(s, 2, fl(1))\n#' \n#' @useDynLib float R_sweep_spm\n#' @name sweep\n#' @rdname sweep\nNULL\n\n\n\nsweep_float32 = function(x, MARGIN, STATS, FUN=\"-\", check.margin=TRUE, ...) \n{\n if (is.double(STATS))\n return(sweep(dbl(x), MARGIN, STATS, FUN, check.margin, ...))\n else if (!is.logical(STATS) && !is.integer(STATS) && !is.float(STATS))\n stop(\"non-numeric argument to binary operator\")\n \n if (isavec(x))\n stop(\"Error in array(STATS, dims[perm]) : 'dims' cannot be of length 0\", call.=FALSE)\n \n if (!isTRUE(all.equal(MARGIN, 1)) && !isTRUE(all.equal(MARGIN, 2)))\n stop(\"missing value where TRUE/FALSE needed\")\n \n if (!is.character(FUN))\n stop(\"only '+', '-', '*', and '/' are implemented for floats\")\n \n FUN = match.arg(FUN, c('+', '-', '*', '/'))\n \n if (isTRUE(check.margin))\n {\n if ((MARGIN == 1 && NROW(x)%%length(STATS)) || (MARGIN == 2 && NCOL(x)%%length(STATS)))\n warning(\"STATS does not recycle exactly across MARGIN\")\n }\n \n ret = .Call(R_sweep_spm, DATA(x), as.integer(MARGIN), STATS, FUN)\n float32(ret)\n}\n\n\n\n#' @rdname sweep\n#' @export\nsetMethod(\"sweep\", signature(x=\"float32\"), sweep_float32)\n", "meta": {"hexsha": "60c53ab69c94a2bb0c21203e73f50d97438de346", "size": 1973, "ext": "r", "lang": "R", "max_stars_repo_path": "R/sweep.r", "max_stars_repo_name": "david-cortes/float", "max_stars_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-11-08T11:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T20:17:08.000Z", "max_issues_repo_path": "R/sweep.r", "max_issues_repo_name": "david-cortes/float", "max_issues_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2017-09-02T11:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T15:11:19.000Z", "max_forks_repo_path": "R/sweep.r", "max_forks_repo_name": "david-cortes/float", "max_forks_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-11-18T18:05:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T01:23:23.000Z", "avg_line_length": 26.6621621622, "max_line_length": 91, "alphanum_fraction": 0.6279776989, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.4643328759013}} {"text": "# # This script was written by nicolas m. roberts, primarily using the geologyGeometry library of functions, written by Joshua R. Davis. \n# # if you incounter bugs in the code, please inform nick at nmroberts@wisc.edu\n\n### PRELIMINARY WORK ####\n\n# Set the working directory.\nsetwd(\"~/Desktop/20170620geologyGeometry\")\n\n# [!!!] FOR WINDOWS: Set the working directory.\n# setwd(\"C:/users/[Insert user name]/Desktop/20170620geologyGeometry\")\n\n# Load the necessary R libraries.\nsource(\"library/all.R\")\n\n# Load some custom functions\nsource(\"JSG_statsFunctions.r\")\n\n# #[!!!] Uncomment only if you have compiled C on your system and have the C libraries loaded at the top of this script. Uncomment and run the following line only if you have compiled C. # [!!!] Markov chain Monte Carlo and Kamb contouring in equal volume plots require C compiler. Skip MCMC and equal volume Kamb lines if you do not wish to install C. Load the necessary library\n# source(\"libraryC/all.R\")\n\n#==========================LOAD THE DATA========================================\n\n# Load the foliation-lineation data\nFollins <- geoDataFromFile(\"data/Follins_Ahs.csv\")\n\n# Check how many measurements there are\nnrow(Follins)\n\n#==========================PLOT THE DATA========================================\n\n# Plot foliation-lineation locations in map view\nplot(\n Follins$easting,\n Follins$northing,\n xlab = \"Easting (meters)\",\n ylab = \"Northing (meters)\"\n)\n\n# Plot the data in Equal area plot. Pole to foliation (red), Lineation (cyan)\nlineEqualAreaPlotTwo(lapply(Follins$rotation, function(s)\n s[1, ]),\n lapply(Follins$rotation, function(s)\n s[2, ]))\n\n# Plot Follins in Equal Area plots with Kamb contours (numbers are 2 sigma values)\n# Poles to foliation (circles)\nlineKambPlot(lapply(Follins$rotation, function(s)\n s[1, ]), c(2, 6, 10, 14, 18))\n# Lineations (squares)\nlineKambPlot(lapply(Follins$rotation, function(s)\n s[2, ]),\n c(2, 6, 10, 14, 18),\n shapes = c(\"s\"))\n\n# Plot the Follins in an Equal Volume plot (after Davis and Titus, 2017)\noriEqualVolumePlot(\n Follins$rotation,\n group = oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = \"black\" ,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Ahsahka_EqualVol1.png\", \"Ahsahka_EqualVol2.png\")\n\n# [!!!] Uncomment only if you have compiled C on your system and have the C libraries loaded at the top of this script.\n# Skip if you have not compiled C. Plot 6-sigma Kamb contours for the data in an equal volume plot (after Davis and Titus, 2017)\n# oricKambPlot(\n# Follins$rotation,\n# group = oriLineInPlaneGroup,\n# multiple = 6,\n# backgroundColor = \"white\",\n# curveColor = \"black\",\n# boundaryAlpha = 0.1,\n# colors = \"black\",\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\"\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"Ahsahka_Kamb_equalVol1.png\", \"Ahsahka_Kamb_EqualVol2.png\")\n\n\n#==========================IDENTIFY GEOGRAPHIC TRENDS========================================\n\n# 1) Visually inspect the possibility of geographic trends in the data\n\n# Plot foliation-lineation locations in map view, colored in gray-scale by northing. This shading will be used in the following plots.\nplot(\n Follins$easting,\n Follins$northing,\n col = shades(Follins$northing),\n pch = 19\n)\n\n# Plot foliation-lineation orientations in an equal volume plot (after Davis and Titus, 2017)\noriEqualVolumePlot(\n Follins$rotation,\n group = oriLineInPlaneGroup,\n simplePoints = FALSE,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = shades(Follins$northing),\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Ahsahka_shadesNorthing_equalVol1.png\",\n \"Ahsahka_shadesNorthing_EqualVol2.png\")\n\n# Plot foliation-lineation orientations colored by northing. Poles to foliation (circles), Lineation (squares)\nlineEqualAreaPlot(\n c(\n lapply(Follins$rotation, function(s)\n s[1, ]),\n lapply(Follins$rotation, function(s)\n s[2, ])\n ),\n col = shades(Follins$northing),\n shapes = c(replicate(length(Follins$rotation), \"c\"), replicate(length(Follins$rotation), \"s\"))\n)\n\n#————————————————————————————————————————————————————————————\n\n# 2) Run geodesic regressions to quantify any extant trends.\n\n# Create a temporary version of the foliation lineation data and establish a geographic criteria that encompasses all the data.\nFollinsAll <- Follins\nAhsAllCrit <-\n FollinsAll$easting > 550000 & Follins$northing > 5140000\nFollinsAll$domain <- replicate(nrow(FollinsAll), 1)\nFollins$domain[AhsAllCrit] <- 1\n\n# 2A) Perform a geodesic regression with respect to azimuths every 10 degrees on all data, using the geographic criteria defined above. Each regression asks the question: \"does orientation change linearly with respect to an azimuth towards x degrees\"\nregressions <- regressionSweep(FollinsAll, 10, (AhsAllCrit), 0)\n\n# Create a data frame that contains the summary information for the regressions\nregressionsSum <- data.frame(regressions[[19]])\n\n# Name the columns of the data frame\nnames(regressionsSum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# View the summary table for the output.\nregressionsSum\n\n# Plot the R^2 value as a function of Azimuth\nplot(\n as.vector(regressionsSum$Azimuth),\n as.vector(regressionsSum$R_squared),\n xlab = \"Azimuth\",\n ylab = \"R-squared\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# 3) Run kernal regression to quantify any extant trends.\n\n# Recategorize the symmetric copies of the data.\nmu <- oriFrechetMean(Follins$rotation, group=oriLineInPlaneGroup)\nFollins$rotation <- oriNearestRepresentatives(Follins$rotation, mu, group=oriLineInPlaneGroup)\n\n# Define the bandwith for a kernal regression. If desired, uncomment the next line (it may take ~20 minutes to run). Otherwise, use the pre-calculated value, \"bandwidth\".\n# bandwidth <- rotBandwidthForKernelRegression(Follins$northing,Follins$rotation)\nbandwidth <- 0.02314421\n\n# Perform a kernel regression with respect to northing. The kernel function is analogous to finding a best fit curve in 2D.\nkernelReg <- lapply(\n seq(\n from = min(Follins$northing),\n to = max(Follins$northing),\n by = 100\n ),\n rotKernelRegression,\n Follins$northing,\n Follins$rotation,\n bandwidth,\n numSteps = 1000\n)\n\n# Filter the regression results to only keep those that give an error of 0 and minimum eigen value > 0\nsapply(kernelReg, function(regr)\n regr$error)\nsapply(kernelReg, function(regr) {\n regr$minEigenvalue > 0\n})\n\n\n# Plot the regression curve in an equal volume plot.\nkernelRegCurve <- lapply(kernelReg, function(regr)\n regr$r)\noriEqualVolumePlot(\n kernelRegCurve,\n group=oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = \"black\",\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n simplePoints = TRUE\n)\n\n# Compute the R^2 for the kernel regression.\nKernRsquared <-\n rotRsquaredForKernelRegression(Follins$northing, Follins$rotation, bandwidth, numSteps =\n 1000)\n\n# View the R^2 value\nKernRsquared\n\n# Do a permutation test for significance. This takes a significant amount of time (>>1 hr)\nrSquareds <-\n rotKernelRegressionPermutations(Follins$northing, Follins$rotation, bandwidth, numPerms =\n 1000)\nlength(rSquareds)\np <- sum(rSquareds > KernRsquared$rSquared)\np\n\n\n#==========================DEFINE GEOGRAPHIC DOMAINS========================================\n\n# Define geographic criteria, based on sampling area, with the proposed shear zone boundary into account.\ndomain1Crit <- Follins$easting < 560000 & Follins$northing < 5158000\ndomain2Crit <- (Follins$easting >= 560000 & Follins$northing < 5163000) | Follins$easting >= 565000\ndomain3Crit <- !(domain1Crit | domain2Crit)\n\n# # Create a new column in the dataframe in which to store the domain information\nFollins$domain <- replicate(nrow(Follins), 1)\n\n# Classify the foliation-only dataset by domain\nFollins$domain[domain1Crit] <- 1\nFollins$domain[domain2Crit] <- 2\nFollins$domain[domain3Crit] <- 3\n\n# Plot the locations of the foliation-lineation data in map view, each domain a different color. Domain 1 (Red), Domain 2 (Green), Domain 3 (Blue)\nplot(\n x = Follins$easting,\n y = Follins$northing,\n xlab = \"Easting (meters)\",\n ylab = \"Northing (meters)\",\n col = hues(Follins$domain),\n pch = 19\n)\n\n#==========================IDENTIFY GEOGRAPHIC TRENDS WITHIN DOMAINS========================================\n\n# 1) Make sure each domain is roughly unimodal\n#DOMAIN 1, n = 23.\noriEqualVolumePlot(\n Follins$rotation[domain1Crit],\n oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = \"black\",\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\n\n#[!!!] Uncomment only if you have compiled C on your system and have the C libraries loaded at the top of this script.\n# oricKambPlot(\n# Follins$rotation[domain1Crit],\n# oriLineInPlaneGroup,\n# backgroundColor = \"white\",\n# curveColor = \"black\",\n# boundaryAlpha = 0.1,\n# colors = \"black\",\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\"\n# )\n\n#DOMAIN 2, n = 14.\noriEqualVolumePlot(\n Follins$rotation[domain2Crit],\n oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = \"black\",\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\n\n#[!!!] Uncomment only if you have compiled C on your system and have the C libraries loaded at the top of this script.\n# oricKambPlot(\n# Follins$rotation[domain2Crit],\n# oriLineInPlaneGroup,\n# backgroundColor = \"white\",\n# curveColor = \"black\",\n# boundaryAlpha = 0.1,\n# colors = \"black\",\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\"\n# )\n\n#DOMAIN 3, n = 32.\noriEqualVolumePlot(\n Follins$rotation[domain2Crit],\n oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.1,\n colors = \"black\",\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\noriEqualVolumePlot(Follins$rotation[domain2Crit],\n oriLineInPlaneGroup,\n col = hues(Follins$easting[domain2Crit]))\n\n#[!!!] Uncomment only if you have compiled C on your system and have the C libraries loaded at the top of this script.\n# oricKambPlot(\n# Follins$rotation[domain2Crit],\n# oriLineInPlaneGroup,\n# backgroundColor = \"white\",\n# curveColor = \"black\",\n# boundaryAlpha = 0.1,\n# colors = \"black\",\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\"\n# )\n\n\n# Plot all the foliation data in an equal volume plot (after Davis and Titus, 2017), colored by domain. Domain 1 (red), Domain 2 (green), Domain 3 (blue)\noriEqualVolumePlot(\n Follins$rotation,\n oriLineInPlaneGroup,\n col = hues(Follins$domain),\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.2,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# 2) Look for geographic patterns in plots.\n#DOMAIN 1, n = 23. maybe a very faint rainbow--more like clumping of the dark blues together.\noriEqualVolumePlot(Follins$rotation[domain1Crit],\n oriLineInPlaneGroup,\n col = shades(Follins$northing[domain1Crit]))\n\n#DOMAIN 2, n = 14. Part of the problem with small sample sizes--you can't really know whether the datapoints are independent...\noriEqualVolumePlot(Follins$rotation[domain2Crit],\n oriLineInPlaneGroup,\n col = shades(Follins$northing[domain2Crit]))\n\n#DOMAIN 3, n = 32. No rainbow.\noriEqualVolumePlot(Follins$rotation[domain2Crit],\n oriLineInPlaneGroup,\n col = shades(Follins$easting[domain2Crit]))\n\n#————————————————————————————————————————————————————————————\n\n# 3) From visual inspection of the above plots, Domain 1 and Domain 3 potentially have geographic dependency. Perform regressions on these two domains.\n\n#DOMAIN 1, n = 23. Perform a series of Geodesic Regressions for every 10° azimuth, with p-values not calculated.\nregressionsD1 <- regressionSweep(Follins, 10, domain1Crit, 0)\n\n# Create a dataframe with the summary information for the regressions\nregressionsD1Sum <- data.frame(regressionsD1[[19]])\n\n# Name the columns of the data frame\nnames(regressionsD1Sum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# View the summary table for the output.\nregressionsD1Sum\n\n# Plot the R^2 value as a function of Azimuth\nplot(\n as.vector(regressionsD1Sum$Azimuth),\n as.vector(regressionsD1Sum$R_squared),\n xlab = \"Azimuth\",\n ylab = \"R-squared\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# Define the Azimuth with the highest R-squared value. (In this case, 130)\nazimuthD1 <-\n Follins$easting[domain1Crit] * sin(130 * degree) + Follins$northing[domain1Crit] *\n cos(130 * degree)\n\n# DOMAIN 1, n = 23. Define the bandwith for a kernal regression. If desired, uncomment the next line (it may take ~20 minutes to run). Otherwise, use the pre-calculated value, \"bandwidthD1\".\n# bandwidthD1 <- rotBandwidthForKernelRegression(azimuthD1,Follins$rotation[domain1Crit])\nbandwidthD1 <- 0.02202349\n\n#Run the kernel regression\nkernelRegD1 <- lapply(\n seq(\n from = min(azimuthD1),\n to = max(azimuthD1),\n by = 100\n ),\n rotKernelRegression,\n azimuthD1,\n Follins$rotation[domain1Crit],\n bandwidthD1,\n numSteps = 1000\n)\nsapply(kernelRegD1, function(regr)\n regr$error)\nsapply(kernelRegD1, function(regr) {\n regr$minEigenvalue > 0\n})\n\n# Plot the regression curve\nkernelRegCurveD1 <- lapply(kernelRegD1, function(regr)\n regr$r)\noriEqualVolumePlot(Follins$rotation[domain1Crit],\n curves = list(kernelRegCurveD1),\n simplePoints = TRUE, oriLineInPlaneGroup)\n\n# Compute the R^2.\nKernRsquaredD1 <-\n rotRsquaredForKernelRegression(azimuthD1, Follins$rotation[domain1Crit], bandwidthD1, numSteps =\n 1000)\nKernRsquaredD1\n\n# Do a permutation test for significance.\nrSquaredsD1 <-\n rotKernelRegressionPermutations(azimuthD1, Follins$rotation[domain1Crit], bandwidthD1, numPerms =\n 1000)\nlength(rSquareds)\npD1 <- sum(rSquareds > KernRsquared$rSquared)\n\n#the p-value for this regression.\npD1\n\n#————————————————————————————————————————————————————————————\n\n#Now do the same thing for Domain 3\n\n#DOMAIN 3, n = 32. A series of Geodesic Regressions for every 10° azimuth, with p-values not calculated.\nregressionsD3 <- regressionSweep(Follins, 10, domain3Crit, 0)\n\n# Create a dataframe with the summary information for the regressions\nregressionsD3Sum <- data.frame(regressionsD3[[19]])\n\n# Name the columns of the data frame\nnames(regressionsD3Sum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# View the summary table for the output.\nregressionsD3Sum\n\n# Plot the R^2 value as a function of Azimuth\nplot(\n as.vector(regressionsD3Sum$Azimuth),\n as.vector(regressionsD3Sum$R_squared),\n xlab = \"Azimuth\",\n ylab = \"R-squared\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# Define the Azimuth with the highest R-squared value. (In this case, 60)\nazimuthD3 <-\n Follins$easting[domain3Crit] * sin(60 * degree) + Follins$northing[domain3Crit] *\n cos(60 * degree)\n\n#DOMAIN 3, n = 32. Define the bandwith for a kernal regression. If desired, uncomment the next line (it may take ~20 minutes to run). Otherwise, use the pre-calculated value, \"bandwidthD3\".\n# bandwidthD3 <-\n# rotBandwidthForKernelRegression(Follins$northing[domain3Crit], Follins$rotation[domain3Crit])\nbandwidthD3 <- 0.1331092\n\n#Run the kernel regression\nkernelRegD3 <- lapply(\n seq(\n from = min(azimuthD3),\n to = max(azimuthD3),\n by = 100\n ),\n rotKernelRegression,\n azimuthD3,\n Follins$rotation[domain3Crit],\n bandwidthD3,\n numSteps = 1000\n)\nsapply(kernelRegD3, function(regr)\n regr$error)\nsapply(kernelRegD3, function(regr) {\n regr$minEigenvalue > 0\n})\n\n# Plot the regression curve\nkernelRegCurveD3 <- lapply(kernelRegD3, function(regr)\n regr$r)\noriEqualVolumePlot(Follins$rotation[domain3Crit],\n curves = list(kernelRegCurveD3),\n simplePoints = TRUE,\n oriLineInPlaneGroup)\n\n# Compute the R^2.\nKernRsquaredD3 <-\n rotRsquaredForKernelRegression(azimuthD3, Follins$rotation[domain3Crit], bandwidthD3, numSteps = 1000)\nKernRsquaredD3\n\n# Do a permutation test for significance.\nrSquaredsD3 <-\n rotKernelRegressionPermutations(Follins$northing[domain3Crit], Follins$rotation[domain3Crit], bandwidthD3, numPerms = 1000)\nlength(rSquareds)\npD3 <- sum(rSquareds > KernRsquaredD3$rSquared)\n\n#the p-value for this regression.\npD3\n\n##==========================STATISTICAL DESCRIPTORS========================================\n\n# 1) Domain 1, n = 23\n\n# Frechet mean (minimizes the Frechet variance).\nFrechetMeanDom1 <-\n oriFrechetMean(Follins$rotation[domain1Crit], oriLineInPlaneGroup)\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom1)\nFrechetVarDom1 <-\n oriVariance(Follins$rotation[domain1Crit], FrechetMeanDom1, oriLineInPlaneGroup)\n\n# Plot the FrechetMean in an Equal Angle plot\nFrechetCurvesDom1 <-\n lapply(Follins$rotation[domain1Crit], function(r)\n rotGeodesicPoints(FrechetMeanDom1, r, 10))\noriEqualAnglePlot(points = Follins$rotation[domain1Crit], curves = FrechetCurvesDom1, group = oriLineInPlaneGroup)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom1)\n\n# Print the Frechet variance.\nFrechetVarDom1\n\n#————————————————————————————————————————————————————————————\n\n# 2) Domain 2, n = 14\n#Frechet mean minimizes the Frechet variance.\nFrechetMeanDom2 <-\n oriFrechetMean(Follins$rotation[domain2Crit], oriLineInPlaneGroup)\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom2)\nFrechetVarDom2 <-\n oriVariance(Follins$rotation[domain2Crit], FrechetMeanDom2, oriLineInPlaneGroup)\n\n# Plot the FrechetMean in an Equal Angle plot\nFrechetCurvesDom2 <-\n lapply(Follins$rotation[domain2Crit], function(r)\n rotGeodesicPoints(FrechetMeanDom2, r, 10))\noriEqualAnglePlot(points = Follins$rotation[domain2Crit], curves = FrechetCurvesDom2, oriLineInPlaneGroup)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom2)\n\n# Print the Frechet variance\nFrechetVarDom2\n\n#————————————————————————————————————————————————————————————\n\n# 3) Domain 3, n = 32\n#Frechet mean minimizes the Frechet variance.\nFrechetMeanDom3 <-\n oriFrechetMean(Follins$rotation[domain3Crit], oriLineInPlaneGroup)\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom3)\nFrechetVarDom3 <-\n oriVariance(Follins$rotation[domain3Crit], FrechetMeanDom3, oriLineInPlaneGroup)\n\n# Plot the FrechetMean in an Equal Angle plot\nFrechetCurvesDom3 <-\n lapply(Follins$rotation[domain3Crit], function(r)\n rotGeodesicPoints(FrechetMeanDom3, r, 10))\noriEqualAnglePlot(points = Follins$rotation[domain3Crit], curves = FrechetCurvesDom3, oriLineInPlaneGroup)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanDom3)\n\n# Print the Frechet variance.\nFrechetVarDom3\n\n#————————————————————————————————————————————————————————————\n\n# 4) Dispersion of the data\n\n#The standard way to get at dispersion is to compute the maximum matrix fisher likelihood. The matrix fisher distribution comprises a kind of \"mean\" and a positive definite symmetric matrix, which characterises the anisotropic dispersion.\n\n# Redefine the rotations to be within one of the symmetric copies\nmu <- oriFrechetMean(Follins$rotation, group = oriLineInPlaneGroup)\nFollins$rotation <-\n oriNearestRepresentatives(Follins$rotation, mu, oriLineInPlaneGroup)\n\n# Northern Domain, n = 16. Fisher maximum likelihood\nmleDom1 <- rotFisherMLE(Follins$rotation[domain1Crit])\nmleDom1\neigen(mleDom1$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n#Central Domain, n = 34. Fisher maximum likelihood\nmleDom2 <- rotFisherMLE(Follins$rotation[domain2Crit])\nmleDom2\neigen(mleDom2$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n#Southern Domain, n = 79. Fisher maximum likelihood\nmleDom3 <- rotFisherMLE(Follins$rotation[domain3Crit])\nmleDom3\neigen(mleDom3$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n#==========================INFERENCE========================================\n\n# Here, we can perform some statistical techniques to use information about the samples (each domain) to compute a probability cloud of the mean of the population(s) from which those samples were taken.\n# From numerical work in Davis and Titus (2017), MCMC will work the best for small sample sizes that have the matrix fisher anisotropy (eigenvalues) of (large, large, small). All four domains have this anisotropy, and have too few data points to use the (computationally quicker) bootstrapping method.\n\n#We'll do both and compare.\n\n# Compute the bootstrap cloud of means\nFollins_domain1Boots <-\n oriBootstrapInference(Follins$rotation[domain1Crit], 10000, oriLineInPlaneGroup)\nFollins_domain2Boots <-\n oriBootstrapInference(Follins$rotation[domain2Crit], 10000, oriLineInPlaneGroup)\nFollins_domain3Boots <-\n oriBootstrapInference(Follins$rotation[domain3Crit], 10000, oriLineInPlaneGroup)\n\n# [!!!] Requires C libraries to run. \n# [!!!] Compute the Markov chain Monte Carlo cloud of means\n# [!!!]Uncomment lines if you have compiled C on your computer and have loaded the C libraries at the top of this script.\n\n# Follins_domain1MCMC <-\n# oricWrappedTrivariateNormalMCMCInference(Follins$rotation[domain1Crit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100)\n# Follins_domain2MCMC <-\n# oricWrappedTrivariateNormalMCMCInference(Follins$rotation[domain2Crit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100)\n# Follins_domain3MCMC <-\n# oricWrappedTrivariateNormalMCMCInference(Follins$rotation[domain3Crit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100)\n\n#————————————————————————————————————————————————————————————\n\n# 1) Northern v. Central domains\n\n# A) Using MCMC\n\n# [!!!] Requires C libraries to run. \n# Construct the 95% confidence ellipsoids from small triangles\n# tris1_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain1MCMC$mBar,\n# Follins_domain1MCMC$leftCovarInv,\n# Follins_domain1MCMC$q095,\n# numNonAdapt = 4\n# )\n# tris2_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain2MCMC$mBar,\n# Follins_domain2MCMC$leftCovarInv,\n# Follins_domain2MCMC$q095,\n# numNonAdapt = 4\n# )\n# \n# # Plot the MCMC comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(Follins_domain1MCMC$ms, Follins_domain2MCMC$ms),\n# boundaryAlpha = .1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# triangles = c(tris1_MCMC, tris2_MCMC),\n# simplePoints = TRUE,\n# colors = c(replicate(length(\n# Follins_domain1MCMC$ms\n# ), \"black\"), replicate(\n# length(Follins_domain2MCMC$ms), \"orange\"\n# )),\n# group = oriTrivialGroup\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_Ahs_d1d2_1.png\", \"MCMC_WestMt_d1d2_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(Follins_domain1MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain1MCMC$ms, function(s)\n# s[2, ])\n# ),\n# c(\n# lapply(Follins_domain2MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain2MCMC$ms, function(s)\n# s[2, ])\n# ))\n\n#....................................................................\n\n# B) Using bootstrapping\n\n# Construct the 95% confidence ellipsoids from small triangles\ntris1_Boot <-\n rotEllipsoidTriangles(\n Follins_domain1Boots$center,\n Follins_domain1Boots$leftCovarInv,\n Follins_domain1Boots$q095,\n numNonAdapt = 4\n )\ntris2_Boot <-\n rotEllipsoidTriangles(\n Follins_domain2Boots$center,\n Follins_domain2Boots$leftCovarInv,\n Follins_domain2Boots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\nrotEqualAnglePlot(\n points = c(\n Follins_domain1Boots$bootstraps,\n Follins_domain2Boots$bootstraps\n ),\n triangles = c(tris1_Boot, tris2_Boot),\n boundaryAlpha = .1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_domain1Boots$bootstraps), \"black\"\n ), replicate(\n length(Follins_domain2Boots$bootstraps), \"orange\"\n ))\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_Ahs_d1d2_1.png\", \"Boots_Ahs_d1d2_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_domain1Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain1Boots$bootstraps, function(s)\n s[2, ])\n),\nc(\n lapply(Follins_domain2Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain2Boots$bootstraps, function(s)\n s[2, ])\n))\n\n#————————————————————————————————————————————————————————————\n\n# 2) Northern vs. Southern domains\n\n# A) Using MCMC\n\n# [!!!] Requires C libraries to run. \n# Construct the 95% confidence ellipsoids from small triangles\n# tris1_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain1MCMC$mBar,\n# Follins_domain1MCMC$leftCovarInv,\n# Follins_domain1MCMC$q095,\n# numNonAdapt = 5\n# )\n# tris3_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain3MCMC$mBar,\n# Follins_domain3MCMC$leftCovarInv,\n# Follins_domain3MCMC$q095,\n# numNonAdapt = 5\n# )\n# \n# # Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(Follins_domain1MCMC$ms, Follins_domain3MCMC$ms),\n# triangles = c(tris1_MCMC, tris3_MCMC),\n# boundaryAlpha = 0.1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# simplePoints = TRUE,\n# colors = c(replicate(length(\n# Follins_domain1MCMC$ms\n# ), \"black\"), replicate(length(\n# Follins_domain3MCMC$ms\n# ), \"blue\")),\n# group = oriTrivialGroup\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_Ahs_d1d3_1.png\", \"MCMC_Ahsd1d3_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(Follins_domain1MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain1MCMC$ms, function(s)\n# s[2, ])\n# ),\n# c(\n# lapply(Follins_domain3MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain3MCMC$ms, function(s)\n# s[2, ])\n# ))\n\n#....................................................................\n\n# B) Using bootstrapping\n# Construct the 95% confidence ellipsoids from small triangles\ntris1_Boot <-\n rotEllipsoidTriangles(\n Follins_domain1Boots$center,\n Follins_domain1Boots$leftCovarInv,\n Follins_domain1Boots$q095,\n numNonAdapt = 4\n )\ntris3_Boot <-\n rotEllipsoidTriangles(\n Follins_domain3Boots$center,\n Follins_domain3Boots$leftCovarInv,\n Follins_domain3Boots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids.\nrotEqualAnglePlot(\n points = c(\n Follins_domain1Boots$bootstraps,\n Follins_domain3Boots$bootstraps\n ),\n triangles = c(tris1_Boot, tris3_Boot),\n boundaryAlpha = .1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_domain1Boots$bootstraps), \"black\"\n ),\n replicate(\n length(Follins_domain3Boots$bootstraps), \"blue\"\n ))\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_Ahs_d1d3_1.png\", \"Boots_Ahs_d1d3_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_domain1Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain1Boots$bootstraps, function(s)\n s[2, ])\n),\nc(\n lapply(Follins_domain3Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain3Boots$bootstraps, function(s)\n s[2, ])\n))\n\n\n\n#————————————————————————————————————————————————————————————\n\n# 3) Central vs. Southern domains\n\n# A) Using MCMC\n\n# [!!!] Requires C libraries to run. \n# Construct the 95% confidence ellipsoids from small triangles\n# tris2_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain2MCMC$mBar,\n# Follins_domain2MCMC$leftCovarInv,\n# Follins_domain2MCMC$q095,\n# numNonAdapt = 4\n# )\n# tris3_MCMC <-\n# rotEllipsoidTriangles(\n# Follins_domain3MCMC$mBar,\n# Follins_domain3MCMC$leftCovarInv,\n# Follins_domain3MCMC$q095,\n# numNonAdapt = 4\n# )\n# \n# # Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(Follins_domain2MCMC$ms, Follins_domain3MCMC$ms),\n# triangles = c(tris2_MCMC, tris3_MCMC),\n# boundaryAlpha = 0.1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# simplePoints = TRUE,\n# colors = c(replicate(\n# length(Follins_domain2MCMC$ms), \"orange\"\n# ), replicate(length(\n# Follins_domain3MCMC$ms\n# ), \"blue\")),\n# group = oriTrivialGroup\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_Ahs_d2d3_1.png\", \"MCMC_Ahs_d2d3_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(Follins_domain2MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain2MCMC$ms, function(s)\n# s[2, ])\n# ),\n# c(\n# lapply(Follins_domain3MCMC$ms, function(s)\n# s[1, ]),\n# lapply(Follins_domain3MCMC$ms, function(s)\n# s[2, ])\n# ))\n\n#....................................................................\n\n\n# B) Using bootstrapping\n\n# Construct the 95% confidence ellipsoids from small triangles\ntris2_Boot <-\n rotEllipsoidTriangles(\n Follins_domain2Boots$center,\n Follins_domain2Boots$leftCovarInv,\n Follins_domain2Boots$q095,\n numNonAdapt = 4\n )\ntris3_Boot <-\n rotEllipsoidTriangles(\n Follins_domain3Boots$center,\n Follins_domain3Boots$leftCovarInv,\n Follins_domain3Boots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\noriEqualAnglePlot(\n points = c(\n Follins_domain2Boots$bootstraps,\n Follins_domain3Boots$bootstraps\n ),\n triangles = c(tris2_Boot, tris3_Boot),\n boundaryAlpha = 0.1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_domain1Boots$bootstraps), \"orange\"\n ), replicate(\n length(Follins_domain3Boots$bootstraps), \"blue\"\n )),\n group = oriTrivialGroup\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_Ahs_d2d3_1.png\", \"Boots_Ahs_d2d3_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_domain2Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain2Boots$bootstraps, function(s)\n s[2, ])\n),\nc(\n lapply(Follins_domain3Boots$bootstraps, function(s)\n s[1, ]),\n lapply(Follins_domain3Boots$bootstraps, function(s)\n s[2, ])\n))\n", "meta": {"hexsha": "d7e6ba997499676553137f36455821164300477c", "size": 33626, "ext": "r", "lang": "R", "max_stars_repo_path": "JSG_StatisticalAnalysis_Orofino.r", "max_stars_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_stars_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-01T13:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T13:18:38.000Z", "max_issues_repo_path": "JSG_StatisticalAnalysis_Orofino.r", "max_issues_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_issues_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JSG_StatisticalAnalysis_Orofino.r", "max_forks_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_forks_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2772680938, "max_line_length": 379, "alphanum_fraction": 0.6687384762, "num_tokens": 9528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4642434924644378}} {"text": "#Jenny Smith\n\n#march 30, 2017 \n#Purpose: Create a list of survival analyses and Given survival package Survfit() object, plot the survival curves and calculate the P values for differences in survival. \n\n\nSurvObjects <- function(df, colNames, group, rho=0, time=NULL,ref=NULL){\n #df is the dataframe with clinical data. \n #colnames is a character vector (length 2) with the colnames of the time and event, in that order. \n #group is the column name as character vector of the explanatory variable to test \n #time is optional if you need to convert days to years for example. \n #rho is 1 or 0 or inbetween. 0=logrank test and 1=gehan-wilcoxon test\n \n require(survival)\n require(survMisc)\n \n #optional time unit conversion\n if (is.null(time)){\n time <- (df[[colNames[1]]])\n }else if (time == \"DtoY\"){\n time <- (df[,colNames[1]]/365)\n }else if (time == \"MtoY\"){\n time <- (df[,colNames[1]]/12)\n }\n \n #Kaplan Meier Estimates\n KM <- Surv(time = time, event = df[[colNames[2]]])\n \n if (group == 1){\n #model fit\n survFit <- survfit(KM ~ 1)\n return(survFit)\n \n }else{\n \n if (!is.null(ref)){\n df[,group] <- relevel(as.factor(df[,group]), ref=ref)\n }\n \n #model fit\n survFit <- survfit(KM ~ df[,group], data=df) \n \n #cox proportional Hazards\n cph.test <- coxph(KM ~ df[,group])\n \n #test proportional hazards assumption\n cph.zph <- cox.zph(cph.test, transform = \"km\")\n rhoPval <- as.data.frame(cph.zph$table)$p #test the PH assumption\n \n if (length(rhoPval) > 1){\n rhoPval <- rhoPval[length(rhoPval)]\n }\n \n # survMisc compare stat tests for two curves\n tne <- ten(eval(survFit$call$formula), data=df) \n capture.output(comp(tne)) -> allTests\n\n if (rhoPval >= 0.05 ){\n attr(tne, \"lrt\")[1,] -> pVal #log-rank test\n test <- \"log.rank\"\n }else if (rhoPval < 0.05){\n attr(tne, \"lrt\")[2, ] -> pVal #Gehan-Breslow-Wilcoxon\n test <- \"Gehan.Breslow.Wilcoxon\"\n }\n \n list <- list(survFit, pVal, cph.test, cph.zph, KM)\n names(list) <- c(\"survFit\", test, \"CoxPH\", \"PH_Test\",\"KaplanMeirerEst\")\n return(list)\n }\n}\n\n\n#Survival plot without gridlines. \nSurvivalPlot <- function(fit, LegendTitle, timeUnit,include.censored=TRUE, colors,pval=NULL,max.year=NULL){\n #fit the output of the survFit() function. \n #legend title is a character vector which will be the plot legend title.\n #timeUnit is a character vector for the follow-up time in days, years, months etc. \n #colors is a character vector the same length as the number of groups. \n #max.year is the time (singe numeric) in years to end the plot at.\n #pval is string (charcter or numeric) of the p-value\n \n require(survival)\n library(ggplot2)\n library(GGally)\n \n if(is.null(pval)){\n pval <- \"\"\n }else{\n pval <- paste0(\"p = \",pval)\n }\n \n if(!is.null(max.year)){\n # if(max(fit$time) < max.year){\n pos.x <- max.year\n # }\n }else{\n pos.x <- max(fit$time)\n }\n \n if(is.null(fit$strata)){\n lm <- 1 #left margin (lm)\n rm <- 4 #right margin(rm)\n num.cols <- 1\n num.rows <- 1\n \n #main survival plot\n p <- ggsurv(fit, surv.col = colors,\n cens.col=colors, CI=FALSE, \n lty.est = 1, size.est = 1.0,\n cens.size = 2.0,order.legend=FALSE)\n \n }else{\n \n m <- max(nchar(gsub(\"^.+\\\\=(.+)\", \"\\\\1\", names(fit$strata)))) #maximum number of characters\n d <- length(fit$strata) #how many groups\n lm <- case_when(m <= 2 ~ 0.90,\n m <= 5 ~ 1.25, \n m > 5 & m <= 9 ~ 1.7,\n m > 9 & m < 13 ~ 2.6,\n m >= 13 & m < 17 ~ 3.4,\n m >= 17 & m < 21 ~ 5.0,\n m >= 21 & m < 23 ~ 6.0,\n m >= 23 & m < 25 ~ 6.5,\n m >= 25 ~ 7.5)#left margin (lm)\n # print(c(\"km.plot\", lm))\n rm <- case_when(d <= 4 ~ 1.5, d > 4 ~ 2.0) #right margin(rm)\n num.cols <- 2\n num.rows <- 2\n \n if(d > 4 & d < 7){\n num.rows <- 3\n }else if(d > 7 & d <= 18){\n num.cols <- 3\n num.rows <- 6\n }else if(d > 18){\n num.cols <- 5\n num.rows <- 5\n }\n \n if(num.cols*num.rows < d){\n num.rows <- 10\n }\n \n #main survival plot\n p <- ggsurv(fit, plot.cens=include.censored, \n surv.col = colors, CI=FALSE, \n lty.est = 1, size.est = 1.0,\n cens.size = 2.0,order.legend=FALSE)\n }\n \n #customize the plot\n p <- p + \n labs(y= \"Fraction Surviving\", x = paste(timeUnit, \"Follow-up\")) + \n scale_y_continuous(limits = c(0,1), \n breaks = seq(0,1,0.2),\n minor_breaks = NULL) +\n scale_x_continuous(limits = c(0,pos.x),\n breaks = seq(0,pos.x, 2)) +\n \n theme(plot.title = element_text(hjust = 0.5, size=10), \n panel.background = element_rect(fill=\"white\"), \n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_rect(colour = \"black\", fill= NA, size=1.0),\n \n axis.text = element_text(colour = \"black\"),\n axis.text.y = element_text(size = 12),\n axis.text.x = element_text(size=12), \n axis.title = element_text(size = 12), \n legend.position = \"top\",\n legend.direction = \"horizontal\",\n legend.margin = margin(0,0,0,0, unit = \"pt\"),\n legend.text = element_text(size=10),\n legend.title = element_text(size=10),\n legend.key=element_blank()) +\n \n theme(plot.margin = margin(0, rm,.5,lm,unit=\"cm\")) +\n annotate(geom=\"text\", x=1, y=0.05, label=pval, size=5) +\n guides(color=guide_legend(ncol=num.cols, nrow=num.rows))\n \n if (length(colors) > 1){\n p$scales$scales[[1]]$name <- LegendTitle\n p$scales$scales[[2]]$name <- LegendTitle\n }\n \n return(p)\n}\n\n\n#risk table dataframe \nrisk.table <- function(survFit.obj, f.levels=NULL, \n times=NULL,col=\"black\",\n ret.data=FALSE, max.year=NULL){\n #survFit.obj is the results survfit()\n #f.levels is an optional character vector to relevel the order of the groups, if desired. else levels is alphabetical\n #times would be a seperate numeric vector, with years/x-axis breaks points, if desired. \n \n if(!is.null(max.year)){\n # if (max(survFit.obj$time) < max.year){\n times <- seq(0,max.year, by= 2)\n xlims <- max.year\n # }\n }else{\n times <- seq(0,max(survFit.obj$time), by= 2)\n xlims <- max(survFit.obj$time)\n }\n \n #Summary dataframe with the selected time points to get % OS/ EFS for plot x-axis\n summ <- summary(survFit.obj, times=times, extend=TRUE)\n \n \n if(is.null(f.levels)){\n f.levels <- unique(as.character(summ$strata)) %>%\n gsub(\"^.+\\\\=(.+)\", \"\\\\1\", .)\n }\n \n #Create a new dataframe to hold the time,KM estimate and strata for plotting\n risk.df <- bind_cols(list(time=summ$time, \n surv=summ$surv,\n n.risk=summ$n.risk, \n Group=as.character(summ$strata))) %>%\n set_colnames(c(\"time\",\"surv\",\"N.Risk\",\"Group\")) %>%\n mutate(Group=gsub(\"^.+\\\\=(.+)\", \"\\\\1\", Group), \n Group=factor(Group, levels = f.levels))\n \n \n if(ret.data){\n return(risk.df)\n }\n \n #variable for deciding length of margins. longer group names would need more space.\n m <- max(nchar(levels(risk.df$Group))) # print(c(\"length:\", m))\n d <- length(levels(risk.df$Group))\n lm <- case_when(m <= 5 ~ 1.75, \n m > 5 & m <= 9 ~ 1.00, \n m > 9 & m <= 10 ~ 1.00, \n m > 10 & m < 13 ~ 1.10,\n m >= 13 ~ 1.20) \n\n rm <- case_when(d <= 5 ~ 1.5, \n m > 5 ~ 2.0) \n\n \n #gglot the risk table (risk.df)\n tbl <- ggplot(risk.df, aes(x = time, y = Group, label=N.Risk)) +\n geom_text(size = 5) +\n theme_bw() +\n scale_x_continuous(\"Number at risk\", \n limits = c(0,xlims),\n breaks = times) +\n xlab(NULL) +\n ylab(NULL) +\n theme(panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n legend.position=\"none\",\n axis.line = element_line(size=0.7, color=\"black\"),\n axis.title.x = element_text(size=12),\n axis.ticks.x = element_blank(),\n axis.title.y = element_blank(),\n axis.text.x = element_blank(),\n axis.text.y = element_text(face=\"bold\",\n size=12,\n color= col[levels(risk.df$Group)],\n hjust=1)) +\n #of note: this margin is still not perfect..... the size of window in Rstudio is different than what actually shows up on the tiff... \n theme(plot.margin = margin(-1.5, rm, 0.1, lm, unit=\"cm\"))\n \n\n \n \n return(tbl)\n}\n\n\n##The function below added 10/2/17\nKM.plots <- function(df, group_vars=NULL, type=\"OS\",\n covariate,\n cohort,cc=NULL, \n riskTable=TRUE,\n f.levels=NULL, \n max.year=NULL,\n custom_cols=NULL,\n include.censored=TRUE){\n library(dplyr)\n library(tibble)\n library(survival)\n library(magrittr)\n library(tidyr)\n suppressPackageStartupMessages(require(gridExtra))\n \n #df is the cleaned CDE with patient IDs as rownames. \n #group_vars is a character vector of a column name to group_by() in dplyr. \n #type is \"OS\" for OS/EFS or \"EOI\" for end of induction time points\n #covariate is a character string for the column in CDE to be the explanatory variable\n #cohort is for \"0531\" or \"1031\" (different colnames)\n \n #Define KM estimates for survival analysis\n if (cohort == \"0531\" & type==\"OS\"){\n os.est <- \"Surv(Overall.Survival.Time.in.Days/365.25, OS.ID)\"\n efs.est <- \"Surv(Event.Free.Survival.Time.in.Days/365.25, Event.ID)\"\n }else if (cohort == \"1031\" & type==\"OS\"){\n os.est <- \"Surv(OS.time..days./365.25, OS.ID)\"\n efs.est <- \"Surv(EFS.time..days./365.25, Event.ID)\"\n }else if (cohort == \"TCGA\" & type==\"OS\"){\n os.est <- \"Surv(OS.months..3.31.12/12, clinData1.vital_status)\"\n efs.est <- \"Surv(EFS.months....3.31.12/12, first.event)\"\n }else if (cohort==\"BEAT_AML\" & type==\"OS\"){\n os.est <- \"Surv(OverallSurvival_VIZOME/365.25, OS.ID)\"\n #No EFS data available\n }else if (type==\"EOI\"){\n if(is.null(custom_cols)){message(\"Need custom columnames for time and event for EOI analyses.\n Custom calls must a list of 2 names os.est and efs.est containing vector of\n time column in days and event.type indicator column as 0,1 in that order.\");\n return(custom_cols)}\n os.est <- paste0(\"Surv(\",custom_cols[[\"os.est\"]][1],\"/365.25\",\", \",custom_cols[[\"os.est\"]][2], \")\")\n efs.est <- paste0(\"Surv(\",custom_cols[[\"efs.est\"]][1],\"/365.25\",\", \",custom_cols[[\"efs.est\"]][2], \")\")\n }\n \n \n #function for colors \n colorcodes <- function(df,covariate){\n strata <- unlist(unique(df[,covariate])) #Unique groups (strata)\n strata <- strata[order(strata)] #ensure the alphabetical order \n len <- length(strata)\n \n if ( ! is.null(cc)){\n return(cc)\n \n }else{\n colors <- c(\"dodgerblue4\", \"brown3\", \"darkgoldenrod3\", \n \"deepskyblue1\",\n \"azure4\", \"darkmagenta\",\n \"turquoise4\", \"green4\", \n \"deeppink\", \"navajowhite2\",\"chartreuse2\",\"lightcoral\",\n \"mediumorchid\", \"saddlebrown\", \"#466791\",\"#60bf37\",\"#953ada\",\n \"#4fbe6c\",\"#ce49d3\",\"#a7b43d\",\"#5a51dc\",\n \"#d49f36\",\"#552095\",\"#507f2d\",\"#db37aa\",\n \"#84b67c\",\"#a06fda\",\"#df462a\",\"#5b83db\",\n \"#c76c2d\",\"#4f49a3\",\"#82702d\",\"#dd6bbb\",\n \"#334c22\",\"#d83979\",\"#55baad\",\"#dc4555\",\n \"#62aad3\",\"#8c3025\",\"#417d61\",\"#862977\",\n \"#bba672\",\"#403367\",\"#da8a6d\",\"#a79cd4\",\n \"#71482c\",\"#c689d0\",\"#6b2940\",\"#d593a7\",\"#895c8b\",\"#bd5975\")\n cc <- NULL\n for ( i in 1:len){\n c <- colors[i]\n cc <- c(cc,c)\n }\n names(cc) <- strata\n return(cc)\n }\n }\n\n \n #Formula for KM curves\n OS.form <- as.formula(paste(os.est,' ~ ',covariate))\n \n #perform survival analysis for all factor levels\n grouped.df <- df %>%\n group_by(!!! rlang::syms(group_vars)) %>%\n do(OS.cox=coxph(OS.form, data = .),\n OS.fit=survfit(OS.form, data=.),\n OS.diff=survdiff(OS.form, data=.), #survdiff for log-rank p-value\n OS=SurvivalPlot(survfit(OS.form, data=.), #survival plots\n LegendTitle = covariate,\n timeUnit = \"Years\",\n max.year = max.year,\n include.censored=include.censored,\n colors = colorcodes(.,covariate = covariate)))\n \n if(exists(\"efs.est\")){\n #Formula for EFS KM curves\n EFS.form <- as.formula(paste(efs.est,' ~ ', covariate))\n \n grouped.df.efs <- df %>%\n group_by(!!! rlang::syms(group_vars)) %>% \n do( EFS.cox=coxph(EFS.form, data = .),\n EFS.fit=survfit(EFS.form, data=.),\n EFS.diff=survdiff(EFS.form, data=.), #survdiff for log-rank p-value\n EFS=SurvivalPlot(survfit(EFS.form, data=.),\n LegendTitle= covariate,\n timeUnit= \"Years\",\n max.year = max.year,\n include.censored=include.censored,\n colors= colorcodes(., covariate = covariate)))\n \n grouped.df <- bind_cols(grouped.df, grouped.df.efs)\n }\n\n #Denote the grouping variable in the results dataframe\n if(is.null(group_vars)){\n grouped.df <- add_column(grouped.df, Group=\"AML\",.before = 1)\n }else{\n col.idx <- which(colnames(grouped.df)==\"OS.cox\")-1\n grouped.df <- unite(grouped.df, \n \"Group\",1:all_of(col.idx), remove = FALSE, sep=\" in \")\n }\n\n \n #function to calculate a p-value\n pvalue <- function(survdiff.res){\n p <- pchisq(survdiff.res$chisq, df=length(survdiff.res$n) - 1, lower=FALSE)\n p <- ifelse(p < 0.001, \"p < 0.001\", paste0(\"p = \", round(p, digits = 3)))\n return(p)\n }\n \n #Function to extract N of cohort.\n groupSize <- function(survdiff.res){paste0(\"N = \", sum(survdiff.res$n))}\n\n #Update the survial plots with an informative title and p values, and group N\n types <- c(\"Relapse\", \"Failure\", \"OS\", \"EFS\")\n plots <- which(colnames(grouped.df) %in% types)\n\n #for each row (nrow > 1, when grouping variable given)\n for ( i in 1:nrow(grouped.df)){\n\n #for each OS/EFS column\n for (plot.idx in plots){\n fit.idx <- plot.idx-2\n fit <- grouped.df[[fit.idx]][[i]]\n summ <- summary(fit)\n median.surv <- summ$table[,\"median\"]\n x_pos <- ifelse(min(median.surv,na.rm=T) < 1, max(summ$time,na.rm = T), 1)\n y_pos <- ifelse(min(median.surv, na.rm=T) < 1, 0.95, 0.05)\n \n idx.logrank <- plot.idx-1\n N <- groupSize(grouped.df[[idx.logrank]][[i]])\n pval <- pvalue(grouped.df[[idx.logrank]][[i]]) %>%\n paste(.,N, sep=\"\\n\")\n\n #Add Main Title that is the column name (eg Relapse,OS, EFS, etc) and grouping factors\n grouped.df[[plot.idx]][[i]]$labels$title <- paste(names(grouped.df[plot.idx]), \n grouped.df[[\"Group\"]][i], \n sep = \": \")\n\n #Add P value and the N\n grouped.df[[plot.idx]][[i]] <- grouped.df[[plot.idx]][[i]] +\n annotate(geom=\"text\", x=x_pos, y=y_pos, label=pval, size=5) +\n theme(plot.title = element_text(face=\"bold\"))\n \n #Add a risk table (Number of patients at risk at each time )\n if(riskTable){\n\n risk.tab <- risk.table(survFit.obj = fit, \n ret.data = TRUE)\n risk.tab.p <- risk.table(survFit.obj = fit,\n col = cc, \n f.levels = f.levels, \n max.year=max.year)\n\n # Create a blank plot for place-holding\n blank.pic <- ggplot(risk.tab, aes(time, surv)) +\n geom_blank() +\n theme_bw() +\n theme(axis.text.x = element_blank(),\n axis.text.y = element_blank(),\n axis.title.x = element_blank(),\n axis.title.y = element_blank(),\n axis.ticks = element_blank(),\n panel.grid = element_blank(),\n panel.border = element_blank())\n\n\n # grid.arrange(grouped.df[[plot.idx]][[i]], blank.pic, risk.tab.p, clip = FALSE, nrow = 3,\n # ncol = 1, heights = unit(c(2, .1, .25), c(\"null\", \"null\", \"null\")))\n\n grouped.df[[plot.idx]][[i]] <- arrangeGrob(grouped.df[[plot.idx]][[i]],\n blank.pic, risk.tab.p,\n clip = FALSE, \n nrow = 3, ncol = 1,\n heights = unit(c(2, .2, .4),\n c(\"null\", \"null\", \"null\")))\n\n }\n }\n }\n \n return(grouped.df)\n}\n\n\n#Function to save the outputs from KM.plots()\nsaveMultiPlots <- function(KM.plots.res,w=8,h=5){\n #This is for the relapse results from KM.plots()\n \n N <- nrow(KM.plots.res)\n \n covar <- function(i){\n names(KM.plots.res[grep(\"diff\",colnames(KM.plots.res))][[i,1]]$n) %>%\n str_split_fixed(.,pattern=\"=\",n=2) %>% .[,1] %>% unique()\n }\n \n name <- function(i){paste(KM.plots.res[[1]][i],covar(i),col,\"KMplot.tiff\", sep=\"_\")}\n cols <- grep(\"diff\",colnames(KM.plots.res), value = TRUE, invert = TRUE)[-1]\n \n for (col in cols){\n lapply(1:N, function(x) ggsave(filename = name(x),\n plot = KM.plots.res[[col]][[x]],\n device = \"tiff\",\n width = w,\n height = 5,\n dpi=600))\n \n }\n}\n\n\n\n\n#Added from LSC17 Analysis on July 12, 2017. \nweibull.HR <- function(weibull.mod){\n #weibull.mod is the output of survreg(, dist=\"wiebull\")\n # multivar is a numeric vector idicating the indices of multi varaite analysis to be returned. \n if (is.null(multivar)){\n idx <- 2 #univariate analysis\n }else{\n idx <- 2:length(weibull.mod$coefficients)\n }\n HR <- round(exp(weibull.mod$coefficients*-1*1/weibull.mod$scale)[idx], digits = 3)\n}\n\n\n\n#Added from LSC17 Analysis on July 12, 2017. \nparametricSumaryTable <- function(survreg.res){\n summ <- summary(survreg.res)\n table <- as.data.frame(summ$table)\n \n # coef <- summ$coefficients[which(! grepl(\"Int\", names(summ$coefficients)))]\n idx <- which( ! grepl(\"Int|Log\", names(survreg.res$coefficients)))\n \n UCI_HR2 <- round(exp((survreg.res$coefficients[idx] - 1.96*table$`Std. Error`[idx])*-1*1/survreg.res$scale),\n digits = 3)\n LCI_HR2 <- round(exp((survreg.res$coefficients[idx] + 1.96*table$`Std. Error`[idx])*-1*1/survreg.res$scale),\n digits=3)\n \n \n HR <- round(exp(survreg.res$coefficients[idx]*-1*1/survreg.res$scale), digits = 3)\n CI <- paste(LCI_HR2, UCI_HR2, sep=\"-\")\n pVal <- round(table$p[idx], digits=3)\n \n \n stats <- data.frame(HR, CI,pVal)\n colnames(stats) <- c(\"Hazard Ratio\", \"95% Confidence Interval\", \"P-value\")\n return(stats)\n}\n\n\n#Added from LSC17 Multivariate Analysis on June 24th, 2017. \ncoxSummaryTable <- function(coxph.res,Colname=\"Group\"){\n c.mod <- coxph.res\n c.summ <- summary(coxph.res)\n c.table <- as.data.frame(c.summ$coefficients) %>% cbind(.,as.data.frame(c.summ$conf.int))\n # c.table\n c.HR <- round(c.table$`exp(coef)`, digits=3)\n c.CI <- paste(round(c.table$`lower .95`,digits=3),round(c.table$`upper .95`, digits = 3), sep=\"-\")\n c.pVal <- round(c.table$`Pr(>|z|)`, digits=3)\n \n comp <- gsub(\"^.+(Yes|No|Unknown|High|Low)\", \"\\\\1\",names(c.mod$coefficients))\n c.stats <- data.frame(names(c.mod$coefficients) ,comp, c.HR, c.CI, c.pVal)\n colnames(c.stats) <- c(\"Variable\", Colname,\"Hazard Ratio\", \"95% Confidence Interval\", \"P-value\")\n # rownames(c.stats) <- names(c.mod$coefficients)\n \n return(c.stats)\n}\n\n\n\n#functions to calculate the p-value for differnces in KM curves from survdiff() function\n#Tests if there is a difference between two or more survival curves using the G-rho family of tests, or for a single curve against a known alternative.\ncalc_KMcurve_pvalues <- function(survdiff, digits=3){\n p <- pchisq(survdiff$chisq, length(survdiff$n)-1, \n lower.tail = FALSE) %>% \n round(., digits = digits)\n \n return(p)\n}\n\n\n\n#create a table with OS/EFS percent at specified time point\n#uses the summary() function on the survfit() object \n#can optionally input p-values manually from survdiff() function\noutcome_table <- function(fit, time=5, pvalues=NULL){\n \n summ <- summary(fit, times=time) \n type <- ifelse(any(grepl(\"OS\", summ$call)),\"OS\",\"EFS\")\n summ <- summ[!grepl(\"table|std.chaz|call\", names(summ))]\n summ <- summ[sapply(summ,length)==length(summ$strata)]\n \n surv_col <- paste(\"Percent\", type)\n n <- length(summ$strata)\n \n tab <- tibble(as.data.frame(summ)) %>% \n mutate_at(vars(surv,lower,upper,std.err), ~round(.*100, digits = 2)) %>% \n mutate(Group=str_split_fixed(strata, pattern = \"=\", n=2)[,2]) \n \n \n if(!is.null(pvalues) & length(pvalues) < n){\n pval_ref <- NA #ref is the first position in the strata\n pvalues=c(pval_ref, pvalues) #must be in same order as strata in the survift()!\n tab <- tab %>% \n add_column(pvalue=pvalues)\n \n tab <- tab %>% \n select(Group,\n \"Number Patients per Group\"=n,\n \"Time (years)\"=time,\n !!surv_col := surv,\n \"Lower 95% CI\"=lower,\n \"Upper 95% CI\"=upper,\n \"Standard Error\"=std.err,\n \"p-value\"=pvalue) \n } else{\n \n tab <- tab %>% \n select(Group,\n \"Number Patients per Group\"=n,\n \"Time (years)\"=time,\n !!surv_col := surv,\n \"Lower 95% CI\"=lower,\n \"Upper 95% CI\"=upper,\n \"Standard Error\"=std.err) \n \n }\n \n \n return(tab)\n}\n\n\n\n\n\n# introduction This entire function was written by Lindsay Keegan based off\n# a tutorial by Edwin Thoen posted here: \n# http://www.r-statistics.com/2013/07/creating-good-looking-survival-curves-the-ggsurv-function/\n# and slightly adapted by Avery McIntosh, 2015.\n#See TCGA AML 05May2017.Rmd for example usage. \n#S is the fit object\n#NEEDS TO BE TESTED AGAIN\n\nggsurv.m <- function(s, CI = 'def', plot.cens = T, surv.col = 'gg.def',\n cens.col = 'red', lty.est = 1, lty.ci = 2,\n cens.shape = \" \", back.white = F, xlab = 'Time (days)',\n ylab = 'Retention Probability', main = '') {\n \n \n strata <- length(s$strata)\n n <- s$strata\n \n #update JS to deal with the super imposed curves to seq by 4 for 24 and split with comma \n groups <- factor(unlist(lapply(strsplit(names(s$strata),split = \"=|,\"), \n function(x) paste(x[2], x[4], sep=\".\"))))\n \n gr.name <- unlist(strsplit(names(s$strata), '='))[1] #LSC17\n gr.df <- vector('list', strata)\n ind <- vector('list', strata)\n n.ind <- c(0,n); n.ind <- cumsum(n.ind)\n \n for(i in 1:strata) ind[[i]] <- (n.ind[i]+1):n.ind[i+1]\n \n for(i in 1:strata){\n gr.df[[i]] <- data.frame(\n time = c(0, s$time[ ind[[i]] ]),\n surv = c(1, s$surv[ ind[[i]] ]),\n up = c(1, s$upper[ ind[[i]] ]),\n low = c(1, s$lower[ ind[[i]] ]),\n cens = c(0, s$n.censor[ ind[[i]] ]),\n group = rep(groups[i], n[i] + 1))\n }\n \n dat <- do.call(rbind, gr.df)\n dat.cens <- subset(dat, cens != 0)\n \n pl <- ggplot(dat, aes(x = time, y = surv, group = group)) +\n xlab(xlab) + ylab(ylab) + ggtitle(main) +\n geom_step(aes(col = group),lty=1, size=1.15) +\n geom_point(data = dat.cens, aes(x=time, y=surv, color=group), shape=3, size=4) +\n labs(y= \"Fraction Surviving\", x = paste(\"Follow-up in\", \"Years\")) + \n theme(plot.title = element_text(hjust = 0.5, size=18), \n panel.background = element_rect(fill=\"white\"), \n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n axis.text.y = element_text(size = 16),\n axis.text.x = element_text(size=16), \n axis.title = element_text(size = 16), \n panel.border = element_rect(colour = \"dark grey\", fill= NA, size=1.0),\n legend.text = element_text(size=14),\n legend.title = element_text(size=14)) +\n scale_y_continuous(limits = c(0,1), breaks = seq(0,1,0.2), minor_breaks = NULL) +\n scale_x_continuous(limits = c(0,max(dat$time)), breaks = seq(0,max(dat$time), 2))\n \n # list <- list(n, groups, gr.name)\n # names(list) <- c(\"n\", \"groups\", \"gr.name\")\n return(p1)\n \n}\n\n\n# KM.plots <- function(df, groupBy, type=\"OS\", covariate,cohort,cc=NULL, \n# riskTable=TRUE,f.levels=NULL, max.year=NULL){\n# library(dplyr)\n# library(survival)\n# library(magrittr)\n# suppressPackageStartupMessages(require(gridExtra))\n# \n# #df is the cleaned CDE with patient IDs as rownames. stringsAsFactors=FALSE\n# #type is for relapse due to having strate with 0 members...\n# #covariate is a character string for the column in CDE to be the explanatory variable\n# \n# #Formula for survival analysis\n# if (cohort == \"0531\"){\n# os.est <- \"Surv(Overall.Survival.Time.in.Days/365.25, OS.ID)\"\n# efs.est <- \"Surv(Event.Free.Survival.Time.in.Days/365.25, Event.ID)\"\n# \n# OS.form <- as.formula(paste(os.est,' ~ ',covariate))\n# EFS.form <- as.formula(paste(efs.est,' ~ ', covariate))\n# }else if (cohort == \"1031\"){\n# os.est <- \"Surv(OS.time..days./365.25, OS.ID)\"\n# efs.est <- \"Surv(EFS.time..days./365.25, Event.ID)\"\n# \n# #updated on 6/15/18 to reflect the new CDEs for 1031. \n# OS.form <- as.formula(paste(os.est, ' ~ ', covariate))\n# EFS.form <- as.formula(paste(efs.est, ' ~ ', covariate))\n# }\n# \n# #function for colors \n# colorcodes <- function(df){\n# strata <- unlist(unique(df[,covariate])) #Unique groups (strata)\n# strata <- strata[order(strata)] #ensure the alphabetical order \n# len <- length(strata)\n# \n# if ( ! is.null(cc)){\n# return(cc)\n# \n# }else{\n# colors <- c(\"dodgerblue4\", \"firebrick1\", \"green4\", \"darkorange\",\n# \"turquoise3\",\"azure4\", \"chartreuse1\", \"darkmagenta\", \n# \"deeppink\", \"darkslategray1\", \"navajowhite2\",\n# \"brown3\", \"darkgoldenrod3\", \"deepskyblue1\", \"lightcoral\", \n# \"mediumorchid\", \"saddlebrown\")\n# cc <- NULL\n# for ( i in 1:len){\n# c <- colors[i]\n# cc <- c(cc,c)\n# }\n# names(cc) <- strata\n# return(cc)\n# }\n# }\n# \n# #perform survival analysis for all factor levels\n# if (type==\"OS\"){\n# grouped.df <- df %>%\n# group_by_(groupBy) %>%\n# do(OS.fit=survfit(OS.form, data=.),\n# OS.diff=survdiff(OS.form, data=.), #survdiff for log-rank p-value\n# OS=SurvivalPlot(survfit(OS.form, data=.), #survival plots\n# LegendTitle = \"\",\n# timeUnit = \"Years\",\n# max.year = max.year,\n# colors = colorcodes(.)),\n# \n# EFS.fit=survfit(EFS.form, data=.),\n# EFS.diff=survdiff(EFS.form, data=.),\n# EFS=SurvivalPlot(survfit(EFS.form, data=.),\n# LegendTitle=\"\",\n# timeUnit= \"Years\",\n# max.year = max.year,\n# colors= colorcodes(.)))\n# }\n# \n# #function to calculate a p-value\n# pvalue <- function(survdiff.res){\n# p <- pchisq(survdiff.res$chisq, df=length(survdiff.res$n) - 1, lower=FALSE)\n# p <- ifelse(p < 0.001, \"p < 0.001\", paste0(\"p = \", round(p, digits = 3)))\n# return(p)\n# }\n# \n# #Function to extract N of cohort.\n# groupSize <- function(survdiff.res){paste0(\"N = \", sum(survdiff.res$n))}\n# \n# #Update the survial plots with an informative title and p values, and group N\n# types <- c(\"Relapse\", \"Failure\", \"OS\", \"EFS\")\n# plots <- which(colnames(grouped.df) %in% types)\n# \n# #for each row (nrow > 1, when grouping variable given)\n# for ( i in 1:nrow(grouped.df)){\n# \n# #for each OS/EFS column\n# for (plot.idx in plots){\n# idx.logrank <- plot.idx-1\n# N <- groupSize(grouped.df[[idx.logrank]][[i]])\n# pval <- pvalue(grouped.df[[idx.logrank]][[i]]) %>% \n# paste(., N, sep=\"\\n\")\n# \n# #Add more informative Legend Title\n# legendTitle <- as.character(grouped.df[i,1]) %>% \n# unique(c(groupBy, .)) %>%\n# paste(., \": \", covariate, sep=\"\")\n# \n# for (j in 1:2){\n# grouped.df[[plot.idx]][[i]]$scales$scales[[j]]$name <- legendTitle\n# }\n# \n# #Add Main Title that is the column name (eg Relapse,OS, EFS, etc)\n# grouped.df[[plot.idx]][[i]]$labels$title <- names(grouped.df[plot.idx])\n# \n# #Add P value and the N\n# grouped.df[[plot.idx]][[i]] <- grouped.df[[plot.idx]][[i]] +\n# annotate(geom=\"text\", x=1, y=0.05, label=pval, size=5)\n# \n# if(riskTable){\n# \n# fit.idx <- plot.idx-2\n# fit <- grouped.df[[fit.idx]][[i]]\n# risk.tab <- risk.table(survFit.obj = fit, ret.data = TRUE)\n# risk.tab.p <- risk.table(survFit.obj = fit,col = cc, f.levels = f.levels, max.year=max.year)\n# \n# # Create a blank plot for place-holding\n# blank.pic <- ggplot(risk.tab, aes(time, surv)) +\n# geom_blank() + \n# theme_bw() +\n# theme(axis.text.x = element_blank(),\n# axis.text.y = element_blank(),\n# axis.title.x = element_blank(),\n# axis.title.y = element_blank(),\n# axis.ticks = element_blank(),\n# panel.grid = element_blank(),\n# panel.border = element_blank())\n# \n# \n# # grid.arrange(grouped.df[[plot.idx]][[i]], blank.pic, risk.tab.p, clip = FALSE, nrow = 3,\n# # ncol = 1, heights = unit(c(2, .1, .25), c(\"null\", \"null\", \"null\")))\n# \n# grouped.df[[plot.idx]][[i]] <- arrangeGrob(grouped.df[[plot.idx]][[i]], blank.pic, risk.tab.p,\n# clip = FALSE, nrow = 3, ncol = 1, \n# heights = unit(c(2, .2, .4),c(\"null\", \"null\", \"null\")))\n# \n# }\n# }\n# }\n# \n# return(grouped.df)\n# }\n\n\n\n\n# saveKM <- function(KM.plots.res,dir){\n# \n# N <- nrow(KM.plots.res)\n# group <- colnames(KM.plots.res)[1]\n# \n# OS <- KM.plots.res$OS\n# EFS <- KM.plots.res$EFS\n# \n# saveplot <- function(gg,N){\n# type <- substitute(gg)\n# \n# lapply(1:N, function(i)\n# ggsave(filename = paste(\"TARGET_AML\",group, \n# unlist(KM.plots.res[i,1]), \n# type,\"plot.png\", sep=\"_\"),\n# plot = gg[[i]], device = \"png\", height = 7, width = 12,dpi = 600 ))\n# }\n# \n# saveplot(OS,N=N)\n# saveplot(EFS,N=N)\n# }\n\n# SurvObjects <- function(df, colNames, group, rho=0, time=NULL){\n# #df is the dataframe with clinical data. \n# #colnames is a character vector (length 2) with the colnames of the time and event, in that order. \n# #group is the column name as character vector of the explanatory variable to test \n# #time is optional if you need to convert days to years for example. \n# #rho is 1 or 0 or inbetween. 0=logrank test and 1=gehan-wilcoxon test\n# \n# require(survival)\n# require(survMisc)\n# \n# #optional time unit conversion\n# if (is.null(time)){\n# time <- (df[, colNames[1]])\n# }else if (time == \"DtoY\"){\n# time <- (df[,colNames[1]]/365)\n# }else if (time == \"MtoY\"){\n# time <- (df[,colNames[1]]/12)\n# }\n# \n# #Kaplan Meier Estimates\n# KM <- Surv(time = time, event = df[,colNames[2]])\n# \n# if (group == 1){\n# #model fit\n# survFit <- survfit(KM ~ 1)\n# return(survFit)\n# \n# }else{\n# #model fit\n# survFit <- survfit(KM ~ df[,group],data=df) \n# \n# #cox proportional Hazards\n# cph.test <- coxph(KM ~ df[,group])\n# \n# #test proportional hazards assumption\n# cph.zph <- cox.zph(cph.test, transform = \"km\")\n# rhoPval <- as.data.frame(cph.zph$table)$p #test the PH assumption\n# \n# if (length(rhoPval) > 1){\n# rhoPval <- rhoPval[length(rhoPval)]\n# }\n# \n# # survMisc compare stat tests for two curves\n# tne <- ten(eval(survFit$call$formula), data=df) \n# capture.output(comp(tne)) -> allTests\n# \n# if (rhoPval >= 0.05 ){\n# attr(tne, \"lrt\")[1,] -> pVal #log-rank test\n# test <- \"log.rank\"\n# }else if (rhoPval < 0.05){\n# attr(tne, \"lrt\")[2, ] -> pVal #Gehan-Breslow-Wilcoxon\n# test <- \"Gehan.Breslow.Wilcoxon\"\n# }\n# \n# list <- list(survFit, pVal, cph.test, cph.zph, KM)\n# names(list) <- c(\"survFit\", test, \"CoxPH\", \"PH_Test\",\"KaplanMeirerEst\")\n# return(list)\n# }\n# }\n\n\n\n", "meta": {"hexsha": "166d54864dd0c3039f65162841e2e56c039bfdc0", "size": 33604, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Survplot_Functions_2018.10.24.r", "max_stars_repo_name": "Meshinchi-Lab/DeGSEA", "max_stars_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Survplot_Functions_2018.10.24.r", "max_issues_repo_name": "Meshinchi-Lab/DeGSEA", "max_issues_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Survplot_Functions_2018.10.24.r", "max_forks_repo_name": "Meshinchi-Lab/DeGSEA", "max_forks_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9017094017, "max_line_length": 172, "alphanum_fraction": 0.5423461493, "num_tokens": 9823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.46391588833519176}} {"text": "#' matmult\n#' \n#' Matrix multiplication.\n#' \n#' @param x,y\n#' fmlmat matrices.\n#' \n#' @return\n#' A matrix of the same type as the inputs.\n#' \n#' @name matmult\n#' @rdname matmult\nNULL\n\n\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"fmlmat\", y=\"fmlmat\"),\n function(x, y)\n {\n ret = linalg_matmult(x=DATA(x), y=DATA(y))\n wrapfml(ret)\n }\n)\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"fmlmat\", y=\"matrix\"),\n function(x, y)\n {\n y_fml = ytox(x, y)\n ret = linalg_matmult(x=DATA(x), y=DATA(y))\n wrapfml(ret)\n }\n)\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"matrix\", y=\"fmlmat\"),\n function(x, y)\n {\n x_fml = ytox(y, x)\n ret = linalg_matmult(x=DATA(x), y=DATA(y))\n wrapfml(ret)\n }\n)\n", "meta": {"hexsha": "bfc479e090da73305ff06b37ed0355ad8062c8b0", "size": 753, "ext": "r", "lang": "R", "max_stars_repo_path": "R/matmult.r", "max_stars_repo_name": "fml-fam/craze", "max_stars_repo_head_hexsha": "5c749b730064b2d40d1933098d5bcbc3222f38ad", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-02-29T14:32:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:32:02.000Z", "max_issues_repo_path": "R/matmult.r", "max_issues_repo_name": "fml-fam/craze", "max_issues_repo_head_hexsha": "5c749b730064b2d40d1933098d5bcbc3222f38ad", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/matmult.r", "max_forks_repo_name": "fml-fam/craze", "max_forks_repo_head_hexsha": "5c749b730064b2d40d1933098d5bcbc3222f38ad", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6875, "max_line_length": 51, "alphanum_fraction": 0.577689243, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791031266116}} {"text": "model_snowdry <- function (Sdry_t1 = 0.0,\n Snowaccu = 0.0,\n Mrf = 0.0,\n M = 0.0){\n #'- Name: SnowDry -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: water in solid state in the snow cover Calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: water in solid state in the snow cover\n #'- inputs:\n #' * name: Sdry_t1\n #' ** description : water in solid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Snowaccu\n #' ** description : snowfall accumulation\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: Mrf\n #' ** description : liquid water in the snow cover in the process of refreezing\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: M\n #' ** description : snow in the process of melting\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #'- outputs:\n #' * name: Sdry\n #' ** description : water in solid state in the snow cover\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n Sdry <- 0.0\n if (M <= Sdry_t1)\n {\n tmp_sdry <- Snowaccu + Mrf - M + Sdry_t1\n if (tmp_sdry < 0.0)\n {\n Sdry <- 0.001\n }\n else\n {\n Sdry <- tmp_sdry\n }\n }\n return (list('Sdry' = Sdry))\n}", "meta": {"hexsha": "f836c278d02ad8d0de9e784f120827c2ba1a986b", "size": 3261, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Snowdry.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/Snowdry.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/Snowdry.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9078947368, "max_line_length": 108, "alphanum_fraction": 0.3066544005, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791031266116}} {"text": "# 4. faza: Napredna analiza podatkov\n\n#RAZVRŠČANJE V SKUPINE\n\n#funkcije iz predavanj in vaj, ki sem jih uporabila v nadaljevanju:\nhc.kolena = function(dendrogram, od = 1, do = NULL, eps = 0.5) {\n n = length(dendrogram$height) + 1 # število primerov in nastavitev parametra do\n if (is.null(do)) {\n do = n - 1\n }\n k.visina = tibble(\n k = as.ordered(od:do),\n visina = dendrogram$height[do:od]) %>%\n mutate(dvisina = visina - lag(visina)) %>% # sprememba višine\n mutate( # ali se je intenziteta spremembe dovolj spremenila?\n koleno = lead(dvisina) - dvisina > eps)\n k.visina\n}\n\n# iz tabele k.visina vrne seznam vrednosti k, pri katerih opazujemo koleno\nhc.kolena.k = function(k.visina) {\n k.visina %>%\n filter(koleno) %>%\n dplyr::select(k) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\n# narišemo diagram višin združevanja\ndiagram.kolena = function(k.visina) { \n k.visina %>% ggplot() +\n geom_point(\n mapping = aes(x = k, y = visina),\n color = \"red\") +\n geom_line(\n mapping = aes(x = as.integer(k), y = visina),\n color = \"red\") +\n geom_point(\n data = k.visina %>% filter(koleno),\n mapping = aes(x = k, y = visina),\n color = \"blue\", size = 2) +\n ggtitle(paste(\"Kolena:\", paste(hc.kolena.k(k.visina), collapse = \", \"))) +\n xlab(\"število skupin (k)\") + ylab(\"razdalja pri združevanju skupin\") +\n theme_classic()\n}\n\ndiagram.skupine = function(podatki, oznake, skupine, k) {\n podatki = podatki %>%\n bind_cols(skupine) %>%\n rename(skupina = ...4)\n \n d = podatki %>%\n ggplot(\n mapping = aes(\n x = x, y = y, color = skupina\n )\n ) +\n geom_point() +\n geom_label(label = oznake, size = 2) +\n scale_color_hue() +\n theme_classic()\n \n for (i in 1:k) {\n d = d + geom_encircle(\n data = podatki %>%\n filter(skupina == i)\n )\n }\n d\n}\n\n\nobrisi = function(podatki, hc = TRUE, od = 2, do = NULL) {\n n = nrow(podatki)\n if (is.null(do)) {\n do = n - 1\n }\n \n razdalje = dist(podatki)\n \n k.obrisi = tibble()\n for (k in od:do) {\n if (hc) {\n o.k = hclust(razdalje) %>%\n cutree(k) %>%\n silhouette(razdalje)\n } else {\n set.seed(42) # zato, da so rezultati ponovljivi\n o.k = kmeans(podatki, k)$cluster %>%\n silhouette(razdalje)\n }\n k.obrisi = k.obrisi %>% bind_rows(\n tibble(\n k = rep(k, n),\n obrisi = o.k[, \"sil_width\"]\n )\n )\n }\n k.obrisi$k = as.ordered(k.obrisi$k)\n \n k.obrisi\n}\n\nobrisi.povprecje = function(k.obrisi) {\n k.obrisi.povprecje = k.obrisi %>%\n group_by(k) %>%\n summarize(obrisi = mean(obrisi))\n}\n\nobrisi.k = function(k.obrisi) {\n obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n summarize(k = min(k)) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\ndiagram.obrisi = function(k.obrisi) {\n ggplot() +\n geom_boxplot(\n data = k.obrisi,\n mapping = aes(x = k, y = obrisi)\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = k, y = obrisi),\n color = \"red\"\n ) +\n geom_line(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = as.integer(k), y = obrisi),\n color = \"red\"\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n filter(k == min(k)),\n mapping = aes(x = k, y = obrisi),\n color = \"blue\"\n ) +\n xlab(\"število skupin (k)\") +\n ylab(\"obrisi (povprečje obrisov)\") +\n ggtitle(paste(\"Maksimalno povprečje obrisov pri k =\", obrisi.k(k.obrisi))) +\n theme_classic()\n}\n\n#________________________________________________________________________________\n#uporabila bom podatke tabela2\ntabela.skupine1.1 <- tabela2 %>%\n dplyr::select(1, 2, 6) %>%\n filter(regija != \"SLOVENIJA\") %>%\n group_by(regija, solsko.leto) %>%\n summarise(promil = sum(delez.promil)) \n\ntabela.skupine1.2 <- tabela.skupine1.1%>%\n pivot_wider(\n names_from = solsko.leto,\n values_from = promil\n )\n\n#wardove razdalje:\nregije <- tabela.skupine1.2[, 1] %>% unlist()\nrazdalje <- tabela.skupine1.2[, -1] %>% dist()\ndendrogram <- razdalje %>% hclust(method = \"ward.D\") \n\n#tabela, za risanje skupin\nregije.x.y <- as.tibble(razdalje %>% cmdscale(k = 2)) %>%\n bind_cols(regije) %>%\n dplyr::select(regija = ...3, x = V1, y = V2)\n\n#DENDROGRAM\n#plot(dendrogram, labels = regije, ylab = \"višina\", main = NULL)\n\n#HIERARHIČNO RAZVRŠČANJE V SKUPINE\n#nariše graf in obarva kolena modro\ngraf.kolena <- dendrogram %>% hc.kolena() %>% diagram.kolena() #dobila sem dva oprimalna k: 2 in 3\n#za k=2:\nskupine.2 <- dendrogram %>%\n cutree(k = 2) %>%\n as.ordered()\ndiagram.skupine(regije.x.y, regije.x.y$regija, skupine.2, 2)\n#za k=3:\nskupine.3 <- dendrogram %>%\n cutree(k = 3) %>%\n as.ordered()\ndiagram.skupine(regije.x.y, regije.x.y$regija, skupine.3, 3)\n\n\n#METODA K-TIH VODITELJEV:\n#za r.km:\nr.km <- tabela.skupine1.2[, -1] %>% obrisi(hc = FALSE)\nopt.st.skupin.r.km <- obrisi.k(r.km) #optimaleno k=2\ndiagram.obrisi(r.km) \n\nset.seed(123)\nskupine <- tabela.skupine1.2[, -1] %>%\n kmeans(centers = 2) %>%\n getElement(\"cluster\") %>%\n as.ordered\n#narišem graf in obkroži skupine:\ndiagram.skupine(regije.x.y, regije.x.y$regija, skupine, opt.st.skupin.r.km)\n\n#za r.hc:\nr.hc <- tabela.skupine1.2[, -1] %>% obrisi(hc = TRUE)\nopt.st.skupin.r.hc <- obrisi.k(r.hc) #optimaleno k=2\ndiagram.obrisi(r.hc) \n\nskupine <- tabela.skupine1.2[, -1] %>%\n dist() %>%\n hclust(method = \"ward.D\") %>%\n cutree(k = 2) %>%\n as.ordered()\n#narišemo graf in obkroži skupine:\ndiagram.skupine(regije.x.y, regije.x.y$regija, skupine, opt.st.skupin.r.hc)\n\n#funkcija, ki nariše graf za optimalno število kolen glede na nacin dolocanja\nnarisi <- function(nacin){\n if(nacin == \"Hierarhično razvrščanje\"){\n graf.kolena <- dendrogram %>% hc.kolena() %>% diagram.kolena()\n graf.kolena\n }else {\n r.km <- tabela.skupine1.2[, -1] %>% obrisi(hc = FALSE) \n diagram.obrisi(r.km) \n }\n}\n\nnarisi(\"Hierarhično razvrščanje\")\nnarisi(\"Metoda k-tih voditeljev\")\n\n\n#zemljevid za razvrščanje po skupinah z metodo HAC\nsource(\"lib/uvozi.zemljevid.r\")\nzemljevid <- uvozi.zemljevid(\"http://kt.ijs.si/~ljupco/lectures/appr/zemljevidi/si/gadm36_SVN_shp.zip\",\n \"gadm36_SVN_1\", mapa = \"zemljevidi\", encoding=\"UTF-8\")\n\nzemljevid <- zemljevid %>% \n spTransform(CRS(\"+proj=longlat +datum=WGS84\")) # pretvorimo v ustrezen format\n\nloc <- locale(encoding=\"UTF-8\")\nfor (col in names(zemljevid)) {\n if (is.character(zemljevid[[col]])) {\n zemljevid[[col]] <- zemljevid[[col]] %>% \n parse_character(locale=loc)\n }\n}\n\nzemljevid@data\nzemljevid.regije <- zemljevid\nnames(zemljevid.regije)\nzemljevid.regije$NAME_1\n\nzemljevid.regije$NAME_1 <- factor(zemljevid.regije$NAME_1)\n\nlvls <- levels(zemljevid.regije$NAME_1)\n\n#funkcija, ki nariše zemljevid glede na število izbranih skupin\nzemljevid <- function(k){\n skupine.k <- dendrogram %>%\n cutree(k = k) %>%\n as.ordered()\n \n podatki.k <- regije.x.y %>%\n bind_cols(skupine.k) %>%\n rename(skupina = ...4) %>%\n dplyr::select(1, 4)\n \n podatki.k$regija <- str_replace_all(\n podatki.k$regija, \n c(\"Primorsko-notranjska\" = \"Notranjsko-kraška\", \"Posavska\"= \"Spodnjeposavska\")\n )\n \n # spremenim imena regij, da se ujemajo z zemljevidom, kratice spremenim nazaj v dolga imena\n imena.regij.nazaj = tibble(\n regija = c(\"Gorenjska\", \"Goriška\", \"Jugovzhodna Slovenija\", \"Koroška\", \n \"Obalno-kraška\", \"Osrednjeslovenska\", \"Podravska\", \"Pomurska\", \n \"Spodnjeposavska\", \"Notranjsko-kraška\", \"Savinjska\",\"Zasavska\",\n \"SLOVENIJA\"),\n oznaka = c(\n \"kr\", \"ng\", \"nm\", \"sg\", \"kp\", \"lj\", \"mb\", \"ms\", \"kk\", \"po\", \"ce\", \"za\", \"slo\")\n )\n \n tmap_mode(\"plot\")\n zemljevid1 <- merge(\n x = podatki.k, \n y = imena.regij.nazaj, \n by = \"regija\", all.x = TRUE\n ) %>% \n dplyr::select(regija, skupina) \n \n zemljevid1 <- merge(zemljevid.regije, \n zemljevid1, \n by.x = \"NAME_1\", \n by.y = \"regija\")\n \n zem <- tm_shape(zemljevid1) + \n tm_polygons(\n \"skupina\" , \n style = \"pretty\", \n palette=\"Blues\",\n title=\"Skupina:\"\n ) + \n tm_layout(\n \"\",\n legend.title.size=1,\n legend.text.size = 0.8,\n legend.position = c(\"right\",\"bottom\"),\n legend.bg.color = \"white\",\n legend.bg.alpha = 1) +\n tm_text(\"NAME_1\", size = 4/5)\n \n zem\n \n}\n\n#narišem zemljevid za k=2:\nzem2 <- zemljevid(2)\n\n#narišem zemljevid za k=3:\nzem3 <- zemljevid(3)\n\n\n#_______________________________________________________________________________\n#NAPOVEDNI MODELI\n#Linearna regresija\npreurejena.4 <- tabela4 %>%\n dplyr::select(2, 4, 5) %>%\n group_by(vrsta.izobrazevanja, solsko.leto) %>%\n summarise(stevilo.diplomantov = sum(stevilo.diplomantov))\n\ntabela.podatki <- tabela3 %>%\n dplyr::select(1, 5, 6) %>%\n group_by(vrsta.izobrazevanja, solsko.leto) %>%\n summarise(stevilo.vpisanih = sum(stevilo.vpisanih)) %>%\n left_join(preurejena.4, by = c(\"vrsta.izobrazevanja\" = \"vrsta.izobrazevanja\", \n \"solsko.leto\" = \"solsko.leto\")\n ) %>%\n filter(solsko.leto != \"2020/21\", solsko.leto != \"2009/10\", solsko.leto != \"2010/11\") \n\ngg <- ggplot(tabela.podatki, aes(x=stevilo.vpisanih, y=stevilo.diplomantov)) + geom_point()\n\nstevilo.diplomantov ~ stevilo.vpisanih\nstevilo.diplomantov ~ stevilo.vpisanih + I(stevilo.vpisanih^2)\n\npodatki <- tabela.podatki\nn <- nrow(podatki)\nr <- sample(1:n)\nformula <- stevilo.diplomantov ~ stevilo.vpisanih\n\nk <- 5\nset.seed(123)\nrazrez <- cut(1:n, k, labels = FALSE)\nrazbitje <- split(r, razrez)\n\npp.napovedi <- rep(0, n)\nfor (i in 1:length(razbitje)){\n train.data <- podatki [-razbitje[[i]], ] #učni podatki\n test.data <- podatki[razbitje[[i]], ] #testni podatki\n model <- lm(data = train.data, formula = formula) #naučimo model\n napovedi <- predict(model, newdata = test.data) #napovemo za testne podatke\n pp.napovedi[razbitje[[i]]] <- napovedi\n}\n\npp.napovedi\n\n#izračunamo kvadratno napako -MSE\nMSE <- mean((pp.napovedi - podatki$stevilo.diplomantov)^2)\n\ngg <- gg + \n geom_smooth(method = \"lm\", \n formula = y ~ x, \n se = TRUE, \n fullrange = TRUE, \n color = \"green\") +\n theme_classic() +\n theme(\n plot.title = element_text(hjust = 0.5) #naslov na sredini\n ) +\n labs(\n x = \"Število vpisanih\",\n y = \"Število diplomantov\",\n title = \"LINEARNA REGRESIJA\"\n )\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6b35e8f5a4eeee9a50e982ef9d8f857cd7cba10e", "size": 10540, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "MajaKomic/APPR-2021-22", "max_stars_repo_head_hexsha": "c621b3f3b129e5287558eb199edeb7661704be50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "MajaKomic/APPR-2021-22", "max_issues_repo_head_hexsha": "c621b3f3b129e5287558eb199edeb7661704be50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-01-05T17:23:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T13:47:19.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "MajaKomic/APPR-2021-22", "max_forks_repo_head_hexsha": "c621b3f3b129e5287558eb199edeb7661704be50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7512690355, "max_line_length": 103, "alphanum_fraction": 0.6078747628, "num_tokens": 3929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.46344201658718476}} {"text": "#Tests and Explanations\n\n#Function Library\ntry(setwd(\"~/Shared Files/DPM/Latest\"))\nsource(file=\"ConsensusMechanism.r\")\n\n#Declare List\nScenarios <- vector(\"list\")\nSLabels <- vector(\"list\")\n\n#[1] Design Case\nSLabels$Base <- \"Basic Case - 14/24 [58%] Honest\"\n\nM1 <- rbind(\n c(1,1,0,0),\n c(1,0,0,0),\n c(1,1,0,0),\n c(1,1,1,0),\n c(0,0,1,1),\n c(0,0,1,1))\n \nrow.names(M1) <- c(\"True\", \"Confused 1\", \"True\", \"Confused 2\", \"Liar\", \"Liar\")\ncolnames(M1) <- c(\"C1.1\",\"C2.1\",\"C3.0\",\"C4.0\")\n\nScenarios$Base <- M1\n#\n\n\n# [2] Reversed Matrix\nSLabels$Reversed <- \"Basic Case - 14/24 [58%] Honest, reversed wording\"\nM2 <- ReverseMatrix(M1)\nScenarios$Reversed <- M2\n#\n\n\n# [3] Deviance: Deranged Nonconformist\nSLabels$Deviance <- \"Punishment from Deviating from Stable\"\n\nM3 <- rbind(M1[c(1,3),],\n M1[c(1,3),],\n \"Liar\"=c(0,0,1,1))\n\nScenarios$Deviance <- M3\n#\n\n\n# [4] Coalitional Deviance: Using a group to game the system.\nSLabels$CoalitionalDeviance <- \"Targeting Contract (#3) with <50% Conspirators (including 1 AntiTruth Diver)\"\nSLabels$CoalitionalDeviance2 <- \"Targeting Contract (#3) with <50% Conspirators (including 1 AntiTeam Diver)\"\n\n M4b <- rbind(\"True\"=c(1,1,0,0),\n \"True\"=c(1,1,0,0),\n \"True\"=c(1,1,0,0),\n \"True\"=c(1,1,0,0),\n \"True\"=c(1,1,0,0),\n \"True\"=c(1,1,0,0),\n \"Diver\"=c(0,0,1,1), #Diver\n \"Liar\"=c(1,1,1,0),\n \"Liar\"=c(1,1,1,0),\n \"Liar\"=c(1,1,1,0), #4 conspirators \n \"Liar\"=c(1,1,1,0)) # + 1 Diver = 5 <6 \n\nM4c <- M4b\nM4c[\"Diver\",3] <- 0 #Diver negatively correlated with his team\n\nM4d <- rbind(M4c,\"FailSafe\"=c(.5,.5,.5,.5))\n\n\nScenarios$CoalitionalDeviance <- M4b\nScenarios$CoalitionalDeviance2 <- M4c\n#\n\n\n# [5] Clueless: Passing on a Contract - \"I have no idea\"\nSLabels$CluelessControl <- c(\"Having no idea - 'passing' on a contract [control]\") \nSLabels$CluelessTest <- c(\"Having no idea - 'passing' on a contract [test]\") \n\nM3a <- rbind(M1[1,],M1[1,],M1[1,],M1[1,],M1[1,],M1[1,],M1[1,]) #bigger reference case\nrow.names(M3a) <- rep(\"True\",nrow(M3a))\n\nM3m <- M3a\nM3m[2,2] <- NA \n\nScenarios$CluelessControl <- M3a \nScenarios$CluelessTest <- M3m \n#\n\n \n# [6] Inchoerence\nSLabels$Incoherence <- c(\"Punishing Incoherence - I KNOW that this contract is spam/nonsense\") \nSLabels$Incoherence2 <- c(\"Punishing Incoherence - I KNOW that this contract is spam/nonsense [2]\") \n\nM6 <- M3a\nM6[-3,2] <- .5 #Incoherent\n\nM6b <- M6\nM6b[7,2] <- 0 #Incentive examination\n\nScenarios$Inchoherence <- M6\nScenarios$Inchoherence2 <- M6b\n#\n \n\n# [7] Unanimous: Perfect Consensus Bug\nSLabels$Unanimous <- c(\"Having everyone agree perfectly (desireable) crashes PCA\") \n\nPerCon <- rbind(M1[1,], M1[1,], M1[1,], M1[1,])\n\nScenarios$PerCon <- PerCon\n#\n\n\n# [8] Contract Gaming\nSLabels$Gaming <- c(\"Gaming the Contracts\") \n\nM9 <- cbind(M1,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5,\"C0.5\"=.5)\nM9[5:6,5:12] <- c(0,1,1,0)\nM9 <- rbind(M9,M9,M9,M9)\n\nScenarios$Gaming <- M9\n#\n\n\n# [9] Handling Missing Values\nSLabels$Missing1 <- c(\"A minority of players give missing values to 1 contract\")\nSLabels$Missing2 <- c(\"A majority of players give missing values to a minority of their contracts\")\nSLabels$Missing3 <- c(\"All players give missing values to a minority of their contracts\")\nSLabels$Missing4 <- c(\"Some players give missing values to a majority of their contracts\")\nSLabels$Missing5 <- c(\"All players give missing values to a majority of their contracts\")\n\nM10a <- cbind(M1,\"C0\"=c(0,NA,0,NA,1,1))\n\nM10b <- cbind(M10a, \"C1\"=c(1,1,1,NA,0,0), \"C1\"=c(NA,NA,NA,0,1,1))\nM10b <- rbind(M10b,M10b)\n\nM10c <- M10b\nM10c[5,1] <- NA ; M10c[6,2] <- NA ; M10c[11,1] <- NA ; M10c[12,2] <- NA ;\n\nM10d <- M10b[-11:-12,]\nM10d[5,3:6] <- NA ; M10d[6,1:4] <- NA ; \nM10d[7:8,1:2] <- NA ; M10d[2,2:3] <- NA;\n\nM10e <- rbind(M1,M1)\nM10e <- cbind(M10e[,1],M10e,M10e)\n\nM10e[1,1:5] <- NA\nM10e[2,2:6] <- NA\nM10e[3,3:7] <- NA\nM10e[4,4:8] <- NA\nM10e[5,5:9] <- NA\nM10e[6,c(6:9,1)] <- NA\nM10e[7,c(7:9,1:2)] <- NA\nM10e[8,c(8:9,1:3)] <- NA\nM10e[9,c(9,1:4)] <- NA\nM10e[10,1:5] <- NA\nM10e[11,2:6] <- NA\nM10e[12,3:7] <- NA\n\nScenarios$Missing1 <- M10a\nScenarios$Missing2 <- M10b\nScenarios$Missing3 <- M10c\nScenarios$Missing4 <- M10d\nScenarios$Missing5 <- M10e\n#\n\n\n# [10] Riven Judgements\nSLabels$Riven <- \"Separate but equal subgroups, and their recombination. [1]\" \nSLabels$Riven2 <- \"Separate but equal subgroups, and their recombination. [2]\" \n\nMg <- rbind( cbind(M1, M1*NA, M1*NA),\n cbind(M1*NA,M1, M1*NA),\n cbind(M1*NA,M1*NA, M1))\n\nMg2 <- Mg\nMg2[7,1] <- 1\n\n\nScenarios$Riven <- Mg\nScenarios$Riven2 <- Mg2\n#\n\n\n\n### * Test Results and Commentary * ###\n\nFactory(Scenarios$Base)\nCompareIncentives(Scenarios$Base)\n#Good.\nChain(X=Scenarios$Base)\n#Very good. Conforms quickly to a correct prediction.\n#I'm thinking one block per day, assuming we smooth difficulty correctly.\n\nFactory(Scenarios$Reversed)\nall.equal(Factory(Scenarios$Reversed)$Agents,Factory(Scenarios$Base)$Agents) #TRUE\n#Identical incentive structure, despite reversed inputs and outputs.\n#Good.\n\nFactory(Scenarios$Deviance)\n#Biggest Deviator gets CRUSHED to zero. High-Stakes!\n#Good.\n\nFactory(Scenarios$CoalitionalDeviance)\n#Success: An attempted <51% attack which failed.\n\nFactory(Scenarios$CoalitionalDeviance2)\n# Oh, no: A Sucessful <51% attack 'Friendly Fire' ...will have to address this.\n\n #Pre-Analytics\n CompareIncentives(X=Scenarios$CoalitionalDeviance2)\n \n row.names( Scenarios$CoalitionalDeviance2 )[7] <- \"Liar\"\n CompareIncentives(X=Scenarios$CoalitionalDeviance2)\n\n # [1] Success: 'Symmetric Friendly Fire' (ie Team truth forms a coalition of their own)\n Scenarios$CoalitionalDeviance3 <- Scenarios$CoalitionalDeviance2\n Scenarios$CoalitionalDeviance3[6,] <- c(0,0,1,1)\n\n CompareIncentives(X=Scenarios$CoalitionalDeviance3)\n Chain(Scenarios$CoalitionalDeviance3,N=100)\n #Team 'True' wins via symmetry-exploitation\n\n # [2] Success: 'Cold Feet 1' (a single player abandons the coalition)\n Scenarios$CoalitionalDeviance4 <- Scenarios$CoalitionalDeviance2\n Scenarios$CoalitionalDeviance4[8,] <- c(1,1,0,0)\n \n CompareIncentives(X=Scenarios$CoalitionalDeviance4)\n Ss <- Chain(Scenarios$CoalitionalDeviance4,N=70)[[70]]$Agents\n Ss <- data.frame(NewRep=as.numeric(Ss[,\"NewRep\"]),Group=row.names(Ss))\n aggregate(.~Group,data=Ss, FUN=sum)\n\n Scenarios$CoalitionalDeviance5 <- Scenarios$CoalitionalDeviance2\n Scenarios$CoalitionalDeviance5[8,] <- c(1,1,0,0)\n Scenarios$CoalitionalDeviance5[9,] <- c(1,1,0,0)\n\n CompareIncentives(X=Scenarios$CoalitionalDeviance5)\n Ss <- Chain(Scenarios$CoalitionalDeviance5,N=50)[[50]]$Agents\n Ss <- data.frame(NewRep=as.numeric(Ss[,\"NewRep\"]),Group=row.names(Ss))\n aggregate(.~Group,data=Ss, FUN=sum)\n #Notice after 50 rounds, the devil [=King of Liars] has actually become the two bottommost liars, as they represent the most significant source of confusion.\n #Team 'True' wins via stoicism\n\n #[3] Recursive Friendly Fire - a sub-coalition forms to defect, but a sub-coalition of this coalition forms to defect again.\n Scenarios$CoalitionalDeviance6 <- rbind(c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1), #10\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1),\n c(1,1,0,0,1), #15 (60%)\n \n #Coalition 1, backstabbing Truth to game contract 3\n c(0,0,0,1,0), #1 - Friendly Fire\n c(1,1,1,0,1),\n c(1,1,1,0,1),\n c(1,1,1,0,1),\n c(1,1,1,0,1),\n c(1,1,1,0,1), #6 (24%)\n \n #Coalition 2, 'backstabbing' Coalition 1 to game contract 4\n c(0,0,1,0,0), #1 - Friendly Fire\n c(1,1,0,1,1),\n c(1,1,0,1,1),\n c(1,1,0,1,1)) #4 (16%)\n\n row.names(Scenarios$CoalitionalDeviance6) <- c(rep('Truth',15),rep('Lie 1',6),rep('Lie 2',4))\n Factory(Scenarios$CoalitionalDeviance6)\n CompareIncentives(Scenarios$CoalitionalDeviance6)\n #fantastic sucess...Lie 2 loses less\n\n #clearly, the Nash Equilibrium\n Scenarios$CoalitionalDeviance7 <- Scenarios$CoalitionalDeviance6[1:21,]\n Scenarios$CoalitionalDeviance7 <- rbind(Scenarios$CoalitionalDeviance7, rbind(\n 'Truth 2'=c(1,1,0,0,1),\n 'Truth 2'=c(1,1,0,0,1),\n 'Truth 2'=c(1,1,0,0,1),\n 'Truth 2'=c(1,1,0,0,1)))\n Factory(Scenarios$CoalitionalDeviance7)\n CompareIncentives(Scenarios$CoalitionalDeviance7)\n\n # [4] Passive - Sideways expansion by 2 contracts\n Scenarios$CoalitionalDeviance8 <- cbind(Scenarios$CoalitionalDeviance2,Scenarios$CoalitionalDeviance2[,1:2])\n Factory(Scenarios$CoalitionalDeviance8)\n CompareIncentives(Scenarios$CoalitionalDeviance8) \n #Success, larger number of contracts makes this attack improbable.\n\n Scenarios$CoalitionalDeviance9 <- cbind(Scenarios$CoalitionalDeviance2,\n Scenarios$CoalitionalDeviance2,\n Scenarios$CoalitionalDeviance2,\n Scenarios$CoalitionalDeviance2[,-3])\n Factory(Scenarios$CoalitionalDeviance9)\n CompareIncentives(Scenarios$CoalitionalDeviance9)\n #The attack must expand proportionally.\n\n\nFactory(Scenarios$CluelessControl)\nFactory(Scenarios$CluelessTest)\n#Finding: 2 falls from tie at 5th .11 to a tie at 7th with .07; no impact on other results: success.\n\n#Note: Must be a discrete set of options: c(1,0,NA,.5) ---- !!! by extention, Catch must be implemented in FillNA. Indeed, in this example our lazy character is punished twice.\n#otherwise there will likely be pragmatic individuals who rationally deviate to answers like ~.85 or ~.92 or some nonsense. [obviously]\n\nFactory(Scenarios$Inchoherence)\nFactory(Scenarios$Inchoherence2)\n#interesting behavior, but incentive compatible, particularly given low Schelling Salience\n#incentive to switch to the consensus .5\n\nFactory(Scenarios$PerCon)\n#No problems.\n\nFactory(Scenarios$Gaming)\nCompareIncentives(Scenarios$Gaming)\n#more or less what i expected\n\n\nFactory(Scenarios$Missing1)\nFactory(Scenarios$Missing2)\nFactory(Scenarios$Missing3)\nFactory(Scenarios$Missing4)\nFactory(Scenarios$Missing5)\n#Works\n\n\nFactory(Scenarios$Riven)\nFactory(Scenarios$Riven2)\n#\n\n# !!! Must FillNa with .5 FIRST, then average in, to prevent monopoly voting on brand-new contracts. (Actually, if it will eventually be ruled .5).\n\n#Voting Across Time\n#Later Votes should count more\n#! ...simple change = ConoutFinal becomes exponentially smoothed result of previous chains.\n#! require X number of chains (blocks) before the outcome is officially determined (two weeks?)\n\n# Will need:\n# 1] Percent Voted\n# 2] Time Dimension of blocks.\n\n#\n# Possible solutions:\n# 1 - sequential filling of NAs (sequential removal of columns) - pre-processing replace with average?\n# 2 - what about the 'expert factor' idea? what happened to that?\n# 3 - Completely replace FillNa with Reputations (lots of positives here)\n\n#TO-DO\n#Cascading reputation .6,.5,.3.,2., etc = dexp(nrow(Mg))\n\n#Mysterious behavior - loading only on first factor\n#solutions\n# 1- ignore. incentives will encourage filling out of contracts on 'obvious' events\n# 2 - use later factors. Unknown what behavior could result from this\n\n\n\n# [ Additive Reputation ] Is reputation completely additive? - Yes, now.\n\nMar1 <- M1\nr1 <- rep(1/6,6)\n\nMar2 <- M1[-6,]\nr2 <- c(1/6, 1/6, 1/6, 1/6, 2/6)\n\nMar3 <- M1[c(1,2,4,5),]\nr3 <- c( 2/6, 1/6, 1/6, 2/6)\n\nMar4 <- M1[c(1,2,4,5,6),]\nr4 <- c( 2/6, 1/6, 1/6, 1/6, 1/6)\n\nFactory(Mar1,Rep=r1)$Agents\nFactory(Mar2,Rep=r2)$Agents\nFactory(Mar3,Rep=r3)$Agents\nFactory(Mar4,Rep=r4)$Agents\n\n#Is reputation additive? Yes (excluding NA-born effects, we could correct with Rep/mean(Rep) but NA is not part of equilibrium so it shouldnt matter).\n\n\nFactory(Mg)$Agents[,c(\"OldRep\",\"ThisRep\",\"SmoothRep\")]\nFactory(Mg2)$Agents[,c(\"OldRep\",\"ThisRep\",\"SmoothRep\")]\n#True 1 of group 2 skyrockets ahead, as desired.\n\n#upon reflection, I dont think this 'problem' is particularly bad.\n\n\n\n\n# [ Scaling - What are the computational limits (on a normal machine)?]\n#Many improvements can be made, of course.\n\nTestLimit <- function(n1,n2,AddNa=1) {\n M_huge <- matrix(round(runif(n1*n2)),n1,n2)\n if(AddNa==1) M_huge[sample(1:(n1*n2),size=(n1*n2)/3)] <- NA\n print(Factory(M_huge))\n}\n\n\n\nsystem.time(print(\"1\"))\nsystem.time(TestLimit(100,10))\nsystem.time(TestLimit(1000,100))\n# user system elapsed \n# 0.66 0.00 0.65\n\n# system.time(TestLimit(10000,1000))\n# user system elapsed \n# 135.03 0.67 135.84\n\n# system.time(TestLimit(100000,100))\n# user system elapsed \n# 86.28 0.13 86.42 \n\n# system.time(TestLimit(100000,10))\n# user system elapsed \n# 5.66 0.03 5.66 \n# registerDoParallel(cores=4)\n\n# Ten million - 10,000,000. That's pretty big\n# \n# system.time(TestLimit(5000,500))\n# user system elapsed \n# 13.53 0.02 13.52 \n\n#Solutions\n\n# [1] - cap the number of rows\n # in its current state, it is basically unlimited - unrealistic\n # the first 100,000 votes are probably decentralized enough ...how low should this number go? (can be a f[ncol(Vmatrix)])\n # given that reputation is fully additive, this would discourage the spreading of reputations\n # this would also solve the \"dust bust\" question (ie suck up any accounts with tiny dust amounts of reputation)\n # can add the slow retarget to make this grow over the next thousand years (every 4 years?)\n\n#after simply listing the specifics of this solution I realize it is the best candidate\n\n#Steps\n\n# [1] [CANCEL - BAD IDEA] Reward later factors (Comp.2, 3)? Seems risky...lets square the loadings or something to truly emphasize the first factor.\n# [2] [DONE] Build R (reward matrix) as a proportion.\n# [3] [DONE] What if the guy has no idea? NAs\n# [4] [DONE] Fix 'perfect consensus' bug.\n# [5] Reward function: a% of current reserve pool? [yes], payouts over time ? [this is whats happening, not finished yet]\n# [6] Scale Cost By Funds availiable [????]\n# [7] Add payment functionality (pay-per-vote)\n# [8] Functionality for new arrivals..old contracts missing data.\n# [9] [DONE] Remove incentive to create contracts where consensus is @.5 !\n# [10.a] [DONE] Univariate fill missing data in an incentive-consistent way.\n# [10.b] [part-DONE] Multivariate fill missing data (recursive? bootstrapped?) [chose simultaneous prediction, and ignore]\n# [10.c - FillNa should faithfully reproduce .5s] \n\n# [adding a NA to a contract can wipe out the validations there, ONLY when filling NA, - fix by using exponential smoothing to calc Rewards] [Fixed!]\n# [11] Ask - Ask people the outcomes of contracts...how to maximize (contract reward? d(Cr)?)\n\n#\n\n# [20 - Discourage \"Obvious Outcome\" Contracts by fee for open interest (more disagreement)]\n\n### \n\n\n\n\n# Ask <- function(M, p=.2, epsilon=.001) {\n# \n# #M is the target matrix, r the random variable assigned to a player\n# #p is the weight given to NAs versus disputed outcomes\n# #epsilon is the weight given to otherwise weightless contracts.\n# \n# Weight1 <- GetWeight( (Factory(M)[[2]][nrow(M)+4,]) + epsilon) #Na Weight\n# Weight2 <- Factory(M)[[2]][nrow(M)+2,] #Contract Reward weight\n# Weight2 <- GetWeight( ((.25)-(Weight2-.5)^2) + epsilon) #Transformation to find low-weighted \n# \n# WeightC <- p*Weight1 + (1-p)*Weight2\n# ConCol <- sample(1:ncol(M),1,prob=WeightC) \n# \n# #print(WeightC)\n# \n# return(ConCol)\n# }\n# \n# Ask(M1)\n\n# temp <- unlist(lapply(1:100,FUN=function(x) Ask(M10a)))\n# hist(temp)\n\n#see Governance\n# # [12] Create a New contract...it should cost(?)\n# NewContract <- function(M) { #This is going to rely on a time dimension I havent implemented yet\n# }\n# \n# OpenInterest <- function(M,c) {\n# \n# }\n\n# [11] [Done] Ask\n# [12] NewContract\n# [13] Open Interest - Two disagreeing parties each pay Ai (i in 1,2 ; Sum(A)=1) to mint two new coins -- eventually redeemable for 0 and 1-FEEepsilon .\n\n# [14] Subsidized Events - Principals paying Agents to influence the outcome of contracts.\n\n\n# [14a] A market for an event will allow it's occurance to be noted by the Factory after it's occurance.\n# [14b] Partition a 'Verification Space' (private information known only to the agent: date, time, colour, etc).\n# [14c] Allow private bets within the Verification Space - possibly a second set of Colored Coins \"specical coin\".\n# [14d] At EoC, people collect proportional to their holdings of insider-information coins.\n# [14e] Assurance contracts to allow anyone to fund a 'club good' event.\n\n\n\n#Plot\nPlotJ(M1)\n\n\n\n\n", "meta": {"hexsha": "4422f5805f7f6f85feaaf7167ee1aa5532e39e4f", "size": 17895, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/consensus/Old/Tests.r", "max_stars_repo_name": "endolith/Truthcoin", "max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 161, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z", "max_issues_repo_path": "lib/consensus/Old/Tests.r", "max_issues_repo_name": "endolith/Truthcoin", "max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z", "max_forks_repo_path": "lib/consensus/Old/Tests.r", "max_forks_repo_name": "endolith/Truthcoin", "max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z", "avg_line_length": 34.3474088292, "max_line_length": 179, "alphanum_fraction": 0.6283878178, "num_tokens": 5660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4634410665875987}} {"text": "calmod <- function(target,x,sumstat,tol,gwt,rejmethod=T)\n{\n# this function uses categorical regression to estimate the posterior probability of a particular model \n# under the ABC framework P(Y=y | S = s)\n#\n# target is the set of target summary stats - i.e. s, what you measured from the data.\n# x is the parameter vector, Y (long vector of numbers from the simulations) and is the dependent variable for the regression\n# This is a categorical variable, taking values 1, 2, .. n where there are n categories (models)\n# sumstat is an array of simulated summary stats, S (i.e. independent variables).\n# tol is the required proportion of points nearest the target values\n# gwt is a vector with T/F weights, weighting out any 'bad' values (determined by the simulation program - i.e. nan's etc)\n# if rejmethod=T it doesn't bother with the regression, and just does rejection.\n\n\n# If rejmethod=F it returns a list with the following components:-\n\n# $x1 expected value on a logit scale, with standard errors of the estimate\n# $x2 expected value on a natural scale - i.e. p(Y=y | S = s) This is what we would normally report.\n# $vals - the Ys in the rejection region. The proportion of the different Ys (different models) is a Pritchard etal-style, rejection-based\n# estimate of the posterior probability of the different models. You might get some improvement by \n# weighting the frequencies with $wt.\n# $wt - the Epanechnikov weight. \n# $ss - the sumstats corresponding to the points in $vals. \n\n\n\nif(missing(gwt))gwt <- rep(T,length(sumstat[,1]))\n\nnss <- length(sumstat[1,])\n\n\n# scale everything \n\n scaled.sumstat <- sumstat\n \n for(j in 1:nss){\n \n \tscaled.sumstat[,j] <- normalise(sumstat[,j],sumstat[,j][gwt])\n }\n target.s <- target\n \n for(j in 1:nss){\n \n \ttarget.s[j] <- normalise(target[j],sumstat[,j][gwt])\n }\n \n# calc euclidean distance\n\n sum1 <- 0\n for(j in 1:nss){\n \tsum1 <- sum1 + (scaled.sumstat[,j]-target.s[j])^2\n }\n dst <- sqrt(sum1)\n# includes the effect of gwt in the tolerance\n dst[!gwt] <- floor(max(dst[gwt])+10)\n \n\n# wt1 defines the region we're interested in \n abstol <- quantile(dst,tol)\n wt1 <- dst < abstol\n nit <- sum(wt1)\n \n if(rejmethod){\n l1 <- list(x=x[wt1],wt=0)\n }\n else{\n regwt <- 1-dst[wt1]^2/abstol^2\n \n catx <- as.numeric(names(table(x[wt1])))\n ncat <- length(catx)\n yy <- matrix(nrow=nit,ncol=ncat)\n for(j in 1:ncat){\n \tyy[,j] <- as.numeric(x[wt1] == catx[j])\n }\n \n tr <- list()\n\n for(j in 1:nss){\n \ttr[[j]] <- scaled.sumstat[wt1,j]\n }\n \n xvar.names <- paste(\"v\",as.character(c(1:nss)),sep=\"\")\n \n names(tr) <- xvar.names\n \n fmla <- as.formula(paste(\"yy ~ \", paste(xvar.names, collapse= \"+\")))\n \n# fit1 <- vglm(fmla,data=tr,multinomial) this is the version described in the \n# manuscript,which did not use the Epanechnikov weights. \n \n\n fit1 <- vglm(fmla,data=tr,multinomial,weights=regwt)\n \n target.df <- list()\n for(j in 1:nss){\n \ttarget.df[[j]] <- target.s[j]\n }\n names(target.df) <- xvar.names\n \n# prediction1 <- predict.vglm(fit1,target.df,se.fit=T) #commented 2014-12-10\n# prediction2 <- predict.vglm(fit1,target.df,type=\"response\") #commented 2014-12-10\n prediction1 <- predict(fit1,target.df,se.fit=T) #added 2014-12-10\n prediction2 <- predict(fit1,target.df,type=\"response\") #added 2014-12-10\n \n l1 <- list(x1=prediction1,x2=prediction2,vals=x[wt1],wt=regwt,ss=sumstat[wt1,])\n \n }\n l1\n}\n\n\nnormalise <- function(x,y){\n\nif(var(y) == 0)return (x - mean(y))\n(x-(mean(y)))/sqrt(var(y))\n}\n\n\n", "meta": {"hexsha": "9551d50341b8d68f24e84d531c9eec8f96821eb3", "size": 3909, "ext": "r", "lang": "R", "max_stars_repo_path": "practicals/practical3/bin/calmod.r", "max_stars_repo_name": "jsollari/IABC2017", "max_stars_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practicals/practical3/bin/calmod.r", "max_issues_repo_name": "jsollari/IABC2017", "max_issues_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practicals/practical3/bin/calmod.r", "max_forks_repo_name": "jsollari/IABC2017", "max_forks_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8487394958, "max_line_length": 139, "alphanum_fraction": 0.6009209517, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4625918616115392}} {"text": "subroutine acchk(i,j,k,anticl,x,y,ntot,eps)\n# Check whether vertices i, j, k, are in anti-clockwise order.\n# Called by locn, qtest, qtest1.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot), xt(3), yt(3)\nlogical anticl\n\n# Create indicator telling which of i, j, and k are ideal points.\nif(i<=0) i1 = 1\nelse i1 = 0\nif(j<=0) j1 = 1\nelse j1 = 0\nif(k<=0) k1 = 1\nelse k1 = 0\nijk = i1*4+j1*2+k1\n\n# Get the coordinates of vertices i, j, and k. (Pseudo-coordinates for\n# any ideal points.)\nxt(1) = x(i)\nyt(1) = y(i)\nxt(2) = x(j)\nyt(2) = y(j)\nxt(3) = x(k)\nyt(3) = y(k)\n\n# Get the ``normalized'' cross product.\ncall cross(xt,yt,ijk,cprd)\n\n# If cprd is positive then (ij-cross-ik) is directed ***upwards*** \n# and so i, j, k, are in anti-clockwise order; else not.\nif(cprd > eps) anticl = .true.\nelse anticl = .false.\nreturn\nend\n", "meta": {"hexsha": "0f130742b4a4d92c9053cbb3f881d3f5a37c3e80", "size": 837, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/acchk.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/acchk.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/acchk.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 23.25, "max_line_length": 70, "alphanum_fraction": 0.6487455197, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4618535550210357}} {"text": "#----------------------------------------------------------------------------------------------------------\n# Name: myEVfunctions.r\n# Purpose: External functions called by the EV_RL.r & EV_RP.r scripts \n# Author: Francesco Tonini\n# Email: \t f_tonini@hotmail.com\n# Created: 11/1/2009\n# Copyright: (c) 2009 by Francesco Tonini\n# License: \tGNU General Public License (GPL)\n# Software: Tested successfully using R-2.14.0 64-bit version(http://www.r-project.org/)\n#-------------------------------------------------------------------------------------------\n\n##CALL PACKAGES MODULE\n##This module is used to call all required packages\nload.packages <- function()\n{\t\n\t#setRepositories(ind=1:2)\n\tpkg <- c(\"ismev\",\"stats\",\"tcltk2\",\"RANN\",\"maptools\",\"evd\")\n\tw <- which(pkg %in% row.names(installed.packages()) == FALSE)\n\tif (length(w) > 0) install.packages(pkg)[w]\n\t#install.packages(c(\"ismev\",\"stats\",\"tcltk2\",\"RANN\",\"maptools\",\"evd\")) alternatively\n\t\n\t#Load (call) specific packages from the existing library collection into the current R session\n\trequire(ismev) #An Introduction to Statistical Modeling of Extreme Values\n\trequire(stats) #R statistical functions\n\trequire(tcltk2) #Tkinter objects and classes\n\trequire(RANN) #spatial functions (e.g. NN interpolation)\n\trequire(maptools) #reading and writing shapefiles\n\trequire(evd)\t\t #Functions for extreme value distributions\n\t#require(raster) #functions for raster data type\n\t#require(extRemes) #only for automatic return-values calculation\n\t\n\tcat('\\nAll libraries have been loaded successfully!\\n')\n}\n\n##GRADIENT FUNCTION MODULE\n##This module is used within the return level module to compute the confidence intervals\n##with delta method\ngevrlgradient<-function (z, p)\n{\n scale <- z$mle[2]\n shape <- z$mle[3]\n if (shape < 0)\n zero.p <- p == 0\n else zero.p <- logical(length(p))\n out <- matrix(NA, nrow = 3, ncol = length(p))\n out[1, ] <- 1\n if (any(zero.p)) {\n out[2, zero.p & !is.na(zero.p)] <- rep(-shape^(-1), sum(zero.p,\n na.rm = TRUE))\n out[3, zero.p & !is.na(zero.p)] <- rep(scale * (shape^(-2)),\n sum(zero.p, na.rm = TRUE))\n }\n if (any(!zero.p)) {\n yp <- -log(1 - p[!zero.p])\n out[2, !zero.p] <- -shape^(-1) * (1 - yp^(-shape))\n out[3, !zero.p] <- scale * (shape^(-2)) * (1 - yp^(-shape)) -\n scale * shape^(-1) * yp^(-shape) * log(yp)\n }\n return(out)\n}\n\n##RETURN LEVEL CALCULATION MODULE\n##This module computes return levels based on the distibution used (GEV, gumbel, GPD)\nreturn.levels <- function (z, conf = 0.05, rperiods = c(10, 100, 210, 510, 810, 980), make.plot = TRUE)\n{\n out <- list()\n out$conf.level <- conf\n eps <- 1e-06\n a <- z$mle\n\n #prova\n #a1<-z$mle[1] + z$mle[2]*rperiods\n \n std <- z$se\n mat <- z$cov\n dat <- z$data\n\t\n kappa <- qnorm(conf/2, lower.tail = FALSE)\n nx <- length(rperiods)\n cl <- 1 - conf\n\n if (class(z) == \"gev.fit\") {\n \n\t\tif (is.null(rperiods)) rperiods <- seq(1.1, 1000, , 200)\n if (any(rperiods <= 1))\n stop(\"return.level: this function presently only supports return periods >= 1\")\n yp <- -log(1 - 1/rperiods)\n if (a[3] < 0)\n zero.p <- yp == 0\n else zero.p <- logical(length(rperiods))\n zero.p[is.na(zero.p)] <- FALSE\n q <- numeric(length(rperiods))\n if (any(zero.p))\n q[zero.p] <- a[1] - a[2]/a[3]\n if (any(!zero.p)) {\n if (a[3] != 0)\n q[!zero.p] <- a[1] - (a[2]/a[3]) * (1 - (yp[!zero.p])^(-a[3]))\n else if (a[3] == 0)\n q[!zero.p] <- a[1] - a[2] * log(yp[!zero.p])\n }\n\t\t\n d <- gevrlgradient(z = z, p = 1/rperiods)\n v <- apply(d, 2, q.form, m = mat)\n yl <- c(min(dat, q, na.rm = TRUE), max(dat, q, na.rm = TRUE))\n if (make.plot) {\n xp <- 1/yp\n plot(xp, q, log = \"x\", type = \"n\", xlim = c(0.1,\n 1000), ylim = yl, xlab = \"Return Period\", ylab = \"Return Level\",\n xaxt = \"n\")\n axis(1, at = c(0.1, 1, 10, 100, 1000), labels = c(\"0.1\",\n \"1\", \"10\", \"100\", \"1000\"))\n lines(xp, q)\n lines(xp, (q + kappa * sqrt(v)), col = \"blue\")\n lines(xp, (q - kappa * sqrt(v)), col = \"blue\")\n points(-1/log((1:length(dat))/(length(dat) + 1)),\n sort(dat))\n }\n out$return.level <- q\n out$return.period <- rperiods\n conf3 <- cbind(q - kappa * sqrt(v), q + kappa * sqrt(v))\n colnames(conf3) <- c(\"lower\", \"upper\")\n out$confidence.delta <- conf3\n \n\t}\n\n\n\tif (class(z) == \"gum.fit\") {\n\n if (is.null(rperiods))\n rperiods <- seq(1.1, 1000, length=200)\n if (any(rperiods <= 1))\n stop(\"return.level: this function presently only supports return periods >= 1\")\n yp <- -log(1 - 1/rperiods)\n q <- a[1] - a[2] * log(yp)\n vq <- std[1]^2 + ((-log(yp))^2 * std[2]^2)\n\t sq <- sqrt(vq)\n\n\t\tyl <- c(min(dat, q, na.rm = TRUE), max(dat, q, na.rm = TRUE))\n if (make.plot) {\n xp <- 1/yp\n plot(xp, q, log = \"x\", type = \"n\", xlim = c(0.1,\n 1000), ylim = yl, xlab = \"Return Period\", ylab = \"Return Level\",\n xaxt = \"n\")\n axis(1, at = c(0.1, 1, 10, 100, 1000), labels = c(\"0.1\",\n \"1\", \"10\", \"100\", \"1000\"))\n lines(xp, q)\n lines(xp, (q + kappa * sq), col = \"blue\")\n lines(xp, (q - kappa * sq), col = \"blue\")\n points(-1/log((1:length(dat))/(length(dat) + 1)),\n sort(dat))\n }\n\n\t\tout$return.level <- q\n out$return.period <- rperiods\n conf3 <- cbind(q - kappa * sq, q + kappa * sq)\n colnames(conf3) <- c(\"lower\", \"upper\")\n out$confidence.delta <- conf3\n }\n\n\tif (class(z) == \"gpd.fit\") {\n\t\n u <- z$threshold\n la <- z$rate\n a <- c(la, a)\n n <- z$n\n npy <- z$npy\n xdat <- z$xdata\n if (is.null(rperiods)) {\n rperiods <- seq(0.1, 1000, , 200)\n }\n m <- rperiods * npy\n if (a[3] == 0)\n q <- u + a[2] * log(m * la)\n else q <- u + a[2]/a[3] * ((m * la)^(a[3]) - 1)\n d <- gpdrlgradient(z, m)\n mat <- matrix(c((la * (1 - la))/n, 0, 0, 0, mat[1, 1],\n mat[1, 2], 0, mat[2, 1], mat[2, 2]), nc = 3)\n v <- apply(d, 2, q.form, m = mat)\n yl <- c(u, max(xdat, q[q > u - 1] + kappa * sqrt(v)[q >\n u - 1], na.rm = TRUE))\n if (make.plot) {\n if (any(is.na(yl)))\n yl <- range(q, na.rm = TRUE)\n plot(m/npy, q, log = \"x\", type = \"n\", xlim = c(0.1,\n max(m)/npy), ylim = yl, xlab = \"Return period (years)\",\n ylab = \"Return level\", xaxt = \"n\")\n axis(1, at = c(0.1, 1, 10, 100, 1000), labels = c(\"0.1\",\n \"1\", \"10\", \"100\", \"1000\"))\n lines(m[q > u - 1]/npy, q[q > u - 1])\n lines((m[q > u - 1]/npy), (q[q > u - 1] + kappa *\n sqrt(v)[q > u - 1]), col = \"blue\")\n lines((m[q > u - 1]/npy), (q[q > u - 1] - kappa *\n sqrt(v)[q > u - 1]), col = \"blue\")\n nl <- n - length(dat) + 1\n sdat <- sort(xdat)\n points((1/(1 - (1:n)/(n + 1))/npy)[sdat > u], sdat[sdat >\n u])\n }\n out$return.level <- q\n out$return.period <- m/npy\n conf3 <- cbind(q[q > u - 1] - kappa * sqrt(v)[q > u -\n 1], q[q > u - 1] + kappa * sqrt(v)[q > u - 1])\n colnames(conf3) <- c(\"lower\", \"upper\")\n out$confidence.delta <- conf3\n \n }\n\ninvisible(out)\n\n}\n\n##NN INTERPOLATION FOR WARNINGS MODULE (FOR RETURN LEVELS)\n##This module serves the purpose of replacing pixels, flagged as warning in the main script\n##because of convergence issues, with the median of the nearest 4 or 8 neighbors\n\n##NOTE: this works better if the raster resolution is not too coarse and the terrain is \n##quite uniform to that of the central pixel. This is not recommended if that is not the case, or \n##if you are using a very coarse resolution raster (e.g. 10 Km or more).\nmedian.interp_RL <- function()\n{\n\t\n\tMatr_coord <- cbind(dataset[1:npixels,]$x, dataset[1:npixels,]$y)\n\t\n\tfor (px in px.idWarning){\n\t\n\t\t#Rook's neighborhood (using the 'spdep' package)\n\t\tNN4 <- knearneigh(Matr_coord,4)\n\t\tMatr_NN4 <- NN4$nn\n\t\t\n\t\t#Queen's neighborhood (using the 'spdep' package)\n\t\t#NN8 <- knearneigh(Matr_coord,8)\n\t\t#Matr_NN8 <- NN8$nn\n\n\t\t#take a subset of the NN matrix only for the pixels flagged with a warning\n\t\tSub4 <- Matr_NN4[px,]\n\t\t#Sub8 <- Matr_NN8[px,]\n\t\t\n\t\tMat_param <- tab.parameters[Sub4,]\n\t\tMat_rlevels <- tab.rlevels[Sub4,]\n\t\t\n\t\ttab.parameters[px,3:length(tab.parameters)] <- round(sapply(Mat_param[,-c(1:2)],median),2)\n\t\ttab.rlevels[px,2:length(tab.rlevels)] <- round(sapply(Mat_rlevels[,-1],median),2)\n\t}\n\n}\n\n##NN INTERPOLATION FOR WARNINGS MODULE (FOR PROBABILITY EXCEEDANCES)\n##This module serves the purpose of replacing pixels, flagged as warning in the main script\n##because of convergence issues, with the median of the nearest 4 or 8 neighbors\n\n##NOTE: this works better if the raster resolution is not too coarse and the terrain is \n##quite uniform to that of the central pixel. This is not recommended if that is not the case, or \n##if you are using a very coarse resolution raster (e.g. 10 Km or more).\nmedian.interp_RP <- function()\n{\n\t\n\tMatr_coord <- cbind(dataset[1:npixels,]$x, dataset[1:npixels,]$y)\n\t\n\tfor (px in px.idWarning){\n\t\n\t\t#Rook's neighborhood (using the 'spdep' package)\n\t\tNN4 <- knearneigh(Matr_coord,4)\n\t\tMatr_NN4 <- NN4$nn\n\t\t\n\t\t#Queen's neighborhood (using the 'spdep' package)\n\t\t#NN8 <- knearneigh(Matr_coord,8)\n\t\t#Matr_NN8 <- NN8$nn\n\n\t\t#take a subset of the NN matrix only for the pixels flagged with a warning\n\t\tSub4 <- Matr_NN4[px,]\n\t\t#Sub8 <- Matr_NN8[px,]\n\t\t\n\t\tMat_param <- tab.parameters[Sub4,]\n\t\tMat_prob <- tab.prob[Sub4,]\n\t\t\n\t\ttab.parameters[px,3:length(tab.parameters)] <- round(sapply(Mat_param[,-c(1:2)],median),2)\n\t\ttab.prob[px,2:length(tab.prob)] <- round(sapply(Mat_prob[,-1],median),2)\n\t}\n\n}\n\n##SAVE SHAPEFILE MODULE (FOR RETURN LEVELS)\n##This module is used to save a point dataset to a shapefile (.shp)\nsave_files_RL <- function()\n{\n\t\n\tMatr_coord <- cbind(dataset[1:npixels,]$x, dataset[1:npixels,]$y)\n\t\n\ttab.parameters$X <- Matr_coord[,1]\n\ttab.parameters$Y <- Matr_coord[,2]\n\ttab.rlevels$X <- Matr_coord[,1]\n\ttab.rlevels$Y <- Matr_coord[,2]\n\t\n\t##Turn input point dataset into a SpatialPointsDataFrame\n\tcoordinates(tab.parameters) <- ~X+Y\n\tcoordinates(tab.rlevels) <- ~X+Y\n\t\n\t##Path to folder\n\tpath <- file.path(mainDir, subDir)\n\t\n\t##Write .csv tables\n\twrite.table(tab.parameters, paste(path,'/MLE_Parameters.csv',sep=''), row.names=F, sep=',')\n\twrite.table(tab.rlevels, paste(path,'/ReturnLevels.csv',sep=''), row.names=F, sep=',')\n\t\n\t##Write/Save the shapefile (library 'maptools')\n\twriteSpatialShape( tab.parameters, paste(path,'/MLE_Parameters',sep='') )\n\twriteSpatialShape( tab.rlevels, paste(path,'/ReturnLevels',sep='') )\n\t\n\t##Write/Save rasters (library 'raster')\n\t\n}\n\n##SAVE SHAPEFILE MODULE (FOR PROBABILITY EXCEEDANCES)\n##This module is used to save a point dataset to a shapefile (.shp)\nsave_files_RP <- function()\n{\n\t\n\tMatr_coord <- cbind(dataset[1:npixels,]$x, dataset[1:npixels,]$y)\n\t\n\ttab.parameters$X <- Matr_coord[,1]\n\ttab.parameters$Y <- Matr_coord[,2]\n\ttab.prob$X <- Matr_coord[,1]\n\ttab.prob$Y <- Matr_coord[,2]\n\t\n\t##Turn input point dataset into a SpatialPointsDataFrame\n\tcoordinates(tab.parameters) <- ~X+Y\n\tcoordinates(tab.prob) <- ~X+Y\n\t\n\t##Path to folder\n\tpath <- file.path(mainDir, subDir)\n\t\n\t##Write .csv tables\n\twrite.table(tab.parameters, paste(path,'/MLE_Parameters.csv',sep=''), row.names=F, sep=',')\n\twrite.table(tab.prob, paste(path,'/ProbExceedance.csv',sep=''), row.names=F, sep=',')\n\t\n\t##Write/Save the shapefile (library 'maptools')\n\twriteSpatialShape( tab.parameters, paste(path,'/MLE_Parameters',sep='') )\n\twriteSpatialShape( tab.prob, paste(path,'/ProbExceedance',sep='') )\n\t\n\t##Write/Save rasters (library 'raster')\n\t\n}\n\n\n##PROBABILITY OF EXCEEDANCE MODULE\n##This module is used to calculate the probability that the event will be exceeded in any one month\n##(or year, or season, depending on what is your maxima/minima time series unit). \n##The return period is the inverse of the probability of exceedance\nprob_fun <- function(dataset,value,tab.extreme,nome,n=3){\n\t\n\tpx.prob <- round(1 - pgev(-return_levels, loc=mu, scale=sig, shape=shp), 3)\n\t\n\t#Use the following line, and not the previous, if you are working with MAXIMA instead of MINIMA\n\t#px.prob <- round(1 - pgev(-return_levels, loc=mu, scale=sig, shape=shp), 3)\n\t\n\t#NOTE: the return period will then simply be 1/prob (in the time unit used, e.g. months)\n\t\n\treturn(px.prob)\n\n}\n\n\n\n\n\t\n", "meta": {"hexsha": "9262a1bf0ea3fa89e3cdc00d968d2d7df13ce58a", "size": 12919, "ext": "r", "lang": "R", "max_stars_repo_path": "myEVfunctions.r", "max_stars_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_stars_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "myEVfunctions.r", "max_issues_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_issues_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "myEVfunctions.r", "max_forks_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_forks_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2978142077, "max_line_length": 107, "alphanum_fraction": 0.5671491602, "num_tokens": 4044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.4615525552939687}} {"text": "source('black-scholes.r')\n\npar(family=\"sans\", mar=c(4,4,1,2)+0.1, mgp=c(2,1,0))\n\ndump <- function(filename) {\n fn <- paste(\"images/\", filename, \".pdf\", sep=\"\")\n dev.copy2pdf(file=fn, family=\"sans\")\n}\n\nplot(function(S){bscall.value(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\")\nplot(function(S){bsput.value(S,100,0.5,0.05,0.20)}, 70, 130, add=T, col=\"#d63d00\", lwd=3)\ntitle(main='', xlab='Stock Price', ylab='Value')\nlegend('topleft', c('Call', 'Put'), lwd=3, col=c(\"#19304f\",\"#d63d00\"), bty='n')\nabline(v=100,lty=3)\ndump('bs-value')\n\nplot(function(S){bscall.delta(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(-1,1))\nplot(function(S){bsput.delta(S,100,0.5,0.05,0.20)}, 70, 130, add=T, col=\"#d63d00\", lwd=3)\nabline(0,0)\ntitle('', xlab='Stock Price', ylab='Delta')\nlegend('topleft', c('Call', 'Put'), lwd=3, col=c(\"#19304f\",\"#d63d00\"), bty='n')\ndump('bs-delta')\n\nplot(function(S){bscall.delta(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\")\nplot(function(S){bscall.delta(S,100,0.5,0.05,0.10)}, 70, 130, col=\"#d63d00\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\nplot(function(S){bscall.delta(S,100,0.5,0.05,0.05)}, 70, 130, col=\"#227711\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\ntitle('', xlab='Stock Price', ylab='Delta')\nlegend('topleft', c('sigma = 0.2','sigma = 0.1','sigma = 0.05'), lwd=3, col=c(\"#19304f\",\"#d63d00\",\"#227711\"), bty='n')\ndump('bs-delta-sigma')\n\nplot(function(S){bscall.delta(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\")\nplot(function(S){bscall.delta(S,100,0.2,0.05,0.20)}, 70, 130, col=\"#d63d00\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\nplot(function(S){bscall.delta(S,100,0.05,0.05,0.20)}, 70, 130, col=\"#227711\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\ntitle('', xlab='Stock Price', ylab='Delta')\nlegend('topleft', c('TTM = 0.5','TTM = 0.2','TTM = 0.05'), lwd=3, col=c(\"#19304f\",\"#d63d00\",\"#227711\"), bty='n')\ndump('bs-delta-ttm')\n\nplot(function(S){bscall.gamma(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,0.03))\ntitle('', xlab='Stock Price', ylab='Gamma')\nlegend('topleft', c('Call Gamma'), lwd=3, col=c(\"#19304f\",\"#d63d00\"), bty='n')\ndump('bs-gamma')\n\nplot(function(S){bscall.value(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\")\nplot(function(S){bscall.value(S,100,0.2,0.05,0.20)}, 70, 130, col=\"#d63d00\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\nplot(function(S){bscall.value(S,100,0.01,0.05,0.20)}, 70, 130, col=\"#227711\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30), add=T)\ntitle('', xlab='Stock Price', ylab='Value')\nlegend('topleft', c('TTM = 0.5','TTM = 0.2','TTM = 0.01'), lwd=3, col=c(\"#19304f\",\"#d63d00\",\"#227711\"), bty='n')\ndump('bs-value-ttm')\n\nplot(function(S){bscall.theta(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(-10,8))\nplot(function(S){bsput.theta(S,100,0.5,0.05,0.20)}, 70, 130, add=T, col=\"#d63d00\", lwd=3)\nabline(0,0)\ntitle('', xlab='Stock Price', ylab='Theta')\nlegend('topleft', c('Call', 'Put'), lwd=3, col=c(\"#19304f\",\"#d63d00\"), bty='n')\ndump('bs-theta')\n\nplot(function(S){bscall.gamma(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,0.07))\nplot(function(S){bscall.gamma(S,100,0.2,0.05,0.20)}, 70, 130, col=\"#d63d00\", lwd=3, xlab=\"\", ylab=\"\", add=T)\nplot(function(S){bscall.gamma(S,100,0.1,0.05,0.20)}, 70, 130, col=\"#227711\", lwd=3, xlab=\"\", ylab=\"\", add=T)\ntitle('', xlab='Stock Price', ylab='Gamma')\nlegend('topleft', c('TTM = 0.5','TTM = 0.2','TTM = 0.1'), lwd=3, col=c(\"#19304f\",\"#d63d00\",\"#227711\"), bty='n')\ndump('bs-gamma-ttm')\n\nplot(function(S){bscall.theta(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(-15,5))\nplot(function(S){bscall.theta(S,100,0.2,0.05,0.20)}, 70, 130, col=\"#d63d00\", lwd=3, xlab=\"\", ylab=\"\", add=T)\nplot(function(S){bscall.theta(S,100,0.1,0.05,0.20)}, 70, 130, col=\"#227711\", lwd=3, xlab=\"\", ylab=\"\", add=T)\nabline(0,0)\ntitle('', xlab='Stock Price', ylab='Theta')\nlegend('topleft', c('TTM = 0.5','TTM = 0.2','TTM = 0.1'), lwd=3, col=c(\"#19304f\",\"#d63d00\",\"#227711\"), bty='n')\ndump('bs-theta-ttm')\n\nplot(function(S){bscall.vega(S,100,0.5,0.05,0.20)}, 70, 130, col=\"#19304f\", lwd=3, xlab=\"\", ylab=\"\", ylim=c(0,30))\ntitle('', xlab='Stock Price', ylab='Vega')\nlegend('topleft', c('Call Vega'), lwd=3, col=c(\"#19304f\",\"#d63d00\"), bty='n')\ndump('bs-vega')\n", "meta": {"hexsha": "59d375d9734229756d1ad16332631297111327c5", "size": 4424, "ext": "r", "lang": "R", "max_stars_repo_path": "moreplots.r", "max_stars_repo_name": "Richard-L-Johnson/black-scholes-R", "max_stars_repo_head_hexsha": "654ed90aef632ec2717e60f19d426ec9e784bf44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T02:44:51.000Z", "max_issues_repo_path": "moreplots.r", "max_issues_repo_name": "Richard-L-Johnson/black-scholes-R", "max_issues_repo_head_hexsha": "654ed90aef632ec2717e60f19d426ec9e784bf44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moreplots.r", "max_forks_repo_name": "Richard-L-Johnson/black-scholes-R", "max_forks_repo_head_hexsha": "654ed90aef632ec2717e60f19d426ec9e784bf44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2015-01-17T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T07:39:25.000Z", "avg_line_length": 58.2105263158, "max_line_length": 123, "alphanum_fraction": 0.5992314647, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.4610629204306478}} {"text": "#Addition\n4+4\n#Substraction\n52-22\n#Division\n15/3\n#Multiplication\n6*3\n#Division\n3^2\n#Modulus\n100%%10\n3^2:\n\n#Assigning values \na<-4\nb<-5\na+b # Calculation\n", "meta": {"hexsha": "e8a2494bbfbc2339d251660ad41f28ac6a541e9d", "size": 154, "ext": "r", "lang": "R", "max_stars_repo_path": "Source Code/Operators.r", "max_stars_repo_name": "Julezclaess/RForNoobs", "max_stars_repo_head_hexsha": "779db520753ef8c226257c3e4d8343b2eddc9bf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-31T17:27:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-31T17:27:55.000Z", "max_issues_repo_path": "Source Code/Operators.r", "max_issues_repo_name": "Julezclaess/RForNoobs", "max_issues_repo_head_hexsha": "779db520753ef8c226257c3e4d8343b2eddc9bf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source Code/Operators.r", "max_forks_repo_name": "Julezclaess/RForNoobs", "max_forks_repo_head_hexsha": "779db520753ef8c226257c3e4d8343b2eddc9bf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-28T17:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-28T17:33:51.000Z", "avg_line_length": 8.1052631579, "max_line_length": 19, "alphanum_fraction": 0.7077922078, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.460901426915192}} {"text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n#' Estimate variance components using EMMA\n#'\n#' Build date: August 30, 2016\n#' Last update: January 27, 2017\n#' \n#' @author EMMA (Kang et. al. Genetics, 2008), Modified only for speed up by Xiaolei Liu and Lilin Yin\n#' \n#' @param y phenotype, n * 2\n#' @param X covariate matrix, the first column is 1s\n#' @param K Kinship matrix\n#' @param ngrids parameters for estimating vg and ve\n#' @param llim parameters for estimating vg and ve\n#' @param ulim parameters for estimating vg and ve\n#' @param esp parameters for estimating vg and ve\n#'\n#' @return\n#' Output: REML - maximum log likelihood\n#' Output: delta - exp(root)\n#' Output: ve - residual variance\n#' Output: vg - genetic variance\n#' \n#' @export\n#'\n#' @examples\n#' phePath <- system.file(\"extdata\", \"07_other\", \"mvp.phe\", package = \"rMVP\")\n#' phenotype <- read.table(phePath, header=TRUE)\n#' print(dim(phenotype))\n#' genoPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.desc\", package = \"rMVP\")\n#' genotype <- attach.big.matrix(genoPath)\n#' print(dim(genotype))\n#' \n#' K <- MVP.K.VanRaden(genotype)\n#' vc <- MVP.EMMA.Vg.Ve(y=phenotype[,2], X=matrix(1, nrow(phenotype)), K=K)\n#' print(vc)\n#' \nMVP.EMMA.Vg.Ve <-\nfunction(y, X, K, ngrids=100, llim=-10, ulim=10, esp=1e-10) {\n # NA in phenotype\n idx <- !is.na(y)\n y <- y[idx]\n X <- as.matrix(X[idx, ])\n K <- K[idx, idx]\n \n if(!is.numeric(y))\ty <- as.numeric(as.character(y))\n emma.delta.REML.LL.wo.Z <- function(logdelta, lambda, etas)\n {\n nq <- length(etas)\n delta <- exp(logdelta)\n return( 0.5 * (nq * (log(nq/(2 * pi))-1-log(sum(etas * etas/(lambda + delta))))-sum(log(lambda + delta))) )\n }\n emma.eigen.R.wo.Z=function(K, X) {\n n <- nrow(X)\n q <- ncol(X)\n \n XX <- crossprod(X)\n iXX <- try(solve(XX), silent = TRUE)\n if(inherits(iXX, \"try-error\")){\n #library(MASS)\n iXX <- ginv(XX)\n }\n\n SS1 <- X %*% iXX\n SS2 <- tcrossprod(SS1, X)\n S <- diag(n)-SS2\n \n eig <- eigen(S %*% (K + diag(1, n)) %*% S, symmetric=TRUE)#S4 error here\n\n stopifnot(!is.complex(eig$values))\n return(list(values=eig$values[1:(n-q)]-1, vectors=eig$vectors[, 1:(n-q)]))\n }\n eig.R=emma.eigen.R.wo.Z(K=K, X=X)\n n <- length(y)\n t <- nrow(K)\n q <- ncol(X)\n\n stopifnot(ncol(K) == t)\n stopifnot(nrow(X) == n)\n\n etas <- crossprod(eig.R$vectors, y)\n \n logdelta <- (0:ngrids)/ngrids * (ulim-llim) + llim\n m <- length(logdelta)\n delta <- exp(logdelta)\n Lambdas <- matrix(eig.R$values, n-q, m) + matrix(delta, n-q, m, byrow=TRUE)\n Etasq <- matrix(etas * etas, n-q, m)\n LL <- 0.5 * ((n-q) * (log((n-q)/(2 * pi))-1-log(colSums(Etasq/Lambdas)))-colSums(log(Lambdas)))\n dLL <- 0.5 * delta * ((n-q) * colSums(Etasq/(Lambdas * Lambdas))/colSums(Etasq/Lambdas)-colSums(1/Lambdas))\n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(llim, eig.R$values, etas))\n }\n if( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(ulim, eig.R$values, etas))\n }\n for(i in 1:(m-1) ){\n if( ( dLL[i] * dLL[i + 1] < 0 ) && ( dLL[i] > 0 ) && ( dLL[i + 1] < 0 ) ) {\n emma.delta.REML.dLL.wo.Z <- function(logdelta, lambda, etas) {\n nq <- length(etas)\n delta <- exp(logdelta)\n etasq <- etas * etas\n ldelta <- lambda + delta\n return( 0.5 * (nq * sum(etasq/(ldelta * ldelta))/sum(etasq/ldelta)-sum(1/ldelta)) )\n }\n r <- uniroot(emma.delta.REML.dLL.wo.Z, lower=logdelta[i], upper=logdelta[i + 1], lambda=eig.R$values, etas=etas)\n optlogdelta <- append(optlogdelta, r$root)\n emma.delta.REML.LL.wo.Z <- function(logdelta, lambda, etas) {\n nq <- length(etas)\n delta <- exp(logdelta)\n return( 0.5 * (nq * (log(nq/(2 * pi))-1-log(sum(etas * etas/(lambda + delta))))-sum(log(lambda + delta))) )\n }\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(r$root, eig.R$values, etas))\n }\n }\n maxdelta <- exp(optlogdelta[which.max(optLL)])\n #handler of grids with NaN log\n replaceNaN<-function(LL) {\n index=(LL == \"NaN\")\n if(length(index)>0) theMin=min(LL[!index])\n if(length(index)<1) theMin=\"NaN\"\n LL[index]=theMin\n return(LL) \n }\n optLL=replaceNaN(optLL) \n maxLL <- max(optLL)\n maxva <- sum(etas * etas/(eig.R$values + maxdelta))/(n-q) \n maxve <- maxva * maxdelta\n return (list(REML=maxLL, delta=maxdelta, ve=maxve, vg=maxva))\n}# end of MVP.EMMA.Vg.Ve function\n", "meta": {"hexsha": "a08618db2d3f0d4dbb80ac757abc90b83f90e724", "size": 5371, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.EMMA.Vg.Ve.r", "max_stars_repo_name": "xiaolei-lab/rMVP", "max_stars_repo_head_hexsha": "6ad1b94c208becc190b5facb2bbc9a9fff9a8353", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 99, "max_stars_repo_stars_event_min_datetime": "2019-10-14T09:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:45:16.000Z", "max_issues_repo_path": "R/MVP.EMMA.Vg.Ve.r", "max_issues_repo_name": "hxxonly/rMVP", "max_issues_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2019-10-20T15:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:20:16.000Z", "max_forks_repo_path": "R/MVP.EMMA.Vg.Ve.r", "max_forks_repo_name": "hxxonly/rMVP", "max_forks_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2019-10-18T02:22:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T08:19:43.000Z", "avg_line_length": 37.0413793103, "max_line_length": 124, "alphanum_fraction": 0.5812697822, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.460901426915192}} {"text": "########################### BayesKin ###########################\n## Bayesian estimates of rigid body kinematics\n## Andy Pohl\n## UofC - Faculty of Kinesiology\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: May 2020\n################################################################\n\n##################### SupplementE.r ###################\n## Performs additional analysis examining the robustness of Bayesian models to\n## increases in measurement noise\n################################################################\n\n## Preliminaries\nrm(list = ls())\n\nWORKING_DIR = \"/media/data/ActiveProjects/P01_BayesianKinematics/PublishedCode/BayesKin/src/SupplementE\" # Replace with appropriate location of working directory on local PC\nSAVE_MDL = TRUE # assume save\nINIT_TYPE = 'true_vals' # either 'true_vals', 'ls_est', 'random\nNITS = 1000 # number of iterations.\n\nsetwd(WORKING_DIR)\n\n# External libraries\nlibrary('dplyr')\nlibrary('latex2exp')\n\nsource('./library.r') # Retrieve function library\n\nset.seed(1) # Set seed for reproducibility\n\n########################### Section A #########################\n## Specify simulation parameters\n################################################################\n\n## 1) Specify parameters\nn.links = 1 # Number of links.\nseg.length = c(0.45) # Length of segment specified in m. NB: Pataky pg 2.\nr_true = c(0.07, 0.03) # Origin location in m.\ntheta_true = c(-55) # Rotation angle in deg. NB: specified to avoid 0/360 issue\n# and mirroring solutions.\nsigma_true = c(0.1, 1.5, 5, 10, 20,40)*(1/1000) # Measurement Noise in m \nlinks = list(gen_link(seg.length = seg.length[1],\n plate.center = 0.7*seg.length[1])) # Link geometry\n\n\n########################### Section B #########################\n## Run simulations \n # run NITS iterations per sigma level\n################################################################\nresults = matrix(NA, nrow = length(sigma_true)*NITS*5, ncol = 7)\nrow_idx =1\nfor(i in 1:length(sigma_true)){\n true_vals = list(r_true = r_true, theta_true = theta_true, sigma_true = sigma_true[i])\n \n # Generate posture\n posture = gen_posture(links, r = true_vals$r_true, theta = true_vals$theta_true)\n seeds = 1:NITS # Generate seed values for each iteration\n \n for(j in 1:NITS){\n seed = seeds[j]\n set.seed(seed)\n print(sprintf(\"--------------------Iteration %.0f of %.0f - seed = %.0f---------------------\\n\",j, NITS, seed))\n # gen obs\n y = gen_obs(posture, true_vals$sigma_true)\n #plot_system(posture = posture, y=y)\n print(\"Compute LS solution.\")\n LS_result = LS_soln(y, links,\n inits = c(true_vals$r_true, true_vals$theta_true, true_vals$sigma_true),\n init_type = 'true_vals')\n results[row_idx,] = c(true_vals$sigma_true, 1, seed, LS_result$r.hat[1], LS_result$r.hat[2], LS_result$theta.hat[1],LS_result$sigma.hat)\n row_idx = row_idx+1\n \n Bayes1_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_vague1.jags', # Vague 1\n init_type = INIT_TYPE,\n true_vals = c(true_vals$r_true,true_vals$theta_true, true_vals$sigma_true),\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat)) \n Bayes1_result = summary(Bayes1_result$fit)\n results[row_idx,] = c(true_vals$sigma_true, 2, seed, Bayes1_result$statistics['r[1]',1], Bayes1_result$statistics['r[2]',1], Bayes1_result$statistics['theta',1], Bayes1_result$statistics['sigma',1])\n row_idx = row_idx +1\n \n Bayes2_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_vague2.jags', # Vague 2\n init_type = INIT_TYPE,\n true_vals = c(true_vals$r_true,true_vals$theta_true, true_vals$sigma_true),\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat)) \n Bayes2_result = summary(Bayes2_result$fit)\n results[row_idx,] = c(true_vals$sigma_true, 3, seed, Bayes2_result$statistics['r[1]',1], Bayes2_result$statistics['r[2]',1], Bayes2_result$statistics['theta',1], Bayes2_result$statistics['sigma',1])\n row_idx = row_idx +1\n \n Bayes4_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p3.jags', # Weakly Informative\n init_type = INIT_TYPE,\n true_vals = c(true_vals$r_true,true_vals$theta_true, true_vals$sigma_true),\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat)) \n Bayes4_result = summary(Bayes4_result$fit)\n results[row_idx,] = c(true_vals$sigma_true, 4, seed, Bayes4_result$statistics['r[1]',1], Bayes4_result$statistics['r[2]',1], Bayes4_result$statistics['theta[1]',1], Bayes4_result$statistics['sigma',1])\n row_idx = row_idx +1\n \n Bayes5_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p2.jags', # Informative\n init_type = INIT_TYPE,\n true_vals = c(true_vals$r_true,true_vals$theta_true, true_vals$sigma_true),\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n \n Bayes5_result = summary(Bayes5_result$fit)\n results[row_idx,] = c(true_vals$sigma_true, 5, seed, Bayes5_result$statistics['r[1]',1], Bayes5_result$statistics['r[2]',1], Bayes5_result$statistics['theta',1],Bayes5_result$statistics['sigma',1])\n row_idx = row_idx +1\n \n }\n}\n\nif(SAVE_MDL){\n saveRDS(results, \"./DeltaVarResults.rds\")\n}\nresults = readRDS('./DeltaVarResults.rds')\n\n########################### Section C #########################\n## Process results and generate figures\n################################################################\nmodels = c('LS', 'Bayes Vague 1', \"Bayes Vague 2\", \n 'Bayes Weakly Informative', 'Bayes Informative')\n\nabs_error = matrix(NA, nrow = length(sigma_true)*length(models)*4, ncol = 6)\nabs_error = data.frame(abs_error)\nnames(abs_error) = c('sigma', 'Model', 'Parameter', 'lwr', 'med', 'upr')\n\nperf = matrix(NA, nrow = 3*length(sigma_true)*length(models), ncol = 4)\nperf = data.frame(perf)\nnames(perf) = c('sigma', 'Model', 'Parameter', 'Perf')\nrow_idx = 1\nrow_idx2 = 1\nfor(i in 1:length(sigma_true)){\n sigma_result = results[results[,1]==sigma_true[i],]\n for(j in 1:length(models)){ # Summarize abs error of each model\n mdl_result = sigma_result[sigma_result[,2] == j,]\n abs_error[row_idx,1] = unique(mdl_result[,1])\n abs_error[row_idx,2] = unique(mdl_result[,2])\n abs_error[row_idx,3] = 'rx'\n abs_error[row_idx, 4:6] = quantile(abs(mdl_result[,4] - r_true[1]), probs = c(0.025, 0.5, 0.975))*1000\n row_idx = row_idx+1\n \n abs_error[row_idx,1] = unique(mdl_result[,1])\n abs_error[row_idx,2] = unique(mdl_result[,2])\n abs_error[row_idx,3] = 'ry'\n abs_error[row_idx, 4:6] = quantile(abs(mdl_result[,5] - r_true[2]), probs = c(0.025, 0.5, 0.975))*1000\n row_idx = row_idx+1\n \n abs_error[row_idx,1] = unique(mdl_result[,1])\n abs_error[row_idx,2] = unique(mdl_result[,2])\n abs_error[row_idx,3] = 'theta1'\n abs_error[row_idx, 4:6] = quantile(abs(mdl_result[,6] - theta_true[1]), probs = c(0.025, 0.5, 0.975))\n row_idx = row_idx+1\n\n abs_error[row_idx,1] = unique(mdl_result[,1])\n abs_error[row_idx,2] = unique(mdl_result[,2])\n abs_error[row_idx,3] = 'sigma'\n abs_error[row_idx, 4:6] = quantile(abs(mdl_result[,7] - sigma_true[i]), probs = c(0.025, 0.5, 0.975))*1000\n row_idx = row_idx +1\n \n if(j >=2){ # Compute performance of Bayes vs LS.\n perf[row_idx2,1] = unique(mdl_result[,1])\n perf[row_idx2,2] = unique(mdl_result[,2])\n perf[row_idx2,3] = 'rx'\n perf[row_idx2,4] = mean(abs(mdl_result[,4] - r_true[1]) < abs(sigma_result[sigma_result[,2] == 1,4] - r_true[1]))\n row_idx2 = row_idx2 +1\n \n perf[row_idx2,1] = unique(mdl_result[,1])\n perf[row_idx2,2] = unique(mdl_result[,2])\n perf[row_idx2,3] = 'ry'\n perf[row_idx2,4] = mean(abs(mdl_result[,5] - r_true[2]) < abs(sigma_result[sigma_result[,2] == 1,5] - r_true[2]))\n row_idx2 = row_idx2 +1\n \n perf[row_idx2,1] = unique(mdl_result[,1])\n perf[row_idx2,2] = unique(mdl_result[,2])\n perf[row_idx2,3] = 'theta1'\n perf[row_idx2,4] = mean(abs(mdl_result[,6] - theta_true[1]) < abs(sigma_result[sigma_result[,2] == 1,6] - theta_true[1]))\n row_idx2 = row_idx2 +1\n\n perf[row_idx2,1] = unique(mdl_result[,1])\n perf[row_idx2,2] = unique(mdl_result[,2])\n perf[row_idx2,3] = 'sigma'\n perf[row_idx2,4] = mean(abs(mdl_result[,7] - sigma_true[i]) < abs(sigma_result[sigma_result[,2] == 1,7] - sigma_true[i]))\n row_idx2 = row_idx2 +1\n }\n }\n}\nabs_error$sigma = abs_error$sigma*1000\nperf$sigma = perf$sigma*1000\n\n########################### Section D #########################\n## Generate figures and tables\n################################################################\n\n# Color scheme\ncolors = list(grey = rgb(97/255, 97/255,97/255, 0.2),\n orange = rgb(241/255, 136/255,5/255, 1),\n blue = rgb(18/255, 78/255,120/255, 0.2),\n light_blue = rgb(93/255, 173/255,226/255, 0.2),\n red = rgb(162/255, 0/255,33/255, 0.2),\n green = rgb(76/255, 159/255, 112/255, 0.2),\n purple = rgb(217/255, 187/255, 249/255, 0.2),\n pink = rgb(217/255, 3/255, 104/255, 0.2))\n\n\ncolors2 = list(grey = rgb(97/255, 97/255,97/255, 0.2),\n orange = rgb(241/255, 136/255,5/255, 1),\n blue = rgb(18/255, 78/255,120/255, 1),\n light_blue = rgb(93/255, 173/255,226/255, 1),\n red = rgb(162/255, 0/255,33/255, 1),\n green = rgb(76/255, 159/255, 112/255, 1),\n purple = rgb(217/255, 187/255, 249/255, 1),\n pink = rgb(217/255, 3/255, 104/255, 1))\npoint_cols = list(colors$pink, colors$blue,colors$light_blue, colors$purple,colors$green)\npoint_cols2 = list(colors2$pink, colors2$blue,colors2$light_blue, colors2$purple,colors2$green)\n\n## -----------------------------------------------------------------------------\n# Figure 1 'Line' plot of absolute error accross strain.\n## -----------------------------------------------------------------------------\n\nylabs = c(TeX(\"Absolute Error $\\\\hat{r}_x \\\\, (mm)$\"), TeX(\"Absolute Error $\\\\hat{r}_y \\\\, (mm)$\"), TeX(\"Absolute Error $\\\\hat{\\\\theta}_1 \\\\, (deg)$\"), TeX(\"Absolute Error $\\\\hat{\\\\sigma} \\\\, (mm)$\"))\ntitles = c(TeX(\"$r_x$\"), TeX(\"$r_y$\"), TeX('$\\\\theta_1'), TeX(\"$\\\\sigma$\"))\ntitles = c(\"(a)\",\"(b)\",'(c)',\"(d)\")\n\nparameters = c('rx', 'ry', 'theta1', 'sigma')\nylims = list(c(0, 250), c(0,250), c(0, 60), c(0, 40))\n# j = 1:4 parameters\n# i = 1:5 models\n\npar(mfrow=c(1,4))\nfor(j in 1:4){\n for(i in 1:5){\n parm_abs_error = abs_error %>% filter(Parameter ==parameters[j])\n\n mdl_abs_error = parm_abs_error %>% filter(Model ==i)\n jitter = (2-(5-i)) * 0.05*mdl_abs_error[,1]\n \n plot_col2 = point_cols2[[i]]\n plot_col1 = point_cols[[i]]\n if(i ==1){\n plot(mdl_abs_error$sigma + jitter, mdl_abs_error$med,type = 'b', pch = 16, col =plot_col2,\n xlab = TeX(\"Noise Level: $\\\\sigma \\\\, (mm)$\"), ylab = ylabs[j], bty='n',\n xlim = c(-0.02, 50), ylim = ylims[[j]],\n xaxt ='n')\n segments(x0=mdl_abs_error$sigma + jitter, y0 = mdl_abs_error$lwr, x1 = mdl_abs_error$sigma + jitter, y1 = mdl_abs_error$upr, lty = 3, col = plot_col2)\n axis(side = 1, at = (sigma_true*1000), as.character(sigma_true*1000), las=2)\n }else{\n lines(mdl_abs_error$sigma + jitter, mdl_abs_error$med,type = 'b', pch = 16, col =plot_col2)\n segments(x0=mdl_abs_error$sigma + jitter, y0 = mdl_abs_error$lwr, x1 = mdl_abs_error$sigma + jitter, y1 = mdl_abs_error$upr, lty = 3, col = plot_col2)\n \n }\n title(titles[j], font.main=1)\n \n }\n}\nlegend(0, 40, legend = models[1:5], \n col = c(point_cols2[[1]],point_cols2[[2]], point_cols2[[3]], point_cols2[[4]], point_cols2[[5]]),\n lty = 1, bty='n')\n\n\n## -----------------------------------------------------------------------------\n# Figure 2 'Line' plot of proportion of sims where Bayes had < error than LS\n## -----------------------------------------------------------------------------\n\ntitles = c(TeX(\"(a) \\t $r_x$\"),TeX(\"(b) \\t $r_y$\"),TeX('(c) \\t $\\\\theta_1$'),TeX(\"(d) \\t $\\\\sigma$\"))\npar(mfrow=c(1,4))\nfor(j in 1:4){\n for(i in 2:5){\n parm_perf = perf %>% filter(Parameter ==parameters[j])\n mdl_parm_perf = parm_perf %>% filter(Model ==i)\n jitter = 0\n \n plot_col2 = point_cols2[[i]]\n if(i ==2){\n plot(mdl_parm_perf$sigma + jitter, mdl_parm_perf$Perf,type = 'b', pch = 16, col =plot_col2,\n xlab = TeX(\"Noise Level: $\\\\sigma \\\\, (mm)$\"), ylab = \"Proportion of Simulations\", bty='n',\n xlim = c(-0.02, 50), ylim = c(0.4,1),\n xaxt ='n')\n axis(side = 1, at = (sigma_true*1000), as.character(sigma_true*1000), las=2)\n }else{\n lines(mdl_parm_perf$sigma + jitter, mdl_parm_perf$Perf,type = 'b', pch = 16, col =plot_col2)\n \n }\n title(titles[j], main.font=1)\n \n }\n}\nlegend(0, 0.5, legend = models[2:5], \n col = c(point_cols2[[2]], point_cols2[[3]], point_cols2[[4]], point_cols2[[5]]),\n lty = 1, bty='n')\n\n## -----------------------------------------------------------------------------\n# Figure 3 Scatter Plot of LS estimator vs Bayes estimator\n## -----------------------------------------------------------------------------\naxis_lims = list(c(-0.2*1000, 0.5*1000), c(-0.5*1000, 0.2*1000), c(-150,100), c(0*1000, 0.12*1000))\ntrue_vals_vec = c(r_true*1000, theta_true, sigma_true[6]*1000)\nresults_40 = results[results[,1]==40/1000,] # This can be changed to explore other noise levels\nresults_40[,c(4,5,7)] = results_40[,c(4,5,7)]*1000\nylabs = c(\"Vague 1\", \"Vague 2\", \"Weakly Informative\", \"Informative\")\ntitles = c(TeX(\"$r_x \\\\, (mm)$\"), TeX(\"$r_y \\\\, (mm)$\"), TeX('$\\\\theta_1 \\\\, (deg)'), TeX(\"$\\\\sigma \\\\, (mm)$\"))\n\npar(mfrow=c(4,4), mai = c(0.6, 0.6, 0.0, 0))\nfor(i in 2:5){\n for(j in 1:4){\n ls_result = results_40[results_40[,2]==1, 3+j]\n mdl_result = results_40[results_40[,2]==i, 3+j]\n b_ls = sqrt((mdl_result-true_vals_vec[j])^2) - sqrt((ls_result - true_vals_vec[j])^2)\n\n b_ls = ifelse(b_ls<0, 1,2)\n cols = list(rgb(52/255, 152/255, 219/255, 0.2),\n colors$pink)\n mycol = rep(\"\", length(b_ls))\n for(ii in 1:length(b_ls)){\n mycol[ii] = cols[[b_ls[ii]]] \n }\n if(j ==1 & i ==5){\n plot(ls_result, mdl_result, pch = 16, col = mycol,\n #asp = 1,\n xlim = axis_lims[[j]], ylim = axis_lims[[j]],\n xlab = \"LS est\",\n ylab = ylabs[i-1],\n bty='n')\n }else if (j >1 & i ==5 ){\n plot(ls_result, mdl_result, pch = 16, col = mycol,\n #asp = 1,\n xlim = axis_lims[[j]], ylim = axis_lims[[j]],\n xlab = \"LS est\",\n ylab = NA,\n bty='n')\n }else if(j==1 & i < 5){\n plot(ls_result, mdl_result, pch = 16, col = mycol,\n #asp = 1,\n xlim = axis_lims[[j]], ylim = axis_lims[[j]],\n xlab = NA,\n ylab = ylabs[i-1],\n bty='n') \n }else{\n plot(ls_result, mdl_result, pch = 16, col = mycol,\n #asp = 1,\n xlim = axis_lims[[j]], ylim = axis_lims[[j]],\n xlab = NA, ylab = NA,\n bty='n')\n }\n if(i ==2){\n title(titles[j], line =-1)\n }\n \n abline(0,1, col = colors$orange)\n points(true_vals_vec[j],true_vals_vec[j], pch=18, cex = 2,col = colors2$orange)\n \n }\n}\n\n########################### Section E #########################\n## Additional Figures not referenced in supplement\n################################################################\n\n# Scatter plot of error distribution for each model/noise level\nylabs = list(r1=TeX(\"$r_1 \\\\, (mm)$\"), r2=TeX(\"$r_2 \\\\, (mm)$\"), theta1=TeX(\"$\\\\theta_1 \\\\, (^o)$\"), \n sigma=TeX(\"$\\\\sigma \\\\, (mm)$\"))\nylims = list(c(-0.1,0.6), c(-0.6, 0.4), c(-180, 60), c(-0.03, 0.12))\n\npar(mfrow = c(4, 6),mai = c(0, 0.6, 0.0, 0), oma=c(0,0,0,0))\nfor(j in 1:4){\n for(i in 1:6){\n # i= 1 # noise level (1:6)\n # j = 1 # parameter (1:4)\n true_val_tmp = c(r_true, theta_true, sigma_true[i])\n \n sigma_results = results[(results[,1]==sigma_true[i]), ]\n plot_col = rep(\"\", nrow(sigma_results))\n for(ii in 1:nrow(sigma_results)){\n plot_col[ii] = point_cols[[sigma_results[ii,2]]]\n }\n \n if(i != 1){\n plot(sigma_results[,2]+rnorm(nrow(sigma_results), 0, 0.1), sigma_results[,3+j],\n pch = 16, col = plot_col,\n ylab = NA, yaxt = 'n',\n ylim =ylims[[j]],\n xlab = NA, bty='n', xaxt = 'n')\n }else{\n plot(sigma_results[,2]+rnorm(nrow(sigma_results), 0, 0.1), sigma_results[,3+j],\n pch = 16, col = plot_col,\n ylab = ylabs[[j]],\n ylim =ylims[[j]],\n xlab = NA, bty='n', xaxt = 'n')\n }\n abline(h = true_val_tmp[j], col = colors$orange)\n \n if(j ==1){\n title(TeX(sprintf(\"$\\\\sigma$ = %.1fmm$\", c(sigma_true[i]*1000))), line = -2)\n }\n }\n}\n", "meta": {"hexsha": "ec73e96a224f40b55428cc429b8de8da3be7be4b", "size": 18511, "ext": "r", "lang": "R", "max_stars_repo_path": "src/SupplementD/SupplementD.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SupplementD/SupplementD.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SupplementD/SupplementD.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8193069307, "max_line_length": 210, "alphanum_fraction": 0.5133704284, "num_tokens": 5409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.46008323631371095}} {"text": "compute.model.average <- function(B,P,params)\n{\n\tregion_enrichment <- c(params[3],params[2],params[4],params[1],params[5],params[2],params[6],params[1],0)\n\tcombined.adj <- (abs(B)+params[8]) * (abs(P)+params[7])\n\tQ.test.I <- combined.adj; Q.test.I[which(B <= 0)] <- 0; Q.test.I[which(P <= 0)] <- 0;\n\tQ.test.II <- combined.adj; Q.test.II[which(B >= 0)] <- 0; Q.test.II[which(P <= 0)] <- 0;\n\tQ.test.III <- combined.adj; Q.test.III[which(B >= 0)] <- 0; Q.test.III[which(P >= 0)] <- 0;\n\tQ.test.IV <- combined.adj; Q.test.IV[which(B <= 0)] <- 0; Q.test.IV[which(P >= 0)] <- 0;\n\tQ.test.PDE <- combined.adj; Q.test.PDE[which(B != 0)] <- 0; Q.test.PDE[which(P <= 0)] <- 0;\n\tQ.test.NDE <- combined.adj; Q.test.NDE[which(B != 0)] <- 0; Q.test.NDE[which(P >= 0)] <- 0;\n\tQ.test.PB <- combined.adj; Q.test.PB[which(B <= 0)] <- 0; Q.test.PB[which(P != 0)] <- 0;\n\tQ.test.NB <- combined.adj; Q.test.NB[which(B >= 0)] <- 0; Q.test.NB[which(P != 0)] <- 0;\n\tQ.test <- region_enrichment[1] * Q.test.I + region_enrichment[2] * Q.test.PDE + region_enrichment[3] * Q.test.II + region_enrichment[4] * Q.test.PB + region_enrichment[5] * Q.test.III + region_enrichment[6] * Q.test.NDE + region_enrichment[7] * Q.test.IV + region_enrichment[8] * Q.test.NB\n\tQ.test\n}\n\ncompute.model.average.new <- function(B,D,params)\n{\n\t# params\n\t# (I,II,III,IV,B,D,Cb,Cd)\n\tBs <- abs(B) + params[7]\n\tDs <- abs(D) + params[8]\n\tM <- matrix(0,nrow=dim(B)[1],ncol=dim(B)[2])\n\trindx <- intersect(which(B>0),which(D>0))\t\t\t\t\t\t\t\t# I\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[1] \n\trindx <- intersect(which(B<0),which(D>0))\t\t\t\t\t\t\t\t# II\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[2] \n\trindx <- intersect(which(B<0),which(D<0))\t\t\t\t\t\t\t\t# III\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[3] \n\trindx <- intersect(which(B>0),which(D<0))\t\t\t\t\t\t\t\t# IV\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[4] \n\trindx <- intersect(which(B!=0),which(D==0))\t\t\t\t\t\t\t# B\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[5] \n\trindx <- intersect(which(B==0),which(D!=0))\t\t\t\t\t\t\t# D\n\tM[rindx] <- abs(Bs[rindx]) * abs(Ds[rindx]) * params[6] \n\tM\n}\n\nplot.model.average.ranking <- function(B,P,params,n=10000,fname)\n{\n region_enrichment <- c(params[3],params[2],params[4],params[1],params[5],params[2],params[6],params[1],0)\n combined.adj <- (abs(B)+params[8]) * (abs(P)+params[7])\n Q.test.I <- combined.adj; Q.test.I[which(B <= 0)] <- 0; Q.test.I[which(P <= 0)] <- 0;\n Q.test.II <- combined.adj; Q.test.II[which(B >= 0)] <- 0; Q.test.II[which(P <= 0)] <- 0;\n Q.test.III <- combined.adj; Q.test.III[which(B >= 0)] <- 0; Q.test.III[which(P >= 0)] <- 0;\n Q.test.IV <- combined.adj; Q.test.IV[which(B <= 0)] <- 0; Q.test.IV[which(P >= 0)] <- 0;\n Q.test.PDE <- combined.adj; Q.test.PDE[which(B != 0)] <- 0; Q.test.PDE[which(P <= 0)] <- 0;\n Q.test.NDE <- combined.adj; Q.test.NDE[which(B != 0)] <- 0; Q.test.NDE[which(P >= 0)] <- 0;\n Q.test.PB <- combined.adj; Q.test.PB[which(B <= 0)] <- 0; Q.test.PB[which(P != 0)] <- 0;\n Q.test.NB <- combined.adj; Q.test.NB[which(B >= 0)] <- 0; Q.test.NB[which(P != 0)] <- 0;\n Q.test <- region_enrichment[1] * Q.test.I + region_enrichment[2] * Q.test.PDE + region_enrichment[3] * Q.test.II + region_enrichment[4] * Q.test.PB + region_enrichment[5] * Q.test.III + region_enrichment[6] * Q.test.NDE + region_enrichment[7] * Q.test.IV + region_enrichment[8] * Q.test.NB\n\n regions <- matrix(0,ncol=dim(B)[2],nrow=dim(B)[1])\n regions[intersect(which(B > 0),which(P > 0))] <- 1\t#IV\n regions[intersect(which(B < 0),which(P > 0))] <- 2\t#III\n regions[intersect(which(B < 0),which(P < 0))] <- 3\t#II\n regions[intersect(which(B > 0),which(P < 0))] <- 4\t#I\n regions[intersect(which(B == 0),which(P != 0))] <- 5\t#P\n regions[intersect(which(B != 0),which(P == 0))] <- 6\t#B\n\n r.freq <- matrix(0,ncol=n,nrow=6)\n r.nzi <- which(regions!=0)\n q.nz <- Q.test[r.nzi]\n r.nz <- regions[r.nzi]\n r.rnk <- r.nz[sort.list(q.nz,decreasing=TRUE)]\n for (i in 2:n)\n {\n r.freq[,i] <- r.freq[,i-1]\n r.freq[r.rnk[i],i] <- r.freq[r.rnk[i],i] + 1\n }\n r.frac <- matrix(0,ncol=n,nrow=6)\n r.frac[1,] <- r.freq[1,]\n for (i in 2:6) \n { \n r.frac[i,] <- r.freq[i,] + r.frac[i-1,] \n }\n r.frac <- t(t(r.frac) / (seq(1,n)-1))\n\tjpeg(filename=fname,width=1800,height=1800,quality=100,res=300)\n plot(seq(1,n)-1,rep(1,times=n),ylim=c(0,1),type='n',xlab=\"Interaction rank\",ylab=\"Cumulative representation\")\n xx <- c(seq(1,n),seq(n,1))-1\n\t\n cols <- c(rgb(0.7,0,0.7),rgb(0.8,0.3,0.3),rgb(1,0.6,0.2),rgb(0.3,0.8,0.3),rgb(0.6,1,1),rgb(0.2,0.6,1))\n\n yy <- c(rep(0,times=n),rev(r.frac[1,]))\n polygon(xx,yy,col=cols[1])\n for (i in 1:5)\n {\n yy <- c(r.frac[i,],rev(r.frac[i+1,]))\n polygon(xx,yy,col=cols[i+1])\n }\n\tdev.off()\n}\n\n", "meta": {"hexsha": "8ba3c94de3c4c186bc84816c57c892f1359c551a", "size": 4713, "ext": "r", "lang": "R", "max_stars_repo_path": "SRC/NetProphet1/modelaverage.r", "max_stars_repo_name": "ygidtu/NetProphet_2.0", "max_stars_repo_head_hexsha": "1ca665d15c6f06a732443bbbe251c58dd221e063", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-11-10T22:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T20:47:09.000Z", "max_issues_repo_path": "SRC/NetProphet1/modelaverage.r", "max_issues_repo_name": "ygidtu/NetProphet_2.0", "max_issues_repo_head_hexsha": "1ca665d15c6f06a732443bbbe251c58dd221e063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-11T08:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T17:33:02.000Z", "max_forks_repo_path": "SRC/NetProphet1/modelaverage.r", "max_forks_repo_name": "ygidtu/NetProphet_2.0", "max_forks_repo_head_hexsha": "1ca665d15c6f06a732443bbbe251c58dd221e063", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-11-03T16:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T04:11:34.000Z", "avg_line_length": 50.1382978723, "max_line_length": 291, "alphanum_fraction": 0.5788245279, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4596211582400818}} {"text": "#'@title calcKristCaa\n#'\n#'@description Calculate air resistance (\\code{Caa}) (dimensionless) using the\n#'Kristensen method.\n#'\n#'@param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}}). \n#'Must align with \\code{tankerBulkCarrierGCargoShipTypes} and\n#' \\code{containerShipTypes} groupings\n#'@param dwt Ship maximum deadweight tonnage (vector of numericals, tonnage)\n#'@param tankerBulkCarrierGCargoShipTypes Ship types specified in input\n#'\\code{shipTypes} to be modeled as tankers, bulk carriers and general cargo\n#'vessels (vector of strings)\n#'@param containerShipTypes Ship types specified in input \\code{shipTypes} to be\n#'modeled as container ships (vector of strings)\n#'\n#' @details\n#' Models the effect of realistic hull roughness on resistance, which is not\n#' captured in the frictional and residual resistance coefficients from tank\n#' towing operations.\n#'\n#' This method this requires ship types to be grouped. Use the\n#' \\code{tankerBulkCarrierGCargoShipTypes}, \\code{containerShipTypes} grouping\n#' parameters to provide these ship type groupings. Any ship types not included\n#' in these groupings will be considered as miscellaneous vessels.\n#'\n#' NOTE: within the container ship section of this calculation, estimations are\n#' made of the ships TEU:\\itemize{\n#' \\item Feeder: TEU = ((dwt/15.19)^(1/0.9814))\n#' \\item Panamax: TEU = ((dwt/28.81)^(1/0.902))\n#' \\item PostPanamax: TEU = ((dwt/37)^(1/0.875))\n#' }\n#' These come from: H.O. Kristensen (2016), \"Revision of statistical analysis and determination of\n#' regression formulas for main dimensions of container ships based on data from Clarkson\".\n#' Kristensen's SHIP DESMO model also uses another dwt/teu relation for post-panamax container ships\n#' with breadth > 49m. This equation has no inverse to map dwt to TEU and thus all post panamaxs are\n#' assumed to have the same dwt/teu relation for all breadths, described above.\n#'\n#' @return \\code{Caa} (vector of numericals, dimensionless)\n#'\n#' @references\n#'Kristensen, H. O. and Lutzen, M. 2013. \"Prediction of Resistance and Propulsion\n#'Power of Ships.\"\n#'\n#'Kristensen, H. O. 2016. \"Revision of statistical analysis and determination of\n#'regression formulas for main dimensions of container ships based on data from\n#'Clarkson.\"\n#'\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'@family Kristensen Calculations\n#'@family Resistance Calculations\n#'\n#' @examples\n#' calcKristCaa(c(\"bulk.carrier\",\"container.ship\",\"other.tanker\"),c(70000,191144,20000))\n#' calcKristCaa(c(\"bulk.carrier\",\"container.ship\",\"other.tanker\"),c(70000,191144,20000),\n#' tankerBulkCarrierGCargoShipTypes=c(\"bulk.carrier\",\"other.tanker\"))\n#'\n#' @export\n\n\n\ncalcKristCaa<-function(shipType,dwt,\n tankerBulkCarrierGCargoShipTypes=c(\"tanker\",\"general.cargo\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\"),\n containerShipTypes=c(\"container.ship\")\n){\n Caa<- ifelse(shipType%in%tankerBulkCarrierGCargoShipTypes,\n ifelse(#case 1:\"Small\",\"Handysize\",\"Handymax\",\n dwt <= 55000,0.07,\n ifelse(#case 2:\"Panamax\",\"Aframax\",\"Suezmax\"\n dwt <= 200000,0.05,\n #case 3: \"VLCC\",\"VLBC\"\n 0.04\n )#end case 3\n )# end case 2\n # end case 1\n #end non container ship group\n ,ifelse(shipType %in% containerShipTypes,#start container ship group\n ifelse( #case 1 Feeder\n dwt <= 35000, pmax(0.28*((dwt/15.19)^(1/0.9814))^-0.126,0.09),\n ifelse(#case 2 Panamax\n dwt <= 60000, pmax(0.28*((dwt/28.81)^(1/0.902))^-0.126,0.09),\n pmax(0.28*((dwt/37)^(1/0.875))^-0.126,0.09) #PostPanamax\n )# end case 2\n ),\n NA# end case 1\n #end container ship group\n )\n )\n\n return(Caa/1000)\n}\n", "meta": {"hexsha": "422156658cff085a11ca7f9236c010c349fb12d3", "size": 3958, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristCaa.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipPowerModel/R/calcKristCaa.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipPowerModel/R/calcKristCaa.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 42.5591397849, "max_line_length": 168, "alphanum_fraction": 0.6867104598, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45838726811205305}} {"text": "# This is a minimal version of the \"sandwich\" package suitable for use in this course\n# It is based on the \"sandwich\" package: https://cran.r-project.org/web/packages/sandwich/index.html\n# Modified 06-03-2021 and this file is licensed under the GPL-2 / GPL-3 license\n\n\nsandwich <- function(x, bread. = bread, meat. = meat, ...)\n{\n if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- \"omit\"\n if(is.function(bread.)) bread. <- bread.(x)\n if(is.function(meat.)) meat. <- meat.(x, ...)\n n <- NROW(estfun(x))\n return(1/n * (bread. %*% meat. %*% bread.))\n}\n\nmeat <- function(x, adjust = FALSE, ...)\n{\n if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- \"omit\"\n psi <- estfun(x, ...)\n k <- NCOL(psi)\n n <- NROW(psi)\n rval <- crossprod(as.matrix(psi))/n\n if(adjust) rval <- n/(n-k) * rval\n rownames(rval) <- colnames(rval) <- colnames(psi)\n return(rval)\n}\n\nvcovOPG <- function(x, adjust = FALSE, ...)\n{\n if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- \"omit\"\n psi <- estfun(x, ...)\n k <- NCOL(psi)\n n <- NROW(psi)\n rval <- chol2inv(qr.R(qr(psi)))\n if(adjust) rval <- n/(n-k) * rval\n rownames(rval) <- colnames(rval) <- colnames(psi)\n return(rval)\n}\n\nvcovHC <- function(x, ...) {\n UseMethod(\"vcovHC\")\n}\n\nvcovHC.default <- function(x, \n type = c(\"HC3\", \"const\", \"HC\", \"HC0\", \"HC1\", \"HC2\", \"HC4\", \"HC4m\", \"HC5\"),\n omega = NULL, sandwich = TRUE, ...)\n{\n type <- match.arg(type)\n rval <- meatHC(x, type = type, omega = omega)\n if(sandwich) rval <- sandwich(x, meat. = rval, ...)\n return(rval)\n}\n\nmeatHC <- function(x, \n type = c(\"HC3\", \"const\", \"HC\", \"HC0\", \"HC1\", \"HC2\", \"HC4\", \"HC4m\", \"HC5\"),\n omega = NULL, ...)\n{\n ## ensure that NAs are omitted\n if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- \"omit\"\n\n ## extract X\n X <- model.matrix(x)\n if(any(alias <- is.na(coef(x)))) X <- X[, !alias, drop = FALSE]\n attr(X, \"assign\") <- NULL\n n <- NROW(X)\n\n ## get hat values and residual degrees of freedom\n diaghat <- try(hatvalues(x), silent = TRUE)\n df <- n - NCOL(X)\n \n ## the following might work, but \"intercept\" is also claimed for \"coxph\"\n ## res <- if(attr(terms(x), \"intercept\") > 0) estfun(x)[,1] else rowMeans(estfun(x)/X, na.rm = TRUE)\n ## hence better rely on\n ef <- estfun(x, ...)\n res <- rowMeans(ef/X, na.rm = TRUE)\n\n ## handle rows with just zeros\n all0 <- apply(abs(ef) < .Machine$double.eps, 1L, all)\n res[all0] <- 0\n ## in case of lm/glm and type = \"const\" re-obtain the working residuals\n if(any(all0) && substr(type, 1L, 1L) == \"c\") {\n if(inherits(x, \"glm\")) {\n res <- as.vector(residuals(x, \"working\")) * weights(x, \"working\")\n if(!(substr(x$family$family, 1L, 17L) %in% c(\"poisson\", \"binomial\", \"Negative Binomial\"))) {\n res <- res * sum(weights(x, \"working\"), na.rm = TRUE) / sum(res^2, na.rm = TRUE)\n }\n } else if(inherits(x, \"lm\")) {\n res <- as.vector(residuals(x))\n if(!is.null(weights(x))) res <- res * weights(x)\n }\n }\n \n ## if omega not specified, set up using type\n if(is.null(omega)) {\n type <- match.arg(type)\n if(type == \"HC\") type <- \"HC0\"\n switch(type,\n \"const\" = { omega <- function(residuals, diaghat, df) rep(1, length(residuals)) * sum(residuals^2)/df },\n \"HC0\" = { omega <- function(residuals, diaghat, df) residuals^2 },\n \"HC1\" = { omega <- function(residuals, diaghat, df) residuals^2 * length(residuals)/df },\n \"HC2\" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat) },\n \"HC3\" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat)^2 },\n \"HC4\" = { omega <- function(residuals, diaghat, df) {\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(4, n * diaghat/p)\n residuals^2 / (1 - diaghat)^delta\n }},\n \"HC4m\" = { omega <- function(residuals, diaghat, df) {\n gamma <- c(1.0, 1.5) ## as recommended by Cribari-Neto & Da Silva\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(gamma[1], n * diaghat/p) + pmin(gamma[2], n * diaghat/p)\n residuals^2 / (1 - diaghat)^delta\n }},\n \"HC5\" = { omega <- function(residuals, diaghat, df) {\n k <- 0.7 ## as recommended by Cribari-Neto et al.\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(n * diaghat/p, pmax(4, n * k * max(diaghat)/p))\n residuals^2 / sqrt((1 - diaghat)^delta)\n }}\n )\n }\n \n ## process omega\n if(is.function(omega)) omega <- omega(res, diaghat, df)\n rval <- sqrt(omega) * X\n rval <- crossprod(rval)/n\n\n return(rval)\n}\n\nvcovHC.mlm <- function(x, \n type = c(\"HC3\", \"const\", \"HC\", \"HC0\", \"HC1\", \"HC2\", \"HC4\", \"HC4m\", \"HC5\"),\n omega = NULL, sandwich = TRUE, ...)\n{\n ## compute meat \"by hand\" because meatHC() can not deal with\n ## residual \"matrices\"\n \n ## ensure that NAs are omitted\n if(is.list(x) && !is.null(x$na.action)) class(x$na.action) <- \"omit\"\n\n ## regressors, df, hat values\n X <- model.matrix(x)\n attr(X, \"assign\") <- NULL\n if(any(alias <- apply(coef(x), 1, function(z) all(is.na(z))))) X <- X[, !alias, drop = FALSE]\n n <- NROW(X)\n diaghat <- hatvalues(x)\n df <- n - NCOL(X)\n\n ## residuals\n res <- residuals(x)\n \n ## if omega not specified, set up using type\n if(is.null(omega)) {\n type <- match.arg(type)\n if(type == \"HC\") type <- \"HC0\"\n switch(type,\n \"const\" = {\n warning(\"not implemented for 'mlm' objects, using vcov() instead\")\n\treturn(vcov(x))\n },\n \"HC0\" = { omega <- function(residuals, diaghat, df) residuals^2 },\n \"HC1\" = { omega <- function(residuals, diaghat, df) residuals^2 * length(residuals)/df },\n \"HC2\" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat) },\n \"HC3\" = { omega <- function(residuals, diaghat, df) residuals^2 / (1 - diaghat)^2 },\n \"HC4\" = { omega <- function(residuals, diaghat, df) {\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(4, n * diaghat/p)\n residuals^2 / (1 - diaghat)^delta\n }},\n \"HC4m\" = { omega <- function(residuals, diaghat, df) {\n gamma <- c(1.0, 1.5)\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(gamma[1], n * diaghat/p) + pmin(gamma[2], n * diaghat/p)\n residuals^2 / (1 - diaghat)^delta\n }},\n \"HC5\" = { omega <- function(residuals, diaghat, df) {\n k <- 0.7\n n <- length(residuals)\n\tp <- as.integer(round(sum(diaghat), digits = 0))\n\tdelta <- pmin(n * diaghat/p, pmax(4, n * k * max(diaghat)/p))\n residuals^2 / sqrt((1 - diaghat)^delta)\n }}\n )\n }\n \n ## process omega\n omega <- apply(res, 2, function(r) omega(r, diaghat, df))\n\n ## compute crossproduct X' Omega X\n rval <- lapply(1:ncol(omega), function(i) as.vector(sign(res[,i]) * sqrt(omega[,i])) * X)\n rval <- do.call(\"cbind\", rval)\n rval <- crossprod(rval)/n\n colnames(rval) <- rownames(rval) <- colnames(vcov(x))\n\n ## if necessary compute full sandwich\n if(sandwich) rval <- sandwich(x, meat. = rval, ...)\n return(rval)\n}\n \n estfun <- function(x, ...)\n{\n UseMethod(\"estfun\")\n}\n\nestfun.lm <- function(x, ...)\n{\n xmat <- model.matrix(x)\n xmat <- naresid(x$na.action, xmat)\n if(any(alias <- is.na(coef(x)))) xmat <- xmat[, !alias, drop = FALSE]\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n res <- residuals(x)\n rval <- as.vector(res) * wts * xmat\n attr(rval, \"assign\") <- NULL\n attr(rval, \"contrasts\") <- NULL\n if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, \"frequency\"))\n if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))\n return(rval)\n}\n\nestfun.mlm <- function(x, ...)\n{\n xmat <- model.matrix(x)\n xmat <- naresid(x$na.action, xmat)\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n res <- residuals(x)\n cf <- coef(x)\n rval <- lapply(1:NCOL(res), function(i) {\n rv <- as.vector(res[,i]) * wts * xmat\n colnames(rv) <- paste(colnames(cf)[i], colnames(rv), sep = \":\")\n rv\n }) \n rval <- do.call(\"cbind\", rval)\n attr(rval, \"assign\") <- NULL\n attr(rval, \"contrasts\") <- NULL\n if(any(alias <- is.na(as.vector(cf)))) rval <- rval[, !alias, drop = FALSE]\n if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, \"frequency\"))\n if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))\n return(rval)\n}\n\nestfun.glm <- function(x, ...)\n{\n xmat <- model.matrix(x)\n xmat <- naresid(x$na.action, xmat)\n if(any(alias <- is.na(coef(x)))) xmat <- xmat[, !alias, drop = FALSE]\n wres <- as.vector(residuals(x, \"working\")) * weights(x, \"working\")\n dispersion <- if(substr(x$family$family, 1, 17) %in% c(\"poisson\", \"binomial\", \"Negative Binomial\")) 1\n else sum(wres^2, na.rm = TRUE)/sum(weights(x, \"working\"), na.rm = TRUE)\n rval <- wres * xmat / dispersion\n attr(rval, \"assign\") <- NULL\n attr(rval, \"contrasts\") <- NULL\n res <- residuals(x, type = \"pearson\")\n if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))\n if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, \"frequency\"))\n return(rval)\n}\n\nestfun.rlm <- function(x, ...)\n{\n xmat <- model.matrix(x)\n xmat <- naresid(x$na.action, xmat)\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n res <- residuals(x)\n psi <- function(z) x$psi(z) * z\n rval <- as.vector(psi(res/x$s)) * wts * xmat\n attr(rval, \"assign\") <- NULL\n attr(rval, \"contrasts\") <- NULL\n if(is.ts(res)) rval <- ts(rval, start = start(res), frequency = frequency(res))\n if(is.zoo(res)) rval <- zoo(rval, index(res), attr(res, \"frequency\"))\n return(rval)\n}\n\nestfun.polr <- function(x, ...)\n{\n ## link processing\n mueta <- x$method\n if(mueta == \"logistic\") mueta <- \"logit\"\n mueta <- make.link(mueta)$mu.eta\n \n ## observations\n xmat <- model.matrix(x)[, -1L, drop = FALSE]\n n <- nrow(xmat)\n k <- ncol(xmat)\n m <- length(x$zeta)\n mf <- model.frame(x)\n y <- as.numeric(model.response(mf))\n w <- model.weights(mf)\n if(is.null(w)) w <- rep(1, n)\n\n ## estimates \n prob <- x$fitted.values[cbind(1:n, y)]\n xb <- if(k >= 1L) as.vector(xmat %*% x$coefficients) else rep(0, n)\n zeta <- x$zeta\n lp <- cbind(0, mueta(matrix(zeta, nrow = n, ncol = m, byrow = TRUE) - xb), 0)\n\n ## estimating functions\n rval <- matrix(0, nrow = n, ncol = k + m + 2L)\n if(k >= 1L) rval[, 1L:k] <- (-xmat * as.vector(lp[cbind(1:n, y + 1L)] - lp[cbind(1:n, y)]))\n rval[cbind(1:n, k + y)] <- -as.vector(lp[cbind(1:n, y)])\n rval[cbind(1:n, k + y + 1L)] <- as.vector(lp[cbind(1:n, y + 1L)])\n rval <- rval[, -c(k + 1L, k + m + 2L), drop = FALSE]\n rval <- w/prob * rval\n\n ## dimnames and return\n dimnames(rval) <- list(rownames(xmat), c(colnames(xmat), names(x$zeta)))\n return(rval)\n}\n\nestfun.clm <- function(x, ...)\n{\n if(x$threshold != \"flexible\") stop(\"only flexible thresholds implemented at the moment\")\n\n ## link processing\n mueta <- make.link(x$link)$mu.eta\n \n ## observations\n xmat <- model.matrix(x)\n if(length(xmat) > 1L) stop(\"estimating functions for scale regression not implemented yet\")\n xmat <- xmat$X[, -1L, drop = FALSE]\n n <- nrow(xmat)\n k <- ncol(xmat)\n m <- length(x$alpha)\n mf <- model.frame(x)\n y <- as.numeric(model.response(mf))\n w <- model.weights(mf)\n if(is.null(w)) w <- rep(1, n)\n\n ## estimates \n prob <- x$fitted.values\n xb <- if(k >= 1L) as.vector(xmat %*% x$beta) else rep(0, n)\n zeta <- x$alpha\n lp <- cbind(0, mueta(matrix(zeta, nrow = n, ncol = m, byrow = TRUE) - xb), 0)\n\n ## estimating functions\n rval <- matrix(0, nrow = n, ncol = k + m + 2L)\n if(k >= 1L) rval[, 1L:k] <- (-xmat * as.vector(lp[cbind(1:n, y + 1L)] - lp[cbind(1:n, y)]))\n rval[cbind(1:n, k + y)] <- -as.vector(lp[cbind(1:n, y)])\n rval[cbind(1:n, k + y + 1L)] <- as.vector(lp[cbind(1:n, y + 1L)])\n rval <- rval[, -c(k + 1L, k + m + 2L), drop = FALSE]\n rval <- w/prob * rval\n\n ## dimnames, re-order and return\n dimnames(rval) <- list(rownames(xmat), c(colnames(xmat), names(x$alpha)))\n ix <- if(k >= 1L) c((k + 1L):(k + m), 1L:k) else 1L:m\n return(rval[, ix, drop = FALSE])\n}\n\nestfun.coxph <- function(x, ...)\n{\n wts <- x$weights\n if(is.null(wts)) wts <- 1\n wts * residuals(x, type = \"score\", ...)\n}\n\nestfun.survreg <- function(x, ...)\n{\n mf <- model.frame(x)\n xmat <- model.matrix(terms(x), mf)\n wts <- model.weights(mf)\n if(is.null(wts)) wts <- 1\n res <- residuals(x, type = \"matrix\")\n rval <- as.vector(res[,\"dg\"]) * wts * xmat\n if(NROW(x$var) > length(coef(x))) {\n rval <- cbind(rval, res[,\"ds\"])\n colnames(rval)[NCOL(rval)] <- \"Log(scale)\"\n }\n attr(rval, \"assign\") <- NULL\n \n return(rval)\n}\n\nestfun.nls <- function(x, ...)\n{\n rval <- as.vector(x$m$resid()) * x$m$gradient()\n colnames(rval) <- names(coef(x))\n rval\n}\n\nestfun.hurdle <- function(x, ...) {\n ## extract data\n Y <- if(is.null(x$y)) model.response(model.frame(x)) else x$y\n X <- model.matrix(x, model = \"count\")\n Z <- model.matrix(x, model = \"zero\")\n beta <- coef(x, model = \"count\")\n gamma <- coef(x, model = \"zero\")\n fulltheta <- x$theta\n\n offset <- x$offset\n if(is.list(offset)) {\n offsetx <- offset$count\n offsetz <- offset$zero\n } else {\n offsetx <- offset\n offsetz <- NULL\n }\n if(is.null(offsetx)) offsetx <- 0\n if(is.null(offsetz)) offsetz <- 0\n if(x$dist$zero == \"binomial\") linkobj <- make.link(x$link)\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n Y1 <- Y > 0\n\n ## count component: working residuals\n eta <- as.vector(X %*% beta + offsetx)\n mu <- exp(eta)\n theta <- fulltheta[\"count\"]\n\n wres_count <- as.numeric(Y > 0) * switch(x$dist$count,\n \"poisson\" = {\n (Y - mu) - exp(ppois(0, lambda = mu, log.p = TRUE) -\n ppois(0, lambda = mu, lower.tail = FALSE, log.p = TRUE) + eta) \n },\n \"geometric\" = {\n (Y - mu * (Y + 1)/(mu + 1)) - exp(pnbinom(0, mu = mu, size = 1, log.p = TRUE) -\n pnbinom(0, mu = mu, size = 1, lower.tail = FALSE, log.p = TRUE) - log(mu + 1) + eta)\n },\n \"negbin\" = {\n (Y - mu * (Y + theta)/(mu + theta)) - exp(pnbinom(0, mu = mu, size = theta, log.p = TRUE) -\n pnbinom(0, mu = mu, size = theta, lower.tail = FALSE, log.p = TRUE) +\n\tlog(theta) - log(mu + theta) + eta)\n })\n \n ## zero component: working residuals\n eta <- as.vector(Z %*% gamma + offsetz)\n mu <- if(x$dist$zero == \"binomial\") linkobj$linkinv(eta) else exp(eta)\n theta <- fulltheta[\"zero\"]\n\n wres_zero <- switch(x$dist$zero,\n \"poisson\" = {\n ifelse(Y1, exp(ppois(0, lambda = mu, log.p = TRUE) -\n ppois(0, lambda = mu, lower.tail = FALSE, log.p = TRUE) + eta), -mu)\n },\n \"geometric\" = {\n ifelse(Y1, exp(pnbinom(0, mu = mu, size = 1, log.p = TRUE) -\n pnbinom(0, mu = mu, size = 1, lower.tail = FALSE, log.p = TRUE) - log(mu + 1) + eta), -mu/(mu + 1))\n },\n \"negbin\" = {\n ifelse(Y1, exp(pnbinom(0, mu = mu, size = theta, log.p = TRUE) -\n pnbinom(0, mu = mu, size = theta, lower.tail = FALSE, log.p = TRUE) +\n log(theta) - log(mu + theta) + eta), -mu * theta/(mu + theta))\n },\n \"binomial\" = {\n ifelse(Y1, 1/mu, -1/(1-mu)) * linkobj$mu.eta(eta)\n })\n\n ## compute gradient from data\n rval <- cbind(wres_count * wts * X, wres_zero * wts * Z)\n colnames(rval) <- names(coef(x))\n rownames(rval) <- rownames(X)\n return(rval)\n}\n\nestfun.zeroinfl <- function(x, ...) {\n ## extract data\n Y <- if(is.null(x$y)) model.response(model.frame(x)) else x$y\n X <- model.matrix(x, model = \"count\")\n Z <- model.matrix(x, model = \"zero\")\n beta <- coef(x, model = \"count\")\n gamma <- coef(x, model = \"zero\")\n theta <- x$theta\n\n offset <- x$offset\n if(is.list(offset)) {\n offsetx <- offset$count\n offsetz <- offset$zero\n } else {\n offsetx <- offset\n offsetz <- NULL\n }\n if(is.null(offsetx)) offsetx <- 0\n if(is.null(offsetz)) offsetz <- 0\n linkobj <- make.link(x$link)\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n Y1 <- Y > 0\n\n eta <- as.vector(X %*% beta + offsetx)\n mu <- exp(eta)\n etaz <- as.vector(Z %*% gamma + offsetz)\n muz <- linkobj$linkinv(etaz)\n\n ## density for y = 0\n clogdens0 <- switch(x$dist,\n \"poisson\" = -mu,\n \"geometric\" = dnbinom(0, size = 1, mu = mu, log = TRUE),\n \"negbin\" = dnbinom(0, size = theta, mu = mu, log = TRUE))\n dens0 <- muz * (1 - as.numeric(Y1)) + exp(log(1 - muz) + clogdens0)\n\n ## working residuals \n wres_count <- switch(x$dist,\n \"poisson\" = ifelse(Y1, Y - mu, -exp(-log(dens0) + log(1 - muz) + clogdens0 + log(mu))),\n \"geometric\" = ifelse(Y1, Y - mu * (Y + 1)/(mu + 1), -exp(-log(dens0) +\n log(1 - muz) + clogdens0 - log(mu + 1) + log(mu))),\n \"negbin\" = ifelse(Y1, Y - mu * (Y + theta)/(mu + theta), -exp(-log(dens0) +\n log(1 - muz) + clogdens0 + log(theta) - log(mu + theta) + log(mu))))\n wres_zero <- ifelse(Y1, -1/(1-muz) * linkobj$mu.eta(etaz),\n (linkobj$mu.eta(etaz) - exp(clogdens0) * linkobj$mu.eta(etaz))/dens0)\n\n ## compute gradient from data\n rval <- cbind(wres_count * wts * X, wres_zero * wts * Z)\n colnames(rval) <- names(coef(x))\n rownames(rval) <- rownames(X)\n return(rval)\n}\n\nestfun.mlogit <- function(x, ...)\n{\n x$gradient\n}\n \n bread <- function(x, ...)\n{\n UseMethod(\"bread\")\n}\n\nbread.default <- function(x, ...) {\n nobs0(x) * vcov0(x, ...)\n}\n\nbread.lm <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n sx <- summary.lm(x)\n return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])))\n}\n\nbread.mlm <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n cf <- coef(x)\n rval <- summary.lm(x)\n rval <- kronecker(\n structure(diag(ncol(cf)), .Dimnames = rep.int(list(colnames(cf)), 2L)),\n structure(rval$cov.unscaled, .Dimnames = rep.int(list(rownames(cf)), 2L)) * as.vector(sum(rval$df[1L:2L])),\n make.dimnames = TRUE\n )\n return(rval)\n}\n\nbread.glm <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n sx <- summary(x)\n wres <- as.vector(residuals(x, \"working\")) * weights(x, \"working\")\n dispersion <- if(substr(x$family$family, 1L, 17L) %in% c(\"poisson\", \"binomial\", \"Negative Binomial\")) 1\n else sum(wres^2)/sum(weights(x, \"working\"))\n return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])) * dispersion)\n}\n\nbread.nls <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n sx <- summary(x)\n return(sx$cov.unscaled * as.vector(sum(sx$df[1L:2L])))\n}\n\nbread.polr <- function(x, ...)\n{\n vcov(x) * x$n\n}\n\nbread.clm <- function(x, ...)\n{\n vcov(x) * x$n\n}\n\nbread.survreg <- function(x, ...)\n length(x$linear.predictors) * x$var\n\nbread.gam <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n sx <- summary(x)\n sx$cov.unscaled * sx$n\n}\n \nbread.coxph <- function(x, ...)\n{\n rval <- x$var * x$n\n dimnames(rval) <- list(names(coef(x)), names(coef(x)))\n return(rval)\n}\n\nbread.hurdle <- function(x, ...)\n{\n x$vcov * x$n\n}\n\nbread.zeroinfl <- function(x, ...)\n{\n x$vcov * x$n\n}\n\nbread.mlogit <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n vcov(x) * length(residuals(x))\n}\n\nbread.rlm <- function(x, ...)\n{\n if(!is.null(x$na.action)) class(x$na.action) <- \"omit\"\n xmat <- model.matrix(x)\n xmat <- naresid(x$na.action, xmat)\n wts <- weights(x)\n if(is.null(wts)) wts <- 1\n res <- residuals(x)\n psi_deriv <- function(z) x$psi(z, deriv = 1)\n rval <- sqrt(abs(as.vector(psi_deriv(res/x$s)/x$s))) * wts * xmat \n rval <- chol2inv(qr.R(qr(rval))) * nrow(xmat)\n return(rval)\n}", "meta": {"hexsha": "c1ebabe09c50946f86cbcddbea3524e6fadf5c08", "size": 19475, "ext": "r", "lang": "R", "max_stars_repo_path": "review_sessions/sandwich.r", "max_stars_repo_name": "jlgraves-ubc/econ-326-student", "max_stars_repo_head_hexsha": "3b7b549afca03564d50ddcddce007c2b14552939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-14T22:20:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T22:20:57.000Z", "max_issues_repo_path": "review_sessions/sandwich.r", "max_issues_repo_name": "jlgraves-ubc/econ-326-student", "max_issues_repo_head_hexsha": "3b7b549afca03564d50ddcddce007c2b14552939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "review_sessions/sandwich.r", "max_forks_repo_name": "jlgraves-ubc/econ-326-student", "max_forks_repo_head_hexsha": "3b7b549afca03564d50ddcddce007c2b14552939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4620355412, "max_line_length": 112, "alphanum_fraction": 0.5727856226, "num_tokens": 6733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4582311408636213}} {"text": "#' knots2ms\n#' \n#' Conversion speed from knots in meter per second.\n#'\n#' @param numeric knots Speed in knots.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords knots2mph\n#' \n#' @export\n#'\n#'\n#'\n#'\nknots2ms<-function(knots)\n{\n return(knots * 0.514444);\n}", "meta": {"hexsha": "e57716b04c316984aaf17d68ed9d0d18a503445f", "size": 340, "ext": "r", "lang": "R", "max_stars_repo_path": "R/knots2ms.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/knots2ms.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/knots2ms.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 101, "alphanum_fraction": 0.6588235294, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4569703443250696}} {"text": "#' Deterministic model function\n#'\n#' Deterministic daily age structured model\n#' \n#' @param params A list with the following parameters included: \n#' \n#' ini.prev = percentage of individuals infected at the start (scalar value between 0 and 1), \n#' \n#' n.age.cats = number of age categories to monitor. Currently makes the most sense to be by decade for 10 categories (must be scalar value greater than 3).\n#' \n#' n.i.cats = number of I subcategories\n#' \n#' n.e.cats = number of E subcategories\n#' \n#' e.move = rate of movement in the exposed categories (scalar values between 0 and 1). \n#' \n#' i.move = rate of movement in the infectious categories (scalar between 0 and 1)\n#' \n#' beta = transmission coefficient \n#' \n#' contacts = symmetrical matrix of n.age.cats*n.age.cats of the contact rate between age categories. 1 = average, 1.1 = 10% increase, .9 = 10% decrease. \n#' \n#' n0 = initial population size (scalar value greater than 0)\n#' \n#' n.days = number of days to run the model (scalar value greater than 2),\n#' \n#' severity is a vector of length n.age.cats of the proportion of I that goes to the hospital\n#' \n#' d.no is the proportion of severe cases that die per day w/o hospital care (currently scalar)\n#' \n#' d.yes is the proportion that die with hospital care\n#' \n#' beds is the # of beds or ICUs that are available\n#' \n#' @return A list with 3 outputs: \n#' \n#' 1. List of counts of the # of individuals in S, E, I, R categories over time with the following columns: age category, day of simulation, sub category (for E and I), n = number of individuals\n#' \n#' 2. List of outcomes-- Dt = deaths, Ht = hospitalizations needed\n#' \n#' Lists for Dt and Ht with the following columns: age category, day of the simulation, n = # of individuals \n#' \n#' 3. R0 = basic disease reproductive number \n#' \n#' @importFrom popbio stable.stage\n#' @importFrom dplyr rename mutate\n#' @importFrom reshape2 melt\n#' @importFrom stats rgamma\n#' @importFrom magrittr %>%\n#' @examples \n#' params <- list(ini.prev = 0.001, n.age.cats = 10, n.e.cats = 6, n.i.cats = 5, \n#' e.move = 0.99, i.move = 0.99, beta = .35, theta = 1, \n#' n0 = 10000, n.days = 360, d.no = 0.05, d.yes = 0.01, beds = 20,\n#' contacts = matrix(1, nrow = 10, ncol = 10),\n#' severity = c(0, 0, 0.001, 0.002, 0.004, 0.010, 0.020, 0.044, \n#' 0.093, 0.200))\n#' \n#' out <- det_model(params)\n#' \n#' @export\n\ndet_model <- function(params) {\n #### warnings ####\n # write the list objects to the local environment\n for (v in 1:length(params)) assign(names(params)[v], params[[v]])\n if(exists(\"ini.prev\")==FALSE){\n message(\"initial prevalence is missing, using default value\")\n ini.ad.m.prev <- 0.01\n }\n if(exists(\"n.age.cats\")==FALSE){\n message(\"# of age categories is missing, using default value\")\n n.age.cats <- 10\n }\n \n if(exists(\"e.move\")==FALSE){\n message(\"e.move is missing, using default value\")\n e.move <- 0.4\n }\n\n if(exists(\"i.move\")==FALSE){\n message(\"i.move is missing, using default value\")\n i.move <- 0.4\n }\n \n if(exists(\"beta\")==FALSE){\n message(\"transmission beta is missing, using default value\")\n beta <- 0.08\n }\n \n if(exists(\"theta\")==FALSE){\n message(\"theta is missing, using default value\")\n theta <- 1\n }\n \n if(exists(\"n0\")==FALSE){\n message(\"initial population size n0 is missing, using default value\")\n n0 <- 10000\n }\n \n if(exists(\"n.days\")==FALSE){\n message(\"n.days is missing, using default value\")\n n.days <- 360\n }\n\n ##### check parameter values #####\n if(ini.prev < 0) warning(\"ini.prev must >=0\")\n if(ini.prev > 1) warning(\"ini.prev must be <= 1\")\n\n if(n.age.cats < 4) warning(\"n.age.cats must be 4 or more\")\n if(e.move < 0) warning(\"e.move must be between 0 and 1\")\n if(e.move > 1) warning(\"e.move must be between 0 and 1\")\n if(i.move < 0) warning(\"i.move must be between 0 and 1\")\n if(i.move > 1) warning(\"i.move must be between 0 and 1\")\n if(beta < 0) warning(\"beta cannot be negative\")\n if(n0 <= 0) warning(\"n0 must be positive\")\n if(n.days <= 0) warning(\"n.days must be positive\")\n if(n.e.cats <= 2) warning(\"n.e.cats must be >= 2\")\n if(n.i.cats <= 2) warning(\"n.i.cats must be >= 2\")\n \n #### INITIAL CONDITIONS #### \n \n #NOTE!!! currently making up these survival and repro values\n #NOTE!!! n.age.cats not fully flexible, best if n.age.cats = 10 (1 for each decade)\n prop.aging <- 1/n.age.cats # proportion that age out of a category (approx.)\n mort <- rep(0.001, n.age.cats - 4)\n old.mort <- rep(0.1, 4) # last 4 categories\n \n remain <- rep(1, n.age.cats) - prop.aging - c(mort, old.mort)\n repro <- 0.08\n\n # Create the matrix to start the population at stable age dist\n # Probably should just fix n.age.cats and feed in the current US age dist.\n M <- matrix(rep(0, n.age.cats * n.age.cats), nrow = n.age.cats)\n diag(M) <- remain\n M[row(M) == (col(M) + 1)] <- prop.aging # off diagonal\n M[n.age.cats, n.age.cats] <- 1-old.mort[1] # old category mortality\n \n # insert the fecundity vector for prebirth census\n # only used for the stable age dist\n M[1, 2:4] <- repro * (1-mort[1]) * 0.5\n \n #lambda(M)\n #plot(stable.stage(M))\n \n # pre-allocate the output matrices\n tmp <- matrix(0, nrow = n.age.cats, ncol = n.days)\n St <- tmp # susceptible \n Et <- array(rep(tmp), dim = c(n.age.cats, n.days, n.e.cats)) # exposed\n It <- array(rep(tmp), dim = c(n.age.cats, n.days, n.i.cats)) # infectious\n Rt <- tmp # recovered\n \n # for tracking purposes\n Dt <- tmp # disease deaths\n Ht <- tmp # hospitalizations \n \n # Intializing with the stable age distribution.\n St[, 1] <- popbio::stable.stage(M) * n0 * (1 - ini.prev)\n\n # equally allocating prevalence across ages, \n # currently putting them in the 1st I category\n It[, 1, 1] <- popbio::stable.stage(M) * n0 * ini.prev\n\n # calculate R0 (not sure about this)\n R0 <- (1-exp (-(beta * n0) / n0^theta)) * \n mean(rgamma(1000, n.i.cats, i.move)) \n # assumes no mortality during infectious period and no effect of \n # hospitalization or containment\n # doesn't account for contact matrix. Probably need an NGM approach\n \n #### MODEL ####\n for (t in 2:(n.days)) {\n # bring forward previous month, then modify it\n St[, t] <- St[, t - 1]\n Et[, t, ] <- Et[, t - 1, ]\n It[, t, ] <- It[, t - 1, ]\n Rt[, t] <- Rt[, t - 1]\n \n # Move E individuals forward in their subcategories\n e.movers <- Et[, t, ] * e.move\n \n Et[, t, 1] <- Et[, t, 1] - e.movers[, 1]\n Et[, t, 2:n.e.cats] <- Et[, t, 2:n.e.cats] - e.movers[, 2:n.e.cats] + \n e.movers[, 1:(n.e.cats-1)]\n \n # Exposed become infectious \n It[, t, 1] <- It[, t, 1] + e.movers[ , n.e.cats]\n \n # Move I individuals forward in their subcategories\n i.movers <- It[, t, ] * i.move\n \n It[, t, 1] <- It[, t, 1] - i.movers[, 1]\n It[, t, 2:n.i.cats] <- It[, t, 2:n.i.cats] - i.movers[, 2:n.i.cats] + \n i.movers[, 1:(n.i.cats-1)]\n\n # infectious individs exit from the last I cat into recovered\n Rt[ , t] <- Rt[ , t] + i.movers[ , n.i.cats] \n \n ##### Transmission #####\n I.current <- rowSums(It[ ,t, ]) # current # of I's by age\n Nall <- sum(St[, t]) + sum(Et[, t, ]) + sum(It[, t, ]) + sum(Rt[, t]) #total\n \n # probably a faster way to do this\n cases <- St[, t] * contacts %*% \n (1 - exp( -(beta * (as.matrix(I.current)/ Nall ^ theta))))\n \n St[, t] <- St[, t] - cases\n Et[, t, 1] <- Et[, t, 1] + cases\n \n ##### Hospitalizations needed #####\n Ht[ ,t] <- severity * I.current\n \n ##### Deaths #####\n # hospital beds are allocated proportion to case load\n # maybe modify in the future for different options\n hos.yes <- min(c(beds * Ht[,t]/sum(Ht[,t]), Ht[,t])) # hospitalized\n hos.no <- Ht[,t] - hos.yes # not able to be hospitalized \n \n # deaths depend on whether they are hospitalized\n Dt[ ,t] <- hos.no * d.no + hos.yes * d.yes\n\n # remove those deaths from the I category\n # currently not skewed by time in the infectious class\n It[ , t, ] <- It[ , t, ] - (It[ , t, ] / I.current) * Dt[ ,t]\n }\n\n ##### organize the output #####\n St <- as.data.frame(t(St))\n names(St) <- paste(\"age\", seq(1,n.age.cats), sep = \".\")\n St$day <- 1:n.days\n \n St.long <- melt(St, id.vars = c(\"day\")) %>%\n rename(age = variable, n = value)\n St.long$age <- as.numeric(St.long$age)\n St.long <- St.long[,c(\"age\", \"day\", \"n\")]\n \n Rt <- as.data.frame(t(Rt))\n names(Rt) <- paste(\"age\", seq(1,n.age.cats), sep = \".\")\n Rt$day <- 1:n.days\n \n Rt.long <- melt(Rt, id.vars = c(\"day\")) %>%\n rename(age = variable, n = value)\n Rt.long$age <- as.numeric(Rt.long$age)\n Rt.long <- Rt.long[,c(\"age\", \"day\", \"n\")]\n \n Dt <- as.data.frame(t(Dt))\n names(Dt) <- paste(\"age\", seq(1,n.age.cats), sep = \".\")\n Dt$day <- 1:n.days\n \n Dt.long <- melt(Dt, id.vars = c(\"day\")) %>%\n rename(age = variable, n = value)\n Dt.long$age <- as.numeric(Dt.long$age)\n Dt.long <- Dt.long[,c(\"age\", \"day\", \"n\")]\n \n Ht <- as.data.frame(t(Ht))\n names(Ht) <- paste(\"age\", seq(1,n.age.cats), sep = \".\")\n Ht$day <- 1:n.days\n \n Ht.long <- melt(Ht, id.vars = c(\"day\")) %>%\n rename(age = variable, n = value)\n Ht.long$age <- as.numeric(Ht.long$age)\n Ht.long <- Ht.long[,c(\"age\", \"day\", \"n\")]\n\n # convert array to matrix format\n Et.long <- melt(Et) %>%\n rename(age = Var1, day = Var2, subcat = Var3, n = value)\n It.long <- melt(It) %>%\n rename(age = Var1, day = Var2, subcat = Var3, n = value)\n \n counts <- list(St = St.long, Et = Et.long, It = It.long, Rt = Rt.long)\n outcomes <- list(Dt = Dt.long, Ht = Ht.long)\n output <- list(counts = counts, outcomes = outcomes, R0 = R0)\n}\n\n", "meta": {"hexsha": "2d0db6a8344d498f46d30295fe3138a9083c76d2", "size": 9724, "ext": "r", "lang": "R", "max_stars_repo_path": "R/det_model_fxn.r", "max_stars_repo_name": "paulccross/CorAge", "max_stars_repo_head_hexsha": "7dc765131a39340fd88b68ea8fe92073f7d80027", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/det_model_fxn.r", "max_issues_repo_name": "paulccross/CorAge", "max_issues_repo_head_hexsha": "7dc765131a39340fd88b68ea8fe92073f7d80027", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/det_model_fxn.r", "max_forks_repo_name": "paulccross/CorAge", "max_forks_repo_head_hexsha": "7dc765131a39340fd88b68ea8fe92073f7d80027", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4890510949, "max_line_length": 194, "alphanum_fraction": 0.592760181, "num_tokens": 3108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4562764657809087}} {"text": "## Created on Sunday, August 29, 2021 at 11:17pm EDT by Weekend Editor on WeekendEditorMachine.\n## Copyright (c) 2021, SomeWeekendReading.blog. All rights reserved. As if you care.\n\nlibrary(\"gsDesign\") # For ciBinomial()\nlibrary(\"plyr\") # For ddply()\n\ntoolsDir <- \"../../tools\" # Various tools available from author\nsource(file.path(toolsDir, \"graphics-tools.r\")) # Various graphics hacks\nsource(file.path(toolsDir, \"pipeline-tools.r\")) # Various graphics hacks\n\n##\n## Take summary data on Israeli population (vax, unvax, part vax) stratified by age.\n## Compute efficacy and 95% confidence interval by posterior Beta function + Monte Carlo method.\n##\n\ndoit <- function(## Inputs\n dataDir = \".\",\n dataFile = \"2021-08-29-covid-simpson-Israeli_data_August_15_2021-vax-summary.tsv\",\n\n ## Outputs\n resultsDir = \".\",\n txFile = \"2021-08-29-covid-simpson-ve-confidence-intervals-by-age.txt\",\n plotFile = \"2021-08-29-covid-simpson-ve-confidence-intervals-by-age.png\") {\n\n loadData <- function(dataDir, dataFile) { # Load the Israeli summary data of Morris\n f <- file.path(dataDir, dataFile) # Full pathname to data\n cat(sprintf(\"* Loading data from %s\", f)) # Announce what we're doing\n vaxData <- read.table(f, header = TRUE, sep = \"\\t\")# Read the data\n cat(sprintf(\"\\n - Found this dataframe:\\n\")) # Capture what we got to the transcript\n print(vaxData) # It's short enough that this is doable\n cat(\"\\n\") # Final newline\n vaxData # Return the dataframe\n } #\n\n addEfficacyAndCI <- function(vaxData) { #\n\n# efficacyCI <- function(Ntrt, NtrtInf, Ncnt, NcntInf,\n# n = 1000000, probs = c(0.025, 0.500, 0.975)) {\n# ## *** This gets negative CI's when case counts are 0\n# ## Median as best guess, 2.5% and 97.5% as confidence limits\n# alphaNum <- NtrtInf + 1 # Numerator Beta distribution, alpha\n# betaNum <- Ntrt - NtrtInf + 1 # and beta parameters (treatment)\n# alphaDenom <- NcntInf + 1 # Denominator Beta distribution, alpha\n# betaDenom <- Ncnt - NcntInf + 1 # and beta parameters (control)\n# effs <- 100.0 * (1 - rbeta(n, alphaNum, betaNum) / rbeta(n, alphaDenom, betaDenom))\n# round(quantile(effs, probs = probs), digits = 1) # Get just the quantiles requested\n# } #\n\n efficacyCI <- function(Ntrt, NtrtInf, Ncnt, NcntInf, probs = c(0.025, 0.500, 0.975)) {\n ## Frequentist method: risk rates are scaled binomial, so we use the binomial\n ## confidence interval function in the gsDesign package.\n ci <- 100.0 * (1 - rev(ciBinomial(NtrtInf, NcntInf, Ntrt, Ncnt, scale = \"RR\")))\n c(\"2.5%\" = ci[[1]], #\n \"ve\" = 100.0 * (1 - (NtrtInf / Ntrt) / (NcntInf / Ncnt)),\n \"97.5%\" = ci[[2]]) #\n } #\n\n cat(sprintf(\"* Adding vaccine efficacies and 95%% confidence limits\"))\n\n vaxDataEffs <- merge(vaxData, #\n ddply(vaxData, \"Age.Cohort\", function(acdf) {\n stopifnot(nrow(acdf) == 1) # Defensive programming: unique age cohorts?\n ves <- efficacyCI(acdf[1, \"Vax.Popln\"],\n acdf[1, \"Vax.Severe\"],\n acdf[1, \"Unvax.Popln\"],\n acdf[1, \"Unvax.Severe\"])\n pves <- efficacyCI(acdf[1, \"Part.Vax.Popln\"],\n acdf[1, \"Part.Vax.Severe\"],\n acdf[1, \"Unvax.Popln\"],\n acdf[1, \"Unvax.Severe\"])\n data.frame(## Efficacy for the fully vaccinated\n VE = ves[[\"ve\"]],\n VE.LCL = ves[[\"2.5%\"]],\n VE.UCL = ves[[\"97.5%\"]],\n ## Efficacy for the partly vaccinated\n PVE = pves[[\"ve\"]],\n PVE.LCL = pves[[\"2.5%\"]],\n PVE.UCL = pves[[\"97.5%\"]])\n }), #\n by = \"Age.Cohort\") #\n\n cat(\"\\n\") # Final newline\n vaxDataEffs # Return augmented dataframe\n } #\n\n plotVEs <- function(vaxDataEffs, resultsDir, plotFile) {\n f <- file.path(resultsDir, plotFile) #\n withPNG(f, 400, 400, FALSE, function() { #\n withPars(function() { #\n cols <- c(\"blue\", \"green\")\n matplot(x = 1 : nrow(vaxDataEffs),\n y = subset(vaxDataEffs, select = c(VE)), #, PVE)),\n type = \"b\", pch = 21, col = \"black\", bg = cols,\n xaxt = \"n\", xlab = NA, ylab = \"Vaccine Efficacy (%)\", ylim = c(0, 100),\n main = \"Vaccine efficacy by age cohort\")\n sapply(1 : nrow(vaxDataEffs), function(rn) {\n drawErrorBar(x0 = rn,\n y0 = vaxDataEffs[[rn, \"VE.LCL\"]],\n x1 = rn,\n y1 = vaxDataEffs[[rn, \"VE.UCL\"]],\n col = \"blue\")\n# drawErrorBar(x0 = rn,\n# y0 = vaxDataEffs[[rn, \"PVE.LCL\"]],\n# x1 = rn,\n# y1 = vaxDataEffs[[rn, \"PVE.UCL\"]],\n# col = \"green\")\n })\n# legend(\"bottomright\", inset = 0.05, bg = \"antiquewhite\",\n# pch = 21, pt.bg = cols, legend = c(\"Fully vaccinated\", \"Partially vaccinated\"))\n axis(side = 1, at = 1 : nrow(vaxDataEffs), labels = as.character(vaxDataEffs$\"Age.Cohort\"))\n title(xlab = \"Age Cohort\", line = 3.5) # Horizontal axis title\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # White background\n mar = c(5, 3, 2, 1), # Pull in on margins a bit\n mgp = c(1.7, 0.5, 0), # Axis title, label, tick\n las = 2, # Axis labels perp to axis\n ps = 16) # Larger type size for file capture\n }) #\n cat(sprintf(\"* Plotted to %s\\n\", f)) # Capture to transcript\n TRUE # Flag that it's done\n } #\n\n withTranscript(dataDir, resultsDir, txFile, \"Israeli COVID-19 VE Stratified by Age\", function() {\n\n heraldPhase(\"Loading Data\") #\n maybeAssign(\"vaxData\", function() { loadData(dataDir, dataFile) })\n\n heraldPhase(\"Computing efficacies and confidence interval\")\n maybeAssign(\"vaxDataEffs\", function() { addEfficacyAndCI(vaxData) })\n\n cat(\"\\n\"); print(vaxDataEffs) # ***\n\n heraldPhase(\"Making plot\") #\n maybeAssign(\"plotDone\", function() { plotVEs(vaxDataEffs, resultsDir, plotFile) })\n\n invisible(NA) # Return nothing of interest\n }) # Done with transcript capture\n} # Done overall\n", "meta": {"hexsha": "92472ac0d9158e426ff1fc8eefd643c64a1800be", "size": 8127, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2021-08-29-covid-simpson-ve-confidence-intervals-by-age.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/2021-08-29-covid-simpson-ve-confidence-intervals-by-age.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-10-14T16:09:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T21:01:06.000Z", "max_forks_repo_path": "assets/2021-08-29-covid-simpson-ve-confidence-intervals-by-age.r", "max_forks_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_forks_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.4676258993, "max_line_length": 99, "alphanum_fraction": 0.4393995324, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45614374193677854}} {"text": "###################################################################\n#\n# R source code providing generalized bilinear mixed effects modeling\n# for social network data. For more information on the model fitting \n# procedure, see \n# \"Bilinear Mixed-Effects Models for Dyadic Data\" (Hoff 2003)\n# http://www.stat.washington.edu/www/research/reports/2003/tr430.pdf\n#\n# This research was supported by ONR grant N00014-02-1-1011 \n#\n# Copyright (C) 2003 Peter D. Hoff\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, \n# Boston, MA 02111-1307, USA.\n#\n##################################################################\n\n###Last modification : 2/22/04\n\n###Preconditions of the main function \"gbme\"\n\n##objects with no defaults\n#Y : a square matrix (n*n)\n\n##objects with defaults\n#Xd : an n*n*rd array representing dyad-specific predictors\n#Xs : an n*rs matrix of sender-specific predictors\n#Xr : an n*rr matrix of receiver-specific predictors\n\n# fam : \"gaussian\" \"binomial\", or \"poisson\"\n# if fam=\"binomial\" then an (n*n) matrix N of trials is needed\n#\n# pi.Sab = (s2a0,sab0,s2b0,v0) : parameters of inverse wishart dist\n# pi.s2u = vector of length 2: parameters of an inv-gamma distribution\n# pi.s2v = vector of length 2: parameters of an inv-gamma distribution\n# pi.s2z = k*2 matrix : parameters of k inv-gamma distributions\n#\n# pim.bd : vector of length rd, the prior mean for beta.d\n# piS.bd : a rd*rd pos def matrix, the prior covariance for beta.d\n#\n# pim.b0sr : vector of length 1+rs+rr, prior mean for (beta0,beta.s,beta.r)\n# piS.b0sr : a (1+rs+rr)*(1+rs+rr) pos def matrix, \n# the prior variance for (beta0,beta.s,beta.r)\n\n# k : dimension of latent space\n# directed : T or F. Is the data directed or undirected? If set to F, \n# estimation proceeds assuming Y[i,j]==Y[j,i], \n# and any supplied value of Xr is not used \n# also, only s2a0 and v0 in pi.Sab need be supplied, \n# and pi.s2v is not used. rr is zero, so pim.b0sr is \n# length 1+rs \n\n# starting values\n# beta.d #a vector of length rd\n# beta.u #a vector of length 1+rs+rr\n# s #a vector of length n\n# r #a vector of length n \n# z #an n*k matrix\n\n###the main function\ngbme<-function(\n #data \n Y, \n Xd=array(dim=c(n,n,0)),\n Xs=matrix(nrow=dim(Y)[1],ncol=0),\n Xr=matrix(nrow=dim(Y)[1],ncol=0), \n\n #model specification\n fam=\"gaussian\", \n N=NULL, \n k=0,\n directed=T, \n\n#compute starting values and emp Bayes for priors?\n estart=T, \n \n#priors - provide if estart=F\n pi.Sab=NULL,\n pi.s2u=NULL,\n pi.s2v=NULL,\n pi.s2z=NULL,\n pim.bd=NULL,\n piS.bd=NULL,\n pim.b0sr=NULL,\n piS.b0sr=NULL,\n \n #starting values - provide if estart=F \n beta.d=NULL,\n beta.u=NULL,\n s=NULL,\n r=NULL,\n z=NULL,\n\n #random seed, \n seed=0,\n\n #details of output\n NS=100000, #number of scans of mcmc to run\n odens=100, #output density\n owrite=T, #write output to a file? \n ofilename=\"OUT\", #name of output file \n oround=3, #rounding of output\n zwrite=(k>0), #write z to file \n zfilename=\"Z\", #outfile for z \n sdigz=3, #rounding for z\n awrite=F,bwrite=F,\n afilename=\"A\",\n bfilename=\"B\"\n\t )\n{\n\n###set seed\nset.seed(seed)\n \n\n\n###dimensions of everything\nn<<-dim(Y)[1]\nrd<<-dim(Xd)[3]\nrs<<-dim(Xs)[2]\nrr<<-dim(Xr)[2] \ndiag(Y)<<-rep(0,n)\n###\n\n###column names for output file\nif(directed==T) {\ncnames<-c(\"k\",\"scan\",\"ll\",paste(\"bd\",seq(1,rd,length=rd),sep=\"\")[0:rd],\"b0\",\n paste(\"bs\",seq(1,rs,length=rs),sep=\"\")[0:rs],\n paste(\"br\",seq(1,rr,length=rr),sep=\"\")[0:rr],\n \"s2a\",\"sab\",\"s2b\",\"s2e\",\"rho\", paste(\"s2z\",seq(1,k,length=k),sep=\"\")[0:k] )\n } \n \nif(directed==F) {\ncnames<-c(\"k\",\"scan\",\"ll\",paste(\"bd\",seq(1,rd,length=rd),sep=\"\")[0:rd],\"b0\",\n paste(\"bs\",seq(1,rs,length=rs),sep=\"\")[0:rs],\n \"s2a\",\"s2e\",paste(\"s2z\",seq(1,k,length=k),sep=\"\")[0:k] )\n }\n\n \n###design matrix for unit-specific predictors\nif(directed==T) {\nX.u<<-rbind( cbind( rep(.5,n), Xs, matrix(0,nrow=n,ncol=rr)),\n cbind( rep(.5,n), matrix(0,nrow=n,ncol=rs), Xr ) )\n }\n\nif(directed==F) { X.u<<-cbind( rep(.5,n), Xs ) }\n###\n\n###construct an upper triangular matrix (useful for later computations)\ntmp<-matrix(1,n,n)\ntmp[lower.tri(tmp,diag=T)]<-NA \nUT<<-tmp\n###\n\n\n###get starting values and empirical bayes priors using a glm-type approach\nif(estart==T) {tmp<-gbme.glmstart(Y,Xd,Xs,Xr,N=N,fam,k,directed)\n priors<-tmp$priors ; startv<-tmp$startv \n }\n\nif(directed==T) {\n pi.Sab<-priors$pi.Sab; pi.s2u<-priors$pi.s2u; pi.s2v<-priors$pi.s2v\n pi.s2z<-priors$pi.s2z ; pim.bd<-priors$pim.bd ; piS.bd<-priors$piS.bd\n pim.b0sr<-priors$pim.b0sr ; piS.b0sr<-priors$piS.b0sr \n beta.d<-startv$beta.d ; beta.u<-startv$beta.u \n s<-startv$s ; r<-startv$r ; z<-startv$z\n }\n###\n\nif(directed == F) { rho<-1 ;sv<-0 ; Xr<-Xs ; rr<-rs \n pi.s2u<-priors$pi.s2u ; pi.s2z<-priors$pi.s2z \n pim.bd<-priors$pim.bd ; piS.bd<-priors$piS.bd\n beta.d<-startv$beta.d ; beta.u<-startv$beta.u ; z<-startv$z\n s<-startv$s ; \n pi.s2a<-priors$pi.s2a ; \n pim.b0s<-priors$pim.b0s ; piS.b0s<-priors$piS.b0s \n Xr<-NULL ; rr<-0 ; r<-s*0 }\n\n \n###Matrices for ANOVA on Xd, s, r\ntmp<-TuTv(n) #unit level effects design matrix for u=yij+yji, v=yij-yji\nTu<-tmp$Tu\nTv<-tmp$Tv\n\nif(directed==F) { Tu<-2*Tu[,1:n] }\n\ntmp<-XuXv(Xd) #regression design matrix for u=yij+yji, v=yij-yji\nXu<-tmp$Xu \nXv<-tmp$Xv\n\nXTu<<-cbind(Xu,Tu)\nXTv<<-cbind(Xv,Tv)\n\ntXTuXTu<<-t(XTu)%*%XTu\ntXTvXTv<<-t(XTv)%*%XTv\n###\n\n\n###redefining hyperparams\nif(directed==T){\nSab0<-matrix( c(pi.Sab[1],pi.Sab[2],pi.Sab[2],pi.Sab[3]),nrow=2,ncol=2) \nv0<-pi.Sab[4] }\n###\n\n###initializing error matrix\nE<-matrix(0,nrow=n,ncol=n)\n###\n\n###if using the linear link, then theta=Y\nif(fam==\"gaussian\"){ theta<-Y }\n###\n\n\n##### The Markov chain Monte Carlo algorithm\nfor(ns in 1:NS){\n\n###update value of theta\nif(fam!=\"gaussian\"){theta<-theta.betaX.d.srE.z(beta.d,Xd,s,s*(1-directed)+r*directed,E,z) }\n\n###impute any missing values if gaussian\nif(fam==\"gaussian\" & any(is.na(Y))) { \n rho<-(pi.s2u[2]-pi.s2v[2])/(pi.s2u[2]+pi.s2v[2])\n se<-(pi.s2u[2]+pi.s2v[2])/4\n mu<-theta.betaX.d.srE.z(beta.d,Xd,s,s*(1-directed)+r*directed,E*0,z)\n imiss<-(1:n)[ is.na(Y%*%rep(1,n)) ]\n for(i in imiss){\n for(j in (1:n)[is.na(Y[i,])]) {\n if( is.na(Y[i,j]) & is.na(Y[j,i]) ) {\n smp<-rmvnorm(c(mu[i,j],mu[j,i]),matrix( se*c(1,rho,rho,1),nrow=2,ncol=2))\n theta[i,j]<-smp[1] ; theta[j,i]<-smp[2] }\nelse{theta[i,j]<-rmvnorm( mu[i,j]+rho*(theta[j,i]-mu[j,i]), sqrt(se*(1-rho^2)))}\n } \n } \n } \n\n\n###Update regression part\ntmp<-uv.E(theta-z%*%t(z)) #the regression part\nu<-tmp$u #u=yij+yji, i0){\n\n#update variance\n#tmp<-eigen(z%*%t(z))\n#z<-tmp$vec[,1:k]%*%sqrt(diag(tmp$val[1:k],nrow=k)) #make cols of z orthogonal \nsz<-1/rgamma(k,pi.s2z[,1]+n/2,pi.s2z[,2]+diag( t(z)%*%z)/2)\n\n#Gibbs for zs, using regression\nres<-theta-theta.betaX.d.srE.z(beta.d,Xd,s,s*(1-directed)+r*directed,0*E,0*z) #theta-(beta*x+a+b)\ns.ares<-se*(1+rho)/2\nfor(i in sample(1:n)) {\nares<-(res[i,-i]+res[-i,i])/2\nZi<-z[-i,]\nSzi<-chol2inv(chol(diag(1/(sz),nrow=k) + \n t(Zi)%*%Zi/s.ares)) #cond variance of z[i,]\nmuzi<-Szi%*%( t(Zi)%*%ares/s.ares ) #cond mean of z[i,]\nz[i,]<-t(rmvnorm(muzi,Szi)) }\n }\n###\nif(k==0){sz<-NULL }\n\n#update E\nif( fam!=\"gaussian\"){\nE<-theta-theta.betaX.d.srE.z(beta.d,Xd,s,s*(1-directed)+r*directed,E*0,z) \n #current E|beta.d,Xd,s,r,z\n\nUU<-VV<-Y*0\n\nu<-rnorm(n*(n-1)/2,0,sqrt(su))\nv<-rnorm(n*(n-1)/2,0,sqrt(sv))\n\nUU[!is.na(UT)]<-u\ntmp<-t(UU)\ntmp[!is.na(UT)]<-u\nUU<-t(tmp)\n\nVV[!is.na(UT)]<-v\ntmp<-t(VV)\ntmp[!is.na(UT)]<--v\nVV<-t(tmp)\n\nEp<-(UU+VV)/2\ntheta.p<-theta-E+Ep\n\ndiag(theta.p)<-diag(theta)<-NA\n\n\n\n##cases\nif(fam==\"poisson\") { mup<-exp(theta.p) ; mu<-exp(theta)\n M.lhr<-dpois(Y,mup,log=T) - dpois(Y,mu,log=T) }\n\nif(fam==\"binomial\"){ mup<-exp(theta.p)/(1+exp(theta.p))\n mu<-exp(theta)/(1+exp(theta))\n M.lhr<-dbinom(Y,N,mup,log=T) - dbinom(Y,N,mu,log=T) }\n\n M.lhr[ is.na(M.lhr) ]<-0\n M.lhr<-(M.lhr+t(M.lhr))/( 2^(1-directed) )\n RU<-matrix(log(runif(n*n)),nrow=n,ncol=n)\n RU[is.na(UT)]<-0 ; RU<-RU+t(RU)\n E[M.lhr>RU]<-Ep[M.lhr>RU]\n }\n\n\n\n\n####output\nif(ns%%odens==0){\n\n#compute loglikelihoods of interest\nif(fam==\"poisson\") { lpy.th<-sum( dpois(Y,exp(theta),log=T),na.rm=T) }\nif(fam==\"binomial\"){ lpy.th<-sum( dbinom(Y,N,exp(theta)/(1+exp(theta)),\n log=T),na.rm=T) }\n\nif(fam==\"gaussian\"){ \nE<-theta-theta.betaX.d.srE.z(beta.d,Xd,s,s*(1-directed)+r*directed,E*0,z)\ntmp<-uv.E(theta-z%*%t(z)) #the regression part\nu<-tmp$u #u=yij+yji, iodens) { write.table(t(out),file=ofilename,append=T,quote=F,\n row.names=F,col.names=F) }\n }\nif(owrite==F) {cat(out,\"\\n\") }\nif(zwrite==T) { write.table(signif(z,sdigz),file=zfilename,\n append=T*(ns>odens),quote=F,row.names=F,col.names=F) }\n\n\nif(awrite==T){write.table(round(t(a),oround),file=afilename,append=T*(ns>odens),quote=F,\n row.names=F,col.names=F) }\nif(bwrite==T & directed==T){write.table(round(t(b),oround),\n file=bfilename,append=T*(ns>odens),quote=F,\n row.names=F,col.names=F) }\n\n }\n\n}}\n\n#####################End of main function : below are helper functions\n\n####\nTuTv<-function(n){\nXu<-Xv<-NULL\nfor(i in 1:(n-1)){\ntmp<-tmp<-NULL\nif( i >1 ){ for(j in 1:(i-1)){ tmp<-cbind(tmp,rep(0,n-i)) } }\ntmp<-cbind(tmp,rep(1,n-i)) \ntmpu<-cbind(tmp,diag(1,n-i)) ; tmpv<-cbind(tmp,-diag(1,n-i))\nXu<-rbind(Xu,tmpu) ; Xv<-rbind(Xv,tmpv)\n }\n\nlist(Tu=cbind(Xu,Xu),Tv=cbind(Xv,-Xv))\n }\n####\n\nXuXv<-function(X){\nXu<-Xv<-NULL\nif(dim(X)[3]>0){\nfor(r in 1:dim(X)[3]){\nxu<-xv<-NULL\nfor(i in 1:(n-1)){\nfor(j in (i+1):n){ xu<-c(xu,X[i,j,r]+X[j,i,r])\n xv<-c(xv,X[i,j,r]-X[j,i,r]) }}\nXu<-cbind(Xu,xu)\nXv<-cbind(Xv,xv) } \n }\nlist(Xu=Xu,Xv=Xv)}\n\n###\nuv.E<-function(E){\nu<- c( t( ( E + t(E) ) *UT ) )\nu<-u[!is.na(u)]\n\nv<-c( t( ( E - t(E) ) *UT ) )\nv<-v[!is.na(v)]\nlist(u=u,v=v)}\n####\n\n\n\n####\ntheta.betaX.d.srE.z<-function(beta.d,X.d,s,r,E,z){\nm<-dim(X.d)[3]\nmu<-matrix(0,nrow=length(s),ncol=length(s))\nif(m>0){for(l in 1:m){ mu<-mu+beta.d[l]*X.d[,,l] }}\ntmp<-mu+re(s,r,E,z)\ndiag(tmp)<-0\ntmp}\n####\n\n####\nre<-function(a,b,E,z){\nn<-length(a)\nmatrix(a,nrow=n,ncol=n,byrow=F)+matrix(b,nrow=n,ncol=n,byrow=T)+E+z%*%t(z) }\n####\n\n####\nrbeta.d.sr.gibbs<-function(u,v,su,sv,piS.bd,mu,Sab){\ndel<-Sab[1,1]*Sab[2,2]-Sab[1,2]^2\niSab<-rbind(cbind( diag(rep(1,n))*Sab[2,2]/del ,-diag(rep(1,n))*Sab[1,2]/del),\n cbind( -diag(rep(1,n))*Sab[1,2]/del,diag(rep(1,n))*Sab[1,1]/del) )\nrd<-dim(as.matrix(piS.bd))[1]\n\nif(dim(piS.bd)[1]>0){\ncov.beta.sr<-matrix(0,nrow=rd,ncol=2*n)\niS<-rbind(cbind(solve(piS.bd),cov.beta.sr),\n cbind(t(cov.beta.sr),iSab)) }\nelse{iS<-iSab}\n\nSig<-chol2inv( chol(iS + tXTuXTu/su + tXTvXTv/sv ) )\n #this may have a closed form expression\n\n#theta<-Sig%*%( (t(XTu)%*%u)/su + (t(XTv)%*%v)/sv + iS%*%mu)\ntheta<-Sig%*%( t( (u%*%XTu)/su + (v%*%XTv)/sv ) + iS%*%mu)\n\nbeta.sr<-rmvnorm(theta,Sig)\nlist(beta.d=beta.sr[(rd>0):rd],s=beta.sr[rd+1:n],r=beta.sr[rd+n+1:n]) }\n####\n\n\n####\nrse.beta.d.gibbs<-function(g0,g1,x,XTx,s,r,beta.d){\nn<-length(s)\n1/rgamma(1, g0+choose(n,2)/2,g1+.5*sum( (x-XTx%*%c(beta.d,s,r))^2 ) ) }\n####\n\n\n####\nrbeta.sr.gibbs<-function(s,r,X.u,pim.b0sr,piS.b0sr,Sab) {\ndel<-Sab[1,1]*Sab[2,2]-Sab[1,2]^2\niSab<-rbind(cbind( diag(rep(1,n))*Sab[2,2]/del ,-diag(rep(1,n))*Sab[1,2]/del),\n cbind( -diag(rep(1,n))*Sab[1,2]/del,diag(rep(1,n))*Sab[1,1]/del) )\n\nS<-solve( solve(piS.b0sr) + t(X.u)%*%iSab%*%X.u )\nmu<-S%*%( solve(piS.b0sr)%*%pim.b0sr+ t(X.u)%*%iSab%*%c(s,r))\nrmvnorm( mu,S)\n }\n####\n\n####\nrSab.gibbs<-function(a,b,S0,v0){\nn<-length(a)\nab<-cbind(a,b)\nSn<-S0+ (t(ab)%*%ab)\nsolve(rwish(solve(Sn),v0+n) )\n }\n\n####\nrmvnorm<-function(mu,Sig2){\nR<-t(chol(Sig2))\nR%*%(rnorm(length(mu),0,1)) +mu }\n\n\n####\nrwish<-function(S0,nu){ \nS<-S0*0\nfor(i in 1:nu){ z<-rmvnorm(rep(0,dim(as.matrix(S0))[1]), S0)\n S<-S+z%*%t(z) }\n\t\tS }\n\n### Procrustes transformation: rotation and reflection\nproc.rr<-function(Y,X){\nk<-dim(X)[2]\nA<-t(Y)%*%( X%*%t(X) )%*%Y\neA<-eigen(A,symmetric=T)\nAhalf<-eA$vec[,1:k]%*%diag(sqrt(eA$val[1:k]),nrow=k)%*%t(eA$vec[,1:k])\n \nt(t(X)%*%Y%*%solve(Ahalf)%*%t(Y)) }\n###\n\n\n\ngbme.glmstart<-function(Y,Xd,Xs,Xr,N=NULL,fam,k,directed){ \n#generate starting values and emp bayes priors from \n#approximate mles\n\nif(fam!=\"binomial\"){\ny<-x<-NULL\nfor (i in 1:n) {\nfor (j in (1:n)[-i]) {\ny<-c(y,Y[i,j])\nx<-rbind(x,c(i,j,Xd[i,j,])) }}\n }\n\nif(fam==\"binomial\"){\ny<-x<-NULL\nfor (i in 1:n) {\nfor (j in (1:n)[-i]) {\ny<-rbind(y,c(Y[i,j], N[i,j]-Y[i,j] ))\nx<-rbind(x,c(i,j,Xd[i,j,])) }}\n }\n\n\nif(rd>0) {\n fit1<-glm(y~-1+as.factor(x[,1])+as.factor(x[,2])+x[,-(1:2)],family=fam) }\nif(rd==0){ fit1<-glm(y~-1+as.factor(x[,1])+as.factor(x[,2]),family=fam) }\n \ns<-fit1$coef[1:n]\nr<-c(0,fit1$coef[n+1:(n-1)])\nif(rd>0){\nbeta.d<-fit1$coef[(2*n):length(fit1$coef)] #beta.d\n }\n \nla<-lm( s~-1+cbind(rep(.5,n),Xs)); a<-la$res\nlb<-lm( r~-1+cbind(rep(.5,n),Xr)); b<-lb$res\n \nb0<-(la$coef[1]+lb$coef[1])/2\n \ns1<-s+( b0-la$coef[1])/2 #s\nr1<-r+( b0-lb$coef[1])/2 #r\n \nla<-lm( s1~-1+cbind(rep(.5,n),Xs)); a<-la$res\nlb<-lm( r1~-1+cbind(rep(.5,n),Xr)); b<-lb$res\n \nbeta.u<-c(lb$coef[1], la$coef[-1],lb$coef[-1])\nSab<-var(cbind(a,b)) #Sab\n\nRes<-matrix(0,nrow=n,ncol=n)\nl<-1 \nfor( m in 1:dim(x)[1] ) {\nif( !is.na(y[m]) ) { Res[x[m,1],x[m,2]]<-fit1$res[l] ; l<-l+1 }\n }\n######\nRes[Res>quantile(Res,.95,na.rm=T) ] <- quantile(Res,.95,na.rm=T)\ndiag(Res)<-rep(0,n)\n \nif(k>0){\nfor(i in 1:50){\ntmp<-eigen( .5*(Res+t(Res) ))\nz<-tmp$vec[,1:k] %*%diag(sqrt(tmp$val[1:k]),nrow=k)\ndiag(Res)<-diag(z%*%t(z))\n }\nsz<-var(c(z)) #z,sz\nE<-Res-z%*%t(z) #E\n }\nif(k==0){E<-Res ; z<-matrix(0,nrow=n,ncol=1) ;sz<-.1}\n\nu<-E+t(E)\nu<-c(u[!is.na(UT)]) #su\nsu<-var(u) #sv\nv<-E-t(E)\nv<-c(v[!is.na(UT)])\nsv<-var(v)\n \nrho<-(su-sv)/(su+sv)\nse<-(su+sv)/4\n\n\n###construct priors centered on these empirical values\npi.Sab<-c(Sab[1,1],Sab[2,1],Sab[2,2],4)\npi.s2u<-c(2,su)\npi.s2v<-c(2,sv)\npi.s2z<-cbind( rep(2,k), diag( t(z)%*%z)/n )\n \nif(rd>0){\npim.bd<-c(beta.d)\npiS.bd<-as.matrix((n*(n-1))^2*summary(fit1)$cov.unscaled[(2*n):length(fit1$coef),\n (2*n):length(fit1$coef)] )\n }\n \n \nif(rd==0){ beta.d<-pim.bd<-NULL ; piS.bd<-matrix(nrow=0,ncol=0) }\n \nif(directed==T) {\npim.b0sr<-beta.u\npiS.b0sr<-rbind(cbind( summary(la)$cov[-1,-1], matrix(0,nrow=rs,ncol=rr)),\n# cbind(matrix(0,nrow=rs,ncol=rr),summary(lb)$cov[-1,-1]))\n# error found 7-7-6\n cbind(matrix(0,nrow=rr,ncol=rs),summary(lb)$cov[-1,-1]))\n\npiS.b0sr<-rbind(c(summary(la)$cov[1,-1],summary(lb)$cov[1,-1]),piS.b0sr)\npiS.b0sr<-cbind(c(summary(la)$cov[1,1:(rs+1)],\n summary(lb)$cov[1,-1]),piS.b0sr)\npiS.b0sr<-as.matrix(piS.b0sr*n*n) \n\npim.b0s<-NULL ; piS.b0s<-NULL ;pi.s2a<-NULL\n }\nif(directed==F) { pim.b0sr<-NULL ; piS.b0sr<-NULL ; pi.Sab<-NULL\n s<-(s+r)/2 ; r<-s*0\n tmp2<-lm(s~-1+cbind( rep(.5,n),Xs)) \n beta.u<-tmp2$coef ; pi.s2a<-c(2,var(tmp2$res)) ;\n pim.b0s<-tmp2$coef ; piS.b0s<-summary(tmp2)$cov*n*n }\n\n\n\n###\nlist( priors=list(pi.Sab=pi.Sab,pi.s2u=pi.s2u,pi.s2v=pi.s2v,pi.s2z=pi.s2z,\n pim.bd=pim.bd,piS.bd=piS.bd,\n pim.b0sr=pim.b0sr,piS.b0sr=piS.b0sr,\n pim.b0s=pim.b0s, piS.b0s=piS.b0s , pi.s2a=pi.s2a) ,\n startv=list(beta.d=beta.d,beta.u=beta.u,s=s,r=r,z=z)\n )\n}\n\n\n####\nrbeta.d.s.gibbs<-function(u,su,piS.bd,mu,s2a){\niSa<-diag(rep(1/s2a,n))\n\nif(dim(piS.bd)[1]>0){\ncov.beta.s<-matrix(0,nrow=rd,ncol=n)\niS<-rbind(cbind(solve(piS.bd),cov.beta.s),\n cbind(t(cov.beta.s),iSa)) }\nelse{iS<-iSa}\n\nSig<-chol2inv( chol(iS + tXTuXTu/su ) )\n #this may have a closed form expression\n\ntheta<-Sig%*%( t( (u%*%XTu)/su) + iS%*%mu)\n\nbeta.s<-rmvnorm(theta,Sig)\nlist(beta.d=beta.s[(rd>0):rd],s=beta.s[rd+1:n]) }\n####\n\n####\nrbeta.s.gibbs<-function(s,X.u,pim.b0s,piS.b0s,s2a) {\niSa<-diag(rep(1/s2a,n))\n\nS<-solve( solve(piS.b0s) + t(X.u)%*%iSa%*%X.u )\nmu<-S%*%( solve(piS.b0s)%*%pim.b0s+ t(X.u)%*%iSa%*%s)\nrmvnorm( mu,S)\n }\n\n\n", "meta": {"hexsha": "4b1dfc5fc44a5f8f9ff2b0227fab0199454285e0", "size": 20575, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/gbme.r", "max_stars_repo_name": "hurwitzlab/gbme", "max_stars_repo_head_hexsha": "52acc4584c212f6e85fb59711e6a95a2a8faf15a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/gbme.r", "max_issues_repo_name": "hurwitzlab/gbme", "max_issues_repo_head_hexsha": "52acc4584c212f6e85fb59711e6a95a2a8faf15a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/gbme.r", "max_forks_repo_name": "hurwitzlab/gbme", "max_forks_repo_head_hexsha": "52acc4584c212f6e85fb59711e6a95a2a8faf15a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9927113703, "max_line_length": 97, "alphanum_fraction": 0.5213122722, "num_tokens": 7516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45591719232617445}} {"text": "model_snowwet <- function (Swet_t1 = 0.0,\n precip = 0.0,\n Snowaccu = 0.0,\n Mrf = 0.0,\n M = 0.0,\n Sdry = 0.0){\n #'- Name: SnowWet -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: water in liquid state in the snow cover calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: water in liquid state in the snow cover\n #'- inputs:\n #' * name: Swet_t1\n #' ** description : water in liquid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: precip\n #' ** description : current precipitation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Snowaccu\n #' ** description : snowfall accumulation\n #' ** inputtype : variable\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: Mrf\n #' ** description : liquid water in the snow cover in the process of refreezing\n #' ** inputtype : variable\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: M\n #' ** description : snow in the process of melting\n #' ** inputtype : variable\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: Sdry\n #' ** description : water in solid state in the snow cover\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #'- outputs:\n #' * name: Swet\n #' ** description : water in liquid state in the snow cover\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n Swet <- 0.0\n if (Mrf <= Swet_t1)\n {\n tmp_swet <- Swet_t1 + precip - Snowaccu + M - Mrf\n frac_sdry <- 0.1 * Sdry\n if (tmp_swet < frac_sdry)\n {\n Swet <- tmp_swet\n }\n else\n {\n Swet <- frac_sdry\n }\n }\n return (list('Swet' = Swet))\n}", "meta": {"hexsha": "6e7c3e7c18aa4b00c6de18f337640326539990ac", "size": 4384, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Snowwet.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/Snowwet.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/Snowwet.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2828282828, "max_line_length": 108, "alphanum_fraction": 0.299270073, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4559171856660425}} {"text": "#' @title interpolate.xy.robust\n#' @description Interpolate some xy data used by netmensuration and mode fifnding methods.\n#' @family abysmally documented\n#' @author Jae Choi, \\email{jae.choi@dfo-mpo.gc.ca}\n#' @export\ninterpolate.xy.robust = function( xy, method, target.r2=0.9, mv.win=10, trim=0.05,\n probs=c(0.025, 0.975), loess.spans=seq( 0.25, 0.01, by=-0.01 ), inla.model=\"rw2\",\n smoothing.kernel=kernel( \"modified.daniell\", c(2,1)), nmax=3, inla.h=0.1, inla.diagonal=0.01, inla.ngroups=400 ) {\n\n # simple interpolation methods\n # target.r2 == target prediction R^2\n\n if (FALSE) {\n x=seq(-5,5,by=0.1)\n y=sin(x) + runif(length(x))^2\n xy = data.frame( x=x, y=y )\n target.r2=0.9\n nmax=5 # max number of times to try to reduce data set\n probs=c(0.025, 0.975)\n loess.spans=seq( 0.2, 0.01, by=-0.01 )\n inla.model=\"rw2\"\n smoothing.kernel=kernel( \"modified.daniell\", c(2,1))\n }\n\n if ( is.vector(xy) ) {\n nz = length(xy)\n z = data.frame( x=1:nz, y=xy )\n } else {\n if (ncol(xy) == 2 ) {\n nz = nrow(xy)\n z = data.frame( xy)\n names(z) = c(\"x\", \"y\" )\n } else {\n stop( \"Error: y or c(x,y) expected\")\n }\n }\n\n\n z$p= NA\n z$noise = FALSE\n z$loc = 1:nz # row index used in seq lin method\n\n\n if (method == \"moving.window\" ) {\n z$p = z$y\n for (nw in mv.win:1) {\n win = -nw:nw\n z$p = NA\n for( i in 1:nz ) {\n iw = i+win\n iw = iw[ which( iw >= 1 & iw <=nz ) ]\n z$p[i] = mean( z$y[iw], na.rm=TRUE )\n }\n z$diff = abs( z$p - z$y )\n qnts = quantile( z$diff, probs=(1-trim), na.rm=TRUE ) # remove upper quantile\n ii = which( z$diff > qnts )\n if (length(ii) > 0) z$p[ ii ] = NA\n z$p[ii] = approx( x=z$x, y=z$p, xout=z$x[ii], method=\"linear\", rule=2 )$y\n rsq = cor( z$p, z$y, use=\"pairwise.complete.obs\" )^2\n if (!is.na(rsq)) {\n if (rsq > target.r2 ) break()\n }\n }\n }\n\n\n if (method ==\"sequential.linear\") {\n # check adjacent values and reject if differences are greater than a given range of quantiles (95%)\n\n m = z # locs are the location indices for z$y ... to bring back into \"z\"\n m = m[ which(is.finite( m$y)) , ]\n lg = 1 # lag\n nw = nrow( m ) # staring number of data points\n nw_target = nw * (1-trim) # proportion of data to retain (not trim)\n\n while ( nw > nw_target ) {\n yd0 = c( diff( m$y, lag=lg ) , rep( 0, lg )) # diffs left-right # padding with 0's (no change)\n dm = quantile( yd0, probs=probs, na.rm=TRUE )\n n = which( yd0 < dm[1] | yd0 > dm[2] )\n if (length(n) == 0 ) break()\n if ( length(n) > 0 ) m = m[-n, ] # remove na's and then assess again\n nw = nrow( m )\n }\n\n # m$locs contains indices of \"good\" data .. setdiff to get the \"bad\" .. set to NA and then\n # infill missing with interpolated values\n ii = setdiff( 1:nz, unique(m$loc) )\n if (length(ii) > 0) {\n z$y[ii] = NA\n afun = approxfun( x=z$x, y=z$y, method=\"linear\", rule=2 )\n z$y[ii] = afun( z$x[ii] )\n }\n z$p = z$y\n }\n\n\n if (method ==\"local.variance\") {\n # local variance estimates used to flag strange areas .. where local variance is too high .. remove the data\n\n z$p = z$y\n for (nw in mv.win:1) {\n z$Zvar = NA\n win = c( -nw : nw )\n for (i in 1:nz ) {\n iw = i+win\n iw = iw[ which(iw >=1 & iw<= nz)]\n if (length(iw)> 3) z$Zvar[i] = var( z$p[iw], na.rm=TRUE )\n }\n qnts = quantile( z$Zvar, probs=(1-trim), na.rm=TRUE ) # remove upper quantile\n ii = which( z$Zvar > qnts )\n if (length(ii) > 0) z$p[ ii ] = NA\n afun = approxfun( x=z$x, y=z$p, method=\"linear\", rule=2 )\n z$p[ii] = afun( z$x[ii] )\n rsq = cor( z$p, z$y, use=\"pairwise.complete.obs\" )^2\n if (!is.na(rsq)){\n if (rsq > target.r2 ) break()\n }\n }\n }\n\n\n if (method == \"loess\" ) {\n var0 = var( z$y, na.rm=TRUE)\n for( sp in loess.spans ) {\n # ID a good span where loess solution ~ real data\n\n loess.mod = try( loess( y ~ x, data=z, span=sp, control=loess.control(surface=\"direct\"),na.action = na.exclude ), silent=TRUE )\n if ( \"try-error\" %in% class(loess.mod) ) next()\n z$p = predict( loess.mod, newdata=z )\n rsq = cor( z$p, z$y, use=\"pairwise.complete.obs\" )^2\n if (!is.na(rsq)) {\n if (rsq > target.r2 ) {\n # if ( var( z$p, na.rm=TRUE) < var0 ) \n\t\tbreak()\n }\n }\n }\n }\n\n\n\n if (method == \"inla\") {\n\n require(INLA)\n ymean = mean( z$y, na.rm=TRUE )\n z$y = z$y - ymean\n nn = abs( diff( z$x) )\n dd = median( nn[nn>0], na.rm=TRUE )\n z$xiid = z$x = jitter( z$x, amount=dd / 20 ) # add noise as inla seems unhappy with duplicates in x?\n\n rsq = 0\n nw = length( which(is.finite( z$y)))\n nw0 = nw + 1\n count = 0\n\n ndat = nrow( z )\n #if ( ndat < inla.ngroups ) inla.ngroups = ndat\n\n # m = get(\"inla.models\", INLA:::inla.get.inlaEnv())\n # m$latent$rw2$min.diff = NULL\n # assign(\"inla.models\", m, INLA:::inla.get.inlaEnv())\n\n # inla's default RW2 resolution is too coarse, causing incomplete solution:\n # alter a bit as this is potentially a smoothed series\n #menv = get(\"inla.models\", INLA:::inla.get.inlaEnv())\n #menv$latent$rw2$min.diff =1e-4\n # assign(\"inla.models\", menv, INLA:::inla.get.inlaEnv() )\n h = 0.02\n while ( nw != nw0 ) {\n count = count + 1\n if (count > nmax ) break() # this is CPU expensive ... try only a few times\n\n FM = formula( y ~ f( inla.group(xiid, n=inla.ngroups), model=\"iid\")\n + f( inla.group(x, n=inla.ngroups), model=inla.model )\n )\n v = NULL\n v = try( inla( FM, data=z,\n control.predictor=list (compute=TRUE ),\n control.compute=list(config=TRUE),\n control.results=list(return.marginals.random=TRUE, return.marginals.predictor=TRUE ),\n control.inla = list( h=h ), # increase in case values are too close to zero\n # control.mode = list( restart=TRUE, result=v ), # restart from previous estimates\n quantiles=NULL, # no quants to save storage requirements\n verbose=FALSE )\n , silent=TRUE )\n\n if ( \"try-error\" %in% class(v) ) next()\n\n # make sure Eigenvalues of Hessian are appropriate (>0)\n if ( v$mode$mode.status > 0 ) {\n h = h + 0.02\n next()\n }\n\n z$p = v$summary.fitted.values$mean\n rsq = cor( z$p, z$y, use=\"pairwise.complete.obs\" )^2\n\n if (!is.na(rsq)) if (rsq > target.r2) break()\n\n # drop a few extreme data points and redo\n iid = v$summary.random$xiid[[\"mean\"]]\n qiid = quantile( iid, probs=probs, na.rm=TRUE )\n i = which( iid > qiid[2] | iid < qiid[1] )\n if (length( i) > 0 ) z$y[i] = z$p[i]\n nw0 = nw\n nw = length( which(is.finite( z$y))) # to check for convergence\n }\n # return to original scale\n z$y = z$y + ymean\n z$p = z$p + ymean\n }\n\n\n if (method==\"kernel.density\") {\n # default method is kernel( \"modified.daniell\", c(2,1)),\n # a 2X smoothing kernel: 2 adjacent values and then 1 adjacent on the smoothed series .. i.e. a high-pass filter\n nd = length(smoothing.kernel$coef) - 1 # data points will be trimmed from tails so need to recenter:\n\n # test in case x increments are not uniform\n vv = unique( diff( z$x ) )\n xr = min(vv[vv>0])\n uu = unique( round( vv, abs(log10(xr))))\n if (length(uu) > 1 ) {\n # interpolate missing/skipped data before smoothing\n ifunc = approxfun( x= z$x, y=z$y, method=\"linear\", rule=2 )\n r0 = range( z$x, na.rm=TRUE )\n fx = seq( r0[1], r0[2], by= min(uu) )\n fy = ifunc( fx)\n } else if (length(uu) ==1 ) {\n fx = z$x\n fy = z$y\n }\n fn = length( fx)\n si = (nd+1):(fn-nd)\n fp = rep( NA, fn)\n fp[si] = kernapply( as.vector(z$y), smoothing.kernel )\n\n\n pfunc = approxfun( x=fx, y=fp, method=\"linear\", rule=2)\n z$p = pfunc( z$x)\n # plot( p ~ x, z, type=\"l\" )\n\n # constrain range of predicted data to the input data range\n TR = quantile( z$y, probs=probs, na.rm=TRUE )\n toolow = which( z$p < TR[1] )\n if ( length(toolow) > 0 ) z$p[toolow] = TR[1]\n toohigh = which( z$p > TR[2] )\n if ( length(toohigh) > 0 ) z$p[toohigh] = TR[2]\n # lines( y ~ x, z, col=\"green\" )\n }\n\n if (method==\"tukey\" ) {\n z$p =smooth( z$y )\n }\n\n\n\n if (method==\"simple.linear\") {\n pfunc = approxfun( x=z$x, y=z$y, method=\"linear\", rule=2)\n z$p = pfunc( z$x)\n }\n\n\n if (method==\"gam\") {\n require(mgcv)\n gmod = gam( y ~ s(x) , data=z)\n z$p = predict( gmod, z, type=\"response\" )\n }\n\n if (method==\"smooth.spline\") {\n # similar to inla .. duplicated x is problematic for smooth.spline ... add small noise\n nn = abs( diff( z$x) )\n dd = median( nn[nn>0], na.rm=TRUE )\n z$x = jitter( z$x, amount=dd / 20) # add noise as inla seems unhappy with duplicates in x?\n rsq = 0\n nw = length( which(is.finite( z$y)))\n nw0 = nw + 1\n count = 0\n while ( nw != nw0 ) {\n count = count + 1\n if ( count > nmax ) break() # in case of endless loop\n uu = smooth.spline( x=z$x, y=z$y, keep.data=FALSE, control.spar=list(tol=dd / 20) )\n if ( length(uu$x) != nrow(z) ) {\n afun = approxfun( x=uu$x, y=uu$y, method=\"linear\", rule=2 )\n vv = afun( z$x )\n z$p = vv$y\n } else {\n z$p = uu$y\n }\n rsq = cor( z$p, z$y, use=\"pairwise.complete.obs\" )^2\n if (!is.na(rsq)){\n if (rsq > target.r2) break()\n }\n # drop a few extreme data points and redo\n iid = z$y - z$p\n qiid = quantile( iid, probs=probs, na.rm=TRUE )\n i = which( iid > qiid[2] | iid < qiid[1] )\n if (length( i) > 0 ) {\n z$y[i] = z$p[i]\n }\n nw0 = nw\n nw = length( which(is.finite( z$y))) # to check for convergence\n }\n }\n\n return(z$p)\n\n}\n\n\n\n\n", "meta": {"hexsha": "3aceb6eef6042624eecc2059ff6c4a37e3f83b90", "size": 9892, "ext": "r", "lang": "R", "max_stars_repo_path": "R/interpolate.xy.robust.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/interpolate.xy.robust.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/interpolate.xy.robust.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6038338658, "max_line_length": 133, "alphanum_fraction": 0.5386170643, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193603519451}} {"text": "# Load Analysis toolbox\n#\n# Pär Johannesson, 15-Sep-2011, 22-May-2015, 17-Aug-2018\n#\n# ts2tp Time signal to Turning Points (optional rainflow filter)\n# tp2arfc4p Calculates asymmetric rainflow cycles from turning points (4-point)\n# tp2rfc Calculates rainflow cycles from turning points (incl. residual)\n\n# -------------------------------------------------------------\n\n# =============================================================\n# ts2tp Time signal to Turning Points (optionally rainflow filtered).\n#\n# CALL: [y] <- rfcfilter(x,h,def);\n#\n# Input:\n# x = Signal. [nx1] OR [nx2]\n# h = Threshold for rainflow filter.\n# def = 0: removes cycles with range < h. (default)\n# 1: removes cycles with range <= h. (default only if h=0)\n# Output:\n# y = Rainflow filtered signal.\n#\n# Examples: # 1. Filtered signal y is the turning points of x.\n# tmp<-read.table(datafil,header=FALSE,stringsAsFactors=FALSE,fill=TRUE)\n# y <- ts2tp(x);\n# # 2. This removes all rainflow cycles with range less than 0.5.\n# y <- ts2tp(x,0.5);\n#\n\nts2tp <- function(x,h=0,def=0)\n{\n \n if(h==0) {\n def <- 1\n }\n \n # Initiation\n \n if(is.data.frame(x)) {\n x <- as.matrix(x) # Convert to matrix\n }\n \n if(is.matrix(x)) {\n n <- nrow(x) # Number of turning points\n }\n else if(is.numeric(x)) {\n n <- length(x) # Number of turning points\n x <- matrix(c(1:n,x),n,2)\n }\n else {\n #ERROR\n }\n \n Ind <- rep(0,n)\n \n j <- 0\n t0 <- 1\n y0 <- x[1,2]\n z0 <- 0\n Ind[1] <- 1\n \n tmin <- 1\n ymin <- y0\n tmax <- 1\n ymax <- y0\n \n # The rainflow filter\n \n for(k in 2:n) {\n fpk <- y0+h\n fmk <- y0-h\n tk <- k\n xk <- x[k,2]\n \n if(z0 == 0) {\n if(xk>ymax) {tmax <- tk; ymax <- xk }\n if(xk=h)\n }\n else { # def == 1\n test <- (ymax-ymin>h)\n }\n \n if(test) {\n if(tminfmk)) | ((z0==-1) & (xk>=fpk)))\n }\n else { # def == 1\n test1 <- (((z0==+1) & (xk=fmk)) | ((z0==-1) & (xk>fpk)))\n }\n \n # Update z1\n if(test1) { z1 <- -1 }\n else if(test2) { z1 <- +1 }\n else { } # warning(['Something wrong, i=' num2str(i)]);\n \n # Update y1\n if(z1 != z0) {\n t1 <- tk\n y1 <- xk\n }\n else if(z1 == -1) {\n # % y1 = min([y0 xi]);\n if(y0 < xk) {\n t1 <- t0\n y1 <- y0\n }\n else {\n t1 <- tk\n y1 <- xk\n }\n }\n else if(z1 == +1) {\n # % y1 = max([y0 xi]);\n if(y0 > xk) {\n t1 <- t0\n y1 <- y0\n }\n else {\n t1 <- tk\n y1 <- xk\n }\n }\n }\n \n # Update y if y0 is a turning point\n #if(abs(z0-z1) == 2) {\n if(abs(z0-z1) > 0) {\n j <- j+1\n Ind[j] <- t0\n }\n \n # Update t0, y0, z0\n t0 <- t1\n y0 <- y1\n z0 <- z1\n }\n \n # Update y if last y0 is greater than (or equal) threshold\n if(z0 == 0) { # All ranges below threshold\n j <- 1 # return the first value\n }\n else {\n if(def == 0) { test <- (abs(y0-x[Ind[j],2]) >= h) }\n else { test <- (abs(y0-x[Ind[j],2]) > h) } # def == 1\n if(test) {\n j <- j+1\n Ind[j] <- t0\n }\n }\n # Truncate Ind\n Ind <- Ind[1:j]\n y <- matrix(x[Ind,],ncol=2)\n \n #res <- list(y=y,Ind=Ind)\n y\n}\n# END: ts2tp\n# =============================================================\n\n\n# =============================================================\n# tp2arfc4p Calculates asymmetric rainflow cycles from turning points (4-point)\n#function [ARFC,res] = tp2arfc4p(x,res0,def_time)\n#%TP2ARFC4P Calculates asymmetric rainflow cycles from turning points (4-point).\n#%\n#% CALL: [ARFC,res] = tp2arfc4p(tp)\n#% [ARFC,res] = tp2arfc4p(tp,res0,def_time)\n#%\n#% Output:\n#% ARFC = Asymmetric RFC (without residual). [N,2]/[N,4]\n#% res = Residual. [nres,1]/[nres,2]\n#%\n#% Input:\n#% tp = Turning points. [T,1]/[T,2]\n#% res0 = Residual. [nres0,1]/[nres0,1]\n#% def_time = 0: Don't store time of max and min. (default)\n#% 1: Store the time when the maxima and minima occured.\n#%\n#% Calculates the rainflow cycles for the sequence of turning points,\n#% by using the so-called 4-point algorithm.\n#%\n#% Calculate ARFC for turning points, starting from old residual 'res0'\n#% [ARFC,res] = tp2arfc4p(tp,res0)\n#%\n#% This routine doesn't use MEX, Fortran or C codes, only matlab code.\n#%\n#% Example:\n#% x = load('sea.dat'); tp=dat2tp(x);\n#% [ARFC,res]=tp2arfc4p(tp); % Default (min-to-Max cycles in residual)\n#% ccplot(ARFC), res\n#%\n\ntp2arfc4p <- function(tp)\n{\n if(is.matrix(tp)) { tp <- tp[,2] }\n \n T <- length(tp) # Number of turrning points\n RFC <- matrix(NaN,floor(T/2),2) # Rainflow cycles\n N <- 0 # Number of counted cycles\n \n res <- tp # Residual\n nres <- 0 # Number of points in residual\n \n # Calculate ARFC and res\n for(k in 1:T) {\n nres <- nres+1\n res[nres] <- tp[k]\n cycleFound <- TRUE\n while(cycleFound & nres >=4) {\n A <- sort(res[(nres-2):(nres-1)])\n B <- sort(res[c((nres-3),nres)])\n if(A[1]>=B[1] & A[2]<=B[2]) {\n N <- N+1\n RFC[N,] <- res[(nres-2):(nres-1)]\n res[nres-2] <- res[nres]\n nres <- nres-2\n }\n else {\n cycleFound <- FALSE\n }\n }\n }\n \n # Counted rainflow cycles & Residual\n \n #RFC <- RFC[1:N,]\n #if(N==0) { RFC <- NULL } else {RFC <- matrix(RFC[1:N,],ncol=2) }\n #if(nres==0) { res <- NULL } else {res <- res[1:nres]}\n RFC <- matrix(RFC[1:N,],ncol=2)\n res <- res[1:nres]\n \n out <- list(RFC=RFC, res=res)\n \n}\n# END: tp2rfc4p\n#=============================================================\n\n\n#=============================================================\n# tp2rfc Calculates rainflow cycles from turning points (incl. residual)\ntp2rfc <- function(tp) { # Calculate ARFC0 and res\n \n R <- tp2arfc4p(tp)\n \n res2 <- ts2tp(c(R$res,R$res)) # TP of double residual\n Rres <- tp2arfc4p(res2)\n \n if(is.na(R$RFC[1,1])) { n <- 0 } else { n <- nrow(R$RFC) }\n if(is.na(Rres$RFC[1,1])) { nres <- 0 } else { nres = nrow(Rres$RFC) }\n if(n+nres==0) {RFC <- R$RFC} else { RFC <- matrix(ncol=2, nrow=n+nres) }\n if(n!=0) { RFC[1:n,] <- R$RFC }\n if(nres!=0) { RFC[(n+1):(n+nres),] <- Rres$RFC }\n \n RFC\n}\n# END: tp2rfc\n#=============================================================\n\n\n#=============================================================\n# Extract ranges from rainflow cycles\nrfc2ls <- function(RFC, new=FALSE, log=\"x\", title=\"Load spectrum\", xlab=\"Cumulative number of cycles\", ylab=\"Load range\",N=1)\n{\n \n rfc.rang<-data.frame(\"S\"=sort(abs(RFC[,2]-RFC[,1]),decreasing=TRUE), \"n\"=rep(1,times=length(RFC[,1])))\n rfc.rang<-rbind(rfc.rang,c(0,N))\n # rfc.rang<-rbind(rfc.rang,c(N,0))\n if (new)\n lines((cumsum(rfc.rang$n)),sort(rfc.rang$S,decreasing=TRUE),type=\"S\",lwd=2,col=\"red\")\n else\n {\n plot(cumsum(rfc.rang$n),sort(rfc.rang$S,decreasing=TRUE), type=\"S\", log=log, lwd=2, col=\"blue\",\n main=title, xlab=xlab, ylab=ylab)\n grid()\n }\n \n return(rfc.rang)\n}\n# END: rfc2ls\n#=============================================================\n\n#=============================================================\n#Find level crossings from rain flow cycles\nrfc2lc <- function(RFC, n=200, new=FALSE, log=\"x\", title=\"Level crossings\", xlab=\"Number of up-crossings\", ylab=\"Load level\")\n{\n \n rfc<-RFC\n \n for (i in 1:length(RFC[,1]))\n rfc[i,]<-sort(RFC[i,])\n \n levels<-seq(min(rfc[,1]),max(rfc[,2]),len=n)\n \n lc<-numeric()\n for (j in 1:n)\n lc[j]<-sum((rfc[,2]>levels[j] )& (rfc[,1]<=levels[j]))\n if(new)\n #lines(levels,lc,type=\"S\",lwd=2,col=\"red\")\n lines(lc,levels,type=\"S\",lwd=2, col=\"red\")\n else\n {\n #plot(levels,lc,type=\"S\",lwd=2,ylab=\"up-crossings\",main=title,col=\"blue\")\n plot(lc, levels, type=\"S\", log=log, lwd=2, col=\"blue\", main=title, xlab=\"Number of up-crossings\", ylab=\"Load level\")\n grid()\n }\n \n data.frame(\"S\"=levels, \"Nup\"=lc)\n}\n", "meta": {"hexsha": "bb4bcc75aa3fd3bc473ad928ad3640b185d2fe05", "size": 8833, "ext": "r", "lang": "R", "max_stars_repo_path": "Apps/load-analysis/LoadAnalysisTools.r", "max_stars_repo_name": "pj3950/fdt", "max_stars_repo_head_hexsha": "abf51dd30da7a11af0d7567708c2023adb3c4b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-12T22:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T22:15:32.000Z", "max_issues_repo_path": "Apps/load-analysis/LoadAnalysisTools.r", "max_issues_repo_name": "pj3950/fdt", "max_issues_repo_head_hexsha": "abf51dd30da7a11af0d7567708c2023adb3c4b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Apps/load-analysis/LoadAnalysisTools.r", "max_forks_repo_name": "pj3950/fdt", "max_forks_repo_head_hexsha": "abf51dd30da7a11af0d7567708c2023adb3c4b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8480243161, "max_line_length": 125, "alphanum_fraction": 0.4632627646, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45425879207616293}} {"text": "\n a1<-read.table(\"A-gene.txt\",header=F)\n b1<-read.table(\"A-mRNA.txt\",header=F)\n c1<-read.table(\"A-STRING.txt\",header=F)\n d1<-read.table(\"A-pearson.txt\",header=F)\n\n a<-read.table(\"D-gene.txt\",header=F)\n b<-read.table(\"D-mRNA.txt\",header=F)\n c<-read.table(\"D-STRING.txt\",header=F)\n d<-read.table(\"D-pearson.txt\",header=F)\n\n n <- a-a1\n n1<- 0.1*n\n\n m <- b-b1\n m1<- 0.1*m\n\n p <- c-c1\n p1<- 0.1*p\n\n q <- d-d1\n q1<- 0.1*q\n\n i<-read.table(\"I.txt\",header=F)\n\n n2 <- -1*n1\n m2 <- -1*m1\n p2 <- -1*p1\n q2 <- -1*q1\n\n n3 <- i+n2\n m3 <- i+m2\n p3 <- i+p2\n q3 <- i+q2\n\n n4 <- solve(n3)\n m4 <- solve(m3)\n p4 <- solve(p3)\n q4 <- solve(q3)\n\n y<-read.table(\"y.txt\",header=F)\n y0<-as.matrix(y)\n\n ygene <- n4%*% y0\n ymRNA <- m4%*% y0\n ySTRING <- p4%*% y0\n ypearson <- q4%*% y0\n\n write.table(ygene,\"y-gene.txt\",quote=F,row.names=F,col.names=F)\n write.table(ymRNA,\"y-mRNA.txt\",quote=F,row.names=F,col.names=F)\n write.table(ySTRING,\"y-STRING.txt\",quote=F,row.names=F,col.names=F)\n write.table(ypearson,\"y-pearson.txt\",quote=F,row.names=F,col.names=F)\n", "meta": {"hexsha": "0bdce718a0017884a00141678d097cb8ce75ce9d", "size": 1026, "ext": "r", "lang": "R", "max_stars_repo_path": "source/kernel.r", "max_stars_repo_name": "Crystal-JJ/maize", "max_stars_repo_head_hexsha": "6f772fd0b3f060027a4f6f1bdca9f0d96c2970a8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-06T04:40:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T04:40:19.000Z", "max_issues_repo_path": "source/kernel.r", "max_issues_repo_name": "Crystal-JJ/maize", "max_issues_repo_head_hexsha": "6f772fd0b3f060027a4f6f1bdca9f0d96c2970a8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/kernel.r", "max_forks_repo_name": "Crystal-JJ/maize", "max_forks_repo_head_hexsha": "6f772fd0b3f060027a4f6f1bdca9f0d96c2970a8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.358490566, "max_line_length": 70, "alphanum_fraction": 0.6023391813, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.45374621503400475}} {"text": "subroutine intri(x,y,u,v,n,okay)\n#\n# Test whether any of the points (u(i),v(i)) are inside the triangle\n# whose vertices are specified by the vectors x and y.\n# Called by .Fortran() from triang.list.R.\n#\n\nimplicit double precision(a-h,o-z)\ndimension x(3), y(3), u(n), v(n)\ninteger okay\nlogical inside\n\nzero = 0.d0\n\n# Check on order (clockwise or anticlockwise).\ns = 1.d0\na = x(2) - x(1)\nb = y(2) - y(1)\nc = x(3) - x(1)\nd = y(3) - y(1)\ncp = a*d - b*c\nif(cp < 0) s = -s\ndo i = 1,n {\n\tinside = .true.\n\tdo j = 1,3 {\n \tjp = j+1\n \tif(jp==4) jp = 1 # Take addition modulo 3.\n\t\ta = x(jp) - x(j)\n\t\tb = y(jp) - y(j)\n\t\tc = u(i) - x(j)\n\t\td = v(i) - y(j)\n\t\tcp = s*(a*d - b*c)\n\t\tif(cp <= zero) {\n\t\t\tinside = .false.\n\t\t\tbreak\n\t\t}\n\t}\n\tif(inside) {\n\t\tokay = 0\n\t\treturn\n\t}\n\t\n}\nokay = 1\nreturn\nend\n", "meta": {"hexsha": "22e3528c34b9ab9bbf15f2c4c742a48c0bd7b9d1", "size": 799, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/ratfor/intri.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/ratfor/intri.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/ratfor/intri.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 17.0, "max_line_length": 68, "alphanum_fraction": 0.5381727159, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45351017425734397}} {"text": "subroutine bakfit(x,npetc,y,w,which,spar,dof,match,nef,\n\t\t\tetal,s,eta,beta,var,tol,\n\t\t\tqr,qraux,qpivot,effect,work)\n#integer npetc(7)\n#1:n\n#2:p\n#3:q\n#4:ifvar\n#5:nit\n#6:maxit\n#7:qrank\n#subroutine bakfit(x,n,p,y,w,q,which,spar,dof,match,nef,\n#\t\t\tetal,s,eta,beta,var,ifvar,tol,nit,maxit,\n#\t\t\tqr,qraux,qrank,qpivot,work)\n#This subroutine fits an additive spline fit to y\n#All arguments are either double precision or integer\n# bakfit uses the modified backfitting algorithm described in Buja, Hastie \n# and Tibshirani, Annals of Statistics, 1989. It calls splsm, and some\n# linpack based routines\n# This was written by Trevor Hastie in 1990\n# It has been modified from the S3 version by Trevor Hastie\n# in March 2005, to accommodate the modified sbart routine in R\n# Note that spar has changed, and we change it here to conform with\n# the smooth.spline routine in R\n#INPUT\n#\n#x\tdouble dim n by p ; x variables, includes constant\n#n\tinteger number of rows in x\n#p\tinteger number of columns of x\n#y\tdouble length n\t; y variable for smoothing\n#w\tdouble length n ; prior weights for smoothing, > 0\n#q\tinteger number of nonlinear terms\n#which \tinteger length q indices of columns of x for nonlinear fits\n#spar\tdouble length q spars for smoothing; see below\n#dof\tdouble length q dof for/from smoothing; see below\n#match \tinteger n by q matrix of match'es; see below\n#nef\tinteger q vector of nef's; see below\n#s\tdouble n by q nonlinear part of the smooth functions\n#\t\tused as starting values. the linear part is\n#\t\tirrelevant\n#ifvar\tlogical should the variance information be computed\n#tol\tdouble tolerance for backfitting convergence; 0.0005 is good\n#maxit\tinteger maximum number of iterations; 15 is good\n#qr\tdouble n by p weighted qr decomposition of x\n#qraux \tdouble p belongs with qr\n#qrank\tinteger rank of x ; if qrank=0, then bakfit computes qr and qraux\n#qpivot\tinteger p the columns of qr are rearranged according to pivot\n#effec double n effect vector\n#work\tdouble \n#\tLet nk=max(nef)+2, then \n# \twork should be (10+2*4)*nk+5*nef+5*n+15 +q double\n#BELOW\n#the following comments come from documentation for splsm\n#\tthey apply to each element of spar,dof match etc\n#spar\tdouble smoothing parameter -1.5 =1, dof is used\n#\t\tnote: dof does not use the constant term\n#match \tinteger length n -- in S language x[i] == sort(unique(x)[match[i]]\n#\t\tmatch is produced by subroutine namat\n#nef\tnumber of unique elements in x; so match has values between 1 and nef+1\n#\t\tmissing data are given the match number nef+1\n#work\tdouble workspace of length (10+2*4)*(nef+2)+5*nef+n+15\n#\n#OUTPUT\n#\n#x,y,w,n,p,which,q,maxit,match,nef are untouched\n#spar\tfor each element of spar:\n# \tif spar was 0 and dof was 0, then spar is that spar \n#\t\t\tthat minimized gcv\n#\tif spar was 0 and dof > 0, then spar is that which achieves dof\n#dof\tthe dof of the fitted smooth. Note: even if dof was given\n#\t\tas 4, it will be returned as say 3.995 which is what\n#\t\tspar produces\n#etal\tdouble length n linear component of the fit\n#s\tdouble n by q nonlinear part of the smooth functions\n#eta\tdouble length n fitted values\n#beta\tdouble length p linear coefficients\n# So, the centered fitted functions are:\n#\t\t\t b(j)*(x(i,j)-mean(x(.,j)) +s(i,j)\n#\t\twhere j is an element of which\n#var\tdouble n by q \n#\tif ifvar was .true.\n#\t\tthe unscaled variance elements for the NONLINEAR\n#\t\tand UNIQUE part of s, in the order of sort(unique(x))\n#\t\tvar is lev(i)/w(i) -h(i)/w where h(i) is the hat element from\n#\t\tthe simple weighted least squares fit. This is used in gamcov\n#\n#nit\tnumber of iterations used\n#qr etc the qr is returned\n\nimplicit double precision(a-h,o-z)\nlogical ifvar\ninteger npetc(7),iter\ninteger n,p,q,which(*),match(*),nef(*),nit,maxit,qrank,qpivot(*)\ndouble precision x(*),y(*),w(*),spar(*),dof(*),\n\t\t\tetal(*),s(*),eta(*),beta(*),var(*),tol,\n\t\t\tqr(*),qraux(*),effect(*),work(*)\nn=npetc(1)\np=npetc(2)\nq=npetc(3)\nifvar=.false.\nif(npetc(4)==1)ifvar=.true.\nmaxit=npetc(6)\nqrank=npetc(7)\ndo i=1,q{work(i)=dof(i)}\ncall backf1(x,n,p,y,w,q,which,spar,dof,match,nef,\n etal,s,eta,beta,var,ifvar,tol,nit,maxit,\n qr,qraux,qrank,qpivot,effect,work(q+1),work(q+n+1),\n work(q+2*n+1),work(q+3*n+1),work(q+4*n+1))\nnpetc(7)=qrank\nreturn\nend\n\nsubroutine backf1(x,n,p,y,w,q,which,spar,dof,match,nef,\n\t\t\tetal,s,eta,beta,var,ifvar,tol,nit,maxit,\n\t\t\tqr,qraux,qrank,qpivot,effect,z,old,sqwt,sqwti,work)\nimplicit double precision(a-h,o-z)\nlogical ifvar\ninteger n,p,q,which(q),match(n,q),nef(q),nit,maxit,qrank,qpivot(p)\ndouble precision x(n,p),y(n),w(n),spar(q),dof(q),\n\t\t\tetal(n),s(n,q),eta(n),beta(p),var(n,q),tol,\n\t\t\tqr(n,p),qraux(p),effect(n),work(*)\ndouble precision z(*),old(*),dwrss,ratio\ndouble precision sqwt(n),sqwti(n)\nlogical anyzwt\ndouble precision deltaf, normf,onedm7\ninteger job,info\nonedm7=1d-7\njob=1101;info=1\nif(q==0)maxit=1\nratio=1d0\n# fix up sqy's for weighted problems.\nanyzwt=.false.\ndo i=1,n{\n\tif(w(i)>0d0){\n\t\tsqwt(i)=dsqrt(w(i))\n\t\tsqwti(i)=1d0/sqwt(i)\n\t}\n\telse{\n\t\tsqwt(i)=0d0\n\t\tsqwti(i)=0d0\n\t\tanyzwt=.true.\n\t\t}\n\t}\n# if qrank > 0 then qr etc contain the qr decomposition\n# else bakfit computes it. \nif(qrank==0){\n\tdo i=1,n{\n\t\tdo j=1,p{\n\t\t\tqr(i,j)=x(i,j)*sqwt(i)\n\t\t\t}\n\t\t}\n\tdo j=1,p{qpivot(j)=j}\n\tcall dqrdca(qr,n,n,p,qraux,qpivot,work,qrank,onedm7)\n\t}\ndo i=1,n{\n\teta(i)=0d0\n\tfor(j=1;j<=q;j=j+1){\n\t\teta(i)=eta(i)+s(i,j)\n\t\t}\n\t}\nnit=0\nwhile ((ratio > tol )&(nit < maxit)){\n\t# first the linear fit\n\tdeltaf=0d0\n\tnit=nit+1\n\tdo i=1,n{\n\t\tz(i)=(y(i)-eta(i))*sqwt(i)\n\t\told(i)=etal(i)\n\t}\n#\tcall dqrsl1(qr,dq,qraux,qrank,sqz,one,work(1),etal,two,three)\n#job=1101 -- computes fits, effects and beta\n\tcall dqrsl(qr,n,n,qrank,qraux,z,work(1),effect(1),beta,\n\t\twork(1),etal,job,info)\n\n# now unsqrt the fits\n#Note: we dont have to fix up the zero weights till the end, since their fits\n#are always immaterial to the computation\n\tdo i=1,n{\n\t\tetal(i)=etal(i)*sqwti(i)\n\t\t}\n\t# now a single non-linear backfitting loop \n\tfor(k=1;k<=q;k=k+1){\n\t\tj=which(k)\n\t\tdo i=1,n{\n\t\t\told(i)=s(i,k)\n\t\t\tz(i)=y(i)-etal(i)-eta(i)+old(i)\n\t\t}\n # this uses spar to set smoothing after iteration 1\n if(nit>1){dof(k)=0d0}\n\t\tcall splsm(x(1,j),z,w,n,match(1,k),nef(k),spar(k),\n\t\t\tdof(k),s(1,k),s0,var(1,k),ifvar,work)\n\t\tdo i=1,n{\n\t\t\teta(i)=eta(i)+s(i,k)-old(i)\n\t\t\tetal(i)=etal(i)+s0\n\t\t\t}\n\t\tdeltaf=deltaf+dwrss(n,old,s(1,k),w)\n\t\t}\n\tnormf=0d0\n\tdo i=1,n{\n\t\tnormf=normf+w(i)*eta(i)*eta(i)\n\t\t}\n\tif(normf>0d0){\n\t\tratio=dsqrt(deltaf/normf)\n\t\t}\n\t else {ratio = 0d0}\n# call DBLEPR(\"ratio\",-1,ratio,1)\n\t}\n#now package up the results\ndo j=1,p {work(j)=beta(j)}\ndo j=1,p {beta(qpivot(j))=work(j)}\nif(anyzwt){\n\tdo i=1,n {\n\t\tif(w(i) <= 0d0){\n\t\t\tetal(i)=0d0\n\t\t\tdo j=1,p{\n\t\t\t\tetal(i)=etal(i)+beta(j)*x(i,j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\t\ndo i=1,n\n\teta(i)=eta(i)+etal(i)\n\t\ndo j=1,q {\n\tcall unpck(n,nef(j),match(1,j),var(1,j),old)\n\tdo i=1,n {var(i,j)=old(i)}\n\t}\n\nreturn\nend\n", "meta": {"hexsha": "d6a0e91f0905fe7cea797b5cbb7eef34c2992091", "size": 7009, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/backfit.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/backfit.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/backfit.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 29.6991525424, "max_line_length": 77, "alphanum_fraction": 0.6752746469, "num_tokens": 2528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45340787241775515}} {"text": "##############\n# SAGP Model #\n##############\n\nmessage('sagp.R module loaded!\\n')\n\n# sagp\n# Y observations, n*1 vector.\n# X observed locations, n*d matrix (only d=1 for now). \n# pinfo list of prior information, used for specifying the hyper-parameters.\n# minfo list of MCMC information. number of MCMC steps, burn-in, etc.\n# tinfo list of partition design that defines the domains of the components and the \n# structure of the layers. \n# E.g., 3 layers, 7 components in bipartite component design (1 comp in 1st layer, 2 comp in 2nd layer, 4 comp in 3rd layer) \n# is represented by:\n# tinfo = list(data.frame(loc=c(0.5),\n# rad=c(0.5)),\n# data.frame(loc=c(0.25,0.75),\n# rad=c(rep(0.25,2))),\n# data.frame(loc=c(0.125,.375,.625,0.875),\n# rad=c(rep(0.125,4))))\n# Xnew is the locations over which we want to conduct our predictions.\n# sampleEta/sampleRho are booleans, should eta/rho be sampled in MCMC algorithm.\n# storePredX boolean, should the predictions at the observed locatios be stored? If X large, \n# should be set to FALSE and only predictions at Xnew are stored.\nsagp<-function(Y,X,pinfo,minfo,tinfo,Xnew=X,sampleEta=T,sampleRho=F,storePredX=T)\n{\n #Seed, for reproducibility\n set.seed(minfo$seed)\n \n #Transform Y to have mean = 0 and sd = 1\n meanY <- mean(Y)\n sdY <- sd(Y)\n Y <- (Y-meanY)/sdY\n #At the end of the code, samples of Y are transformed back to original scale\n \n #overall number of observations in the sample.\n n =nrow(X)\n if(n!=length(Y))stop('sagpfun::sagp @ the length of X and Y shall match.')\n #overall number of new locations to be predicted.\n nNew = nrow(Xnew)\n #number of additive components - defined by the list with tree partition structure\n #N=length(unlist(tinfo))/2\n #number of pseudo inputs - if equal for all components\n m=pinfo$m\n #number of layers\n L=length(tinfo)\n #dimension of X\n D=ncol(X)\n \n #number of samples to store and return in the result list\n Nmcmc = minfo$Nmcmc \n #number of burn-in iterations\n burnIn = minfo$burnIn \n #total number of iterations to run\n Nsamples = Nmcmc+burnIn\n \n #Identify the locations (X and Xnew) corresponding to each component, for each layer\n # indexCompX is a list of L elements. For each layer l, indexCompX[[l]] is a vector with length n.\n # For each element X[i] in X[1],...,X[n], indexCompX[[l]][i] is the index of the component in the l-th layer to which X[i] belongs.\n # indexCompNew is a list of L elements. For each layer l, indexCompX[[l]] is a vector with length nNew.\n # For each element X[i] in X[1],...,X[nNew], indexCompX[[l]][i] is the index of the component in the l-th layer to which X[i] belongs.\n # layers is a data.frame that links layers and components\n # e.g. layer=data.frame(comp=c(1,2,3),layer=c(1,2,2)) means the component 1 is in the 1st layer while the component 2,3 are in the 2nd layer.\n # It is used throughtout the code to know which is the layer of each component: layers$layer[layers$comp==j] is the layer of component j.\n indexCompX=vector(\"list\",L)\n indexCompNew=vector(\"list\",L)\n layers <- NULL\n # m_l is a vector of length N=N_1+N_2+...+N_L recording how many PIs should there be in each componet, or the l-th component to be more precise.\n m_comp <- c()\n #Initialize the layers dataframe. numCompTot is the iterator that records the loop;\n numCompTot <- 0\n for(l in 1:L) {\n #The outer loop loops through 1,2,...,L layer.\n \n #tinfo_layer is a data frame consisting of N_l*2 elements, \n # the number of rows N_l means the number of components in the l-th layer\n # the number of PIs in each component m are determined before.\n # the first column is recording the center of each component.\n # the second column is recording the radius of each component.\n tinfo_layer <- tinfo[[l]]\n indexCompX[[l]] <- rep(NA, n)\n indexCompNew[[l]] <- rep(NA, nNew)\n #N_l is the number of components in the l-th layer.\n N_l <- nrow(tinfo_layer$loc)\n for(j_l in 1:N_l) {\n #The inner loop loops through different components j_l=1,2,...,nrow(tinfo_layer) in each layer/ the l-th layer.\n \n #loc_j_l is the 'center' of the j_l component domain\n #rad_j_l is the 'radius' of the j_l component domain.\n loc_j_l <- tinfo_layer$loc[j_l,] \n rad_j_l <- tinfo_layer$rad[j_l,]\n \n ids_j_l <- ids_X_comp(X,loc=loc_j_l,rad=rad_j_l)\n cat('Initialize...Layer',l,'Component',j_l,'/',N_l,'\\n');message('loc=',loc_j_l,' rad=',rad_j_l,'\\n')\n #Check:are there points in this component that have not been already assigned to other components?\n #Need to check that the points are not already assigned because points could be on the border between\n #two components and could be assigned to both.\n idToReplace <- ids_j_l[is.na(indexCompX[[l]][ids_j_l])]\n #If yes: include it. Otherwise: do not increase the counter and do not include the component.\n if(length(idToReplace) > 0) {\n numCompTot <- numCompTot + 1\n \n indexCompX[[l]][idToReplace] <- numCompTot\n \n ids_new_j_l <- ids_X_comp(Xnew,loc=loc_j_l,rad=rad_j_l)\n indexCompNew[[l]][ids_new_j_l] <- numCompTot\n \n layers <- rbind(layers, data.frame(layer=l,comp=numCompTot))\n \n # Assign different m_comp (number of PIs) in this case we use the same number of PIs in each component.\n #m_comp <- c(m_comp,m-4*floor(log(numCompTot,base=sqrt(2))))\n # or set all m_comp to be the same\n m_comp<-c(m_comp,m)\n } \n \n \n }\n }\n #Note: numCompTot is the number of temporary real components, where I have at least one data point.\n \n #cat(m_comp)\n m_max <- max(m_comp)\n m_compActual<-m_comp\n if(m_max<=0)stop('sagpfuns::sagp @ the maximal number of PIs in components must be greater than 0.')\n \n #\"Deactivate\" components corresponding to areas where there are not enough data points.\n # Loop from last component (lowest layer, local) to first (higher layer, global).\n # For each component j, look how many components are nested in j and compute necessary number of PIs.\n # If number of data points is not sufficient, deactivate the most local components nested in j (lowest layer)\n # and check if there are enough data points. Iterate, removing one layer of components each time. \n for(j in numCompTot:1) {\n layer_j <- layers$layer[layers$comp==j] #Layer of component j\n ids_layer_j <- (indexCompX[[layer_j]] %in% j) #ids of points in comp j\n nestedComp <- list() #list where store the nested components\n layers_below_j <- 0 #counter of nested layers\n for(l in layer_j:L) {\n #Which components are nested in j in layer l? stored in nestedComp_l\n compOfNestedPoints <- indexCompX[[l]][ids_layer_j] \n compOfNestedPoints_noNA <- compOfNestedPoints[!is.na(compOfNestedPoints)]\n nestedComp_l <- sort(unique(compOfNestedPoints_noNA))\n #If there is one component at layer l: store it in list nestedComp.\n if(length(nestedComp_l)>0) {\n layers_below_j <- layers_below_j + 1\n nestedComp[[layers_below_j]] <- nestedComp_l \n } else {\n break\n }\n } \n #Given all the components nested in j, how many PIs do we need?\n req_m <- length(unlist(nestedComp)) * m\n #How many data points are available in component j?\n numPointsComp <- sum(ids_layer_j)\n #If the component does not contain enough points for its PI and the PI of the nested components:\n if(numPointsComp=req_m) {\n break\n }\n }\n \n }\n }\n \n #Rename remaining components from 1 to the number of remaining components and match the number of PIs\n #assigned to the \"old\" components to the \"new\" components.\n #Assign \"old\" labels to comp_old and \"new\" labels to comp.\n layers$comp_old <- layers$comp \n layers$comp <- 1:nrow(layers)\n #Same for m_comp\n m_comp_old <- m_comp\n m_comp <- rep(NA,nrow(layers))\n #Loop on the \"new\" labels of the components\n for(j in layers$comp) {\n layer_j <- layers$layer[layers$comp==j]\n indexCompX[[layer_j]][indexCompX[[layer_j]] %in% layers$comp_old[layers$comp==j]] <- j\n indexCompNew[[layer_j]][indexCompNew[[layer_j]] %in% layers$comp_old[layers$comp==j]] <- j\n m_comp[j] <- m_comp_old[layers$comp_old[layers$comp==j]]\n }\n #Remove \"old\" labels\n layers$comp_old <- NULL\n m_compActual<-m_comp\n \n #If a layer does not have any components left, remove layer\n for(l in L:1) {\n if(all(is.na(indexCompX[[l]]))) {\n indexCompX <- indexCompX[1:(l-1)]\n indexCompNew <- indexCompNew[1:(l-1)]\n }\n }\n \n #Rename objects with correct number of components:\n N <- nrow(layers)\n L <- length(indexCompX)\n \n \n #Define prior on rhos and eta using the correct number of components and layers\n #Same priors for all the dimensions\n pinfo$rho=list() # one rho prior per layer, list of values defined below\n pinfo$eta=list() # one eta prior per layer, list of values defined below\n #Fixed vector of rhos\n fixedRhos <- 10^(seq(pinfo$logRhoFirstLayer, pinfo$logRhoLastLayer,length = L))\n for(l in 1:L) {\n #rho: fixed values, equispaced in the log_10-scale between 10^-1 and 10^-50\n pinfo$rho[[l]] <- fixedRhos[l]\n #eta: gamma prior with mean 1/ ((1-r) * r^(l-1)) in layer l\n #pinfo$eta[[l]] <- list(a=1, b = (1-pinfo$r) * (pinfo$r^(l-1)))\n pinfo$eta[[l]] <- list(a=50, b = 50*(1-pinfo$r) * (pinfo$r^(l-1)))\n }\n \n #Rhos\n #Initialize array to store rho samples, each row stores one MCMC sample for rho.\n rho=array(NA,dim=c(Nsamples,N,D))\n #First value for each component: sampled or set to fixed value \n for(j in 1:N) {\n for(d in 1:D) {\n layer_j <- layers$layer[layers$comp==j]\n if(sampleRho) {\n rho[1,j,d]=rbeta(1,pinfo$rho[[layer_j]]$alpha, pinfo$rho[[layer_j]]$beta) \n } else {\n rho[1,j,d]=pinfo$rho[[layer_j]]\n }\n }\n }\n #Semiwidth of MH proposal for rho (same for all component and for each dimension)\n semiWidthRho=matrix(minfo$semiWidthRho,nrow=N,ncol=D)\n \n #Etas\n #Initialize matrix to store eta samples, each row stores one MCMC sample for eta.\n eta=matrix(NA,nrow=Nsamples,ncol=N)\n #print(pinfo$eta)\n #First value for each component: sampled\n for(j in 1:N) {\n layer_j <- layers$layer[layers$comp==j]\n #if(sampleEta) {\n eta[1,j]=rgamma(1,pinfo$eta[[layer_j]]$a, pinfo$eta[[layer_j]]$b) \n #}\n }\n #Semiwidth of MH proposal for eta(same for all component)\n semiWidthEta=rep(minfo$semiWidthEta,N)\n \n #lambda - reciprocal of overall Gaussian noise variance\n lambda=rep(NA,Nsamples)\n lambda[1]=rgamma(1,pinfo$a,pinfo$b)\n \n #D_mcmc is a matrix that stores the last set of residuals for each component, each column stores residuals for each component.\n D_mcmc=matrix(0,nrow=n,ncol=N)\n for(j in 1:N){\n D_mcmc[,j]=Y\n }\n \n #xBar/fBar are lists storing the samples of pseudo-inputs/targets (for *ALL* samples, also burn-in iterations).\n xBar=vector(\"list\",Nsamples)\n fBar=vector(\"list\",Nsamples)\n for(i in 1:Nsamples){\n #Initialize the xBar to be zero vectors.\n #Each term in xBar is a matrix representing the xBars. Each column of the matrix is a vector for xBar in an additive component.\n xBar[[i]]=array(0,dim=c(m_max,N,D))\n #Initializes the fBar to be zeros.\n #Each term in xBar is a matrix representing the fBars. Each column of the matrix is a vector for fBar in an additive component.\n fBar[[i]]=matrix(0,nrow=m_max,ncol=N)\n \n }\n complete_vec<-function(vec,len){\n ret<-c(vec,rep(NA,len-length(vec)))\n return(ret)\n }\n complete_mat<-function(mat,len){\n ret<-rbind(mat,matrix(NA,nrow=(len-nrow(mat)),ncol=ncol(mat)))\n return(ret)\n }\n #Sample first xBar/fBar we must complete the vector to store them in a mtrix form if m_comp differ.\n for(j in 1:N) {\n idSampleX <- sample.int(n,m_comp[j])\n xBar[[1]][,j,] <- complete_mat(matrix(X[idSampleX,],ncol=D),m_max)\n fBar[[1]][,j] <- complete_vec(mvtnorm::rmvnorm(1,mean=rep(0,m_comp[j]),sigma=diag(1,m_comp[j]) ),m_max)\n }\n \n #Matrices storing the means of each component in last MCMC iteration (at observed and new locations). \n #Cannot initialize as non-0.\n mu.component.temp=matrix(0,nrow=n,ncol=N)\n mu.new.component.temp=matrix(0,nrow=nNew,ncol=N)\n \n #Lists to store samples of the means of each component at each MCMC iteration - only after burnin to reduce memory allocation.\n mu.component=vector(\"list\",Nmcmc)\n mu.new.component=vector(\"list\",Nmcmc)\n \n #Lambda_diag is a list with N components, Lambda_diag[[j]] is the diagonal of Lambda_j (diagonal matrices)\n Lambda_diag=vector(\"list\",N)\n for(j in 1:N) {\n layer_j <- layers$layer[layers$comp==j]\n #The number of elements of Lambda_diag[[j]] is the number of data points X belonging to component j\n Lambda_diag[[j]] <- rep(1, sum(indexCompX[[layer_j]] %in% j))\n }\n \n #Vector of in-sample and out-sample means (only last iteration)\n mu.temp = matrix(0,nrow=n,ncol=1)\n mu.new.temp = matrix(0,nrow=nNew,ncol=1)\n \n #Stored in-sample and out-sample means - only stored after burn-in to reduce memory allocation\n # Means at observed locations are stored only if storePredX==T\n if(storePredX==T) {\n mu=matrix(NA,nrow=n,ncol=Nmcmc)\n mu[,1]=mu.temp\n } else {\n mu <- NULL\n }\n mu.new=matrix(NA,nrow=nNew,ncol=Nmcmc)\n mu.new[,1]=mu.new.temp\n \n #Stored in-sample and out-sample predictions - only stored after burn-in to reduce memory allocation\n # Prediction at observed locations are stored only if storePredX==T\n # No need to initialize them\n if(storePredX==T) {\n Yhat=matrix(NA,nrow=n,ncol=Nmcmc)\n } else {\n Yhat <- NULL\n }\n Yhat.new=matrix(NA,nrow=nNew,ncol=Nmcmc)\n \n #Acceptance rates of MH samples\n acceptCountRhos <- matrix(0,nrow=N,ncol=D)\n sampledRhos <- matrix(0,nrow=N,ncol=D)\n acceptCountEtas <- rep(0,N)\n sampledEtas <- rep(0,N)\n \n #Say some stuff\n cat(\"Sparse Additive Gaussian Process (SAGP) Model\\n\")\n cat(\"Number of observations: \",n,\"\\n\")\n cat(\"Number of predictive locations: \",nrow(Xnew),\"\\n\")\n \n cat(\"Number of layers: \",L,\"\\n\")\n cat(\"Number of additive components: \",N,\"\\n\")\n cat(\"Number of inducing variables measure at pseudo-inputs per component: \",m,\"\\n\")\n cat(\"\\n\")\n cat(\"Running MCMC for \",Nsamples,\" iterations (burn-in:\",burnIn,\", saved:\", Nmcmc, \")\\n\")\n \n pb <- txtProgressBar(min=2,max=Nsamples,style=3)\n # Main MCMC loop\n for(i in 2:Nsamples) {\n \n setTxtProgressBar(pb, i)\n \n #Initialize i-th step to (i-1)-th step for all the sampled parameters - so we don't need to worry about i or i-1\n xBar[[i]] <- xBar[[i-1]]\n fBar[[i]] <- fBar[[i-1]] \n rho[i,,] <- rho[i-1,,]\n eta[i,] <- eta[i-1,]\n lambda[i] <- lambda[i-1]\n \n # BOTTOM-UP\n #Arrange the pseudo-inputs for the current iterations of the MCMC loop\n # Pseudo-inputs are assigned from the last (finest) to the first (roughest) layer, to make sure \n # that there are enough pseudo-inputs in each component.\n # Pseudo-inputs are assigned to each component *WITHOUT* repetition.\n Xavail <- rep(T, n) #Available X (all at beginning)\n listIndexEligX <- list() #Store eligible X for each component\n #From last to first component:\n for(j in N:1) { \n layer_j <- layers$layer[layers$comp==j]\n #Eligible X: which are X that happen to fall in layer_j layer.\n #Available X: which are X that are not used in all previous components.\n listIndexEligX[[j]] <- which(indexCompX[[layer_j]]==j)\n #Eligible AND available X: \n indexesEligAndAvailX <- which(indexCompX[[layer_j]]==j & Xavail) \n #Sample from eligible AND available X:\n indexesSampledX <- sample(indexesEligAndAvailX, m_comp[j])\n #Sampled X are not available anymore\n Xavail[indexesSampledX] <- F\n #Store sampled xBar\n #xBar[[i]][,j]<-X[indexesSampledX]\n xBar[[i]][,j,]<-complete_mat(matrix(X[indexesSampledX,],ncol=D),m_max)\n } \n \n # TOP-DOWN (commented)\n # #For each component, Gibbs sampler\n # Xavail <- rep(T, n) #Available X (all at beginning) for xBar sampling\n\n for(j in 1:N) {\n \n # Component j corresponds to layer layer_j\n layer_j <- layers$layer[layers$comp==j]\n \n ########################################\n # Sampling xBar(START) #\n \n # TOP-DOWN (commented)\n # #Alternative sampling scheme\n # #Arrange the pseudo-inputs for the current iterations of the MCMC loop\n # # Pseudo-inputs are assigned to each component *WITHOUT* repetition.\n # \n # listIndexEligX <- list() #Store eligible X for each component\n # #Eligible X: which are X that happen to fall in layer_j layer.\n # #Available X: which are X that are not used in all previous components.\n # listIndexEligX[[j]] <- which(indexCompX[[layer_j]]==j)\n # #Eligible AND available X: \n # indexesEligAndAvailX <- which(indexCompX[[layer_j]]==j & Xavail) \n # #Sample from eligible AND available X:\n # if(length(indexesEligAndAvailX) \n # LambdaPerturbedInv %*% Ktrainm = \n # [ diag(diaLambdaPerturbedInv) * Ktrainm[,1] | diag(diaLambdaPerturbedInv) * Ktrainm[,m] | ... | diag(diaLambdaPerturbedInv) * Ktrainm[,m] ],\n # where diag(diaLambdaPerturbedInv) %*% Ktrainm[,k] is the elementwise product of the k-t column of Ktrainm times diag(diaLambdaPerturbedInv).\n # This is computed in R with Ktrainm * LambdaPerturbedInv_diag \n LambdaPerturbedInv_Ktrainm <- Ktrainm * LambdaPerturbedInv_diag\n Q <- Kmm + t(Ktrainm) %*% LambdaPerturbedInv_Ktrainm\n \n Qinv = chol2inv(chol(Q,pivot=F))\n #M_j is just auxillary matrix to reduce computation.\n M_j = Kmm %*% Qinv %*% t(Ktrainm)\n \n #Compute Mean_j \n # Definition: Mean_j = M_j%*% LambdaPerturbedInv %*% D_mcmc_train\n # As for the definition of Q, take advantage of diagonal structure of LambdaPerturbedInv.\n # M_j %*% LambdaPerturbedInv = elementwise product of rows of M_j times LambdaPerturbedInv_diag = t(t(M_j) * LambdaPerturbedInv_diag)\n Mean_j = t(t(M_j) * LambdaPerturbedInv_diag) %*% D_mcmc_train\n \n M_j = Kmm %*% Qinv %*% t(Kmm)\n #Symmetrizer to avoid numerical issue.\n Var_j = (1/2) * (M_j+t(M_j))\n \n #Sample fBar\n fBar[[i]][,j] = complete_vec(mvtnorm::rmvnorm(1,mean=Mean_j,sigma=Var_j),m_max)\n #This fBar_noNA fetches the fBar, whose empty entries are NA, into a shorter vector by dropping the NAs.\n #Recall that NAs comes from the complete_vec function that allows us to record the fBar in a matrix form.\n fBar_noNA<-fBar[[i]][,j][!is.na(fBar[[i]][,j])]\n \n #Define prediction of component j with STEP-TAPERING: mean is 0 outside the domain of the component j.\n # Observed locations: avoid computing Knm - mean !=0 only on Xtrain\n mu.component.temp[,j] <- 0\n mu.component.temp[indexesEligX,j] = (Ktrainm %*% KmmInv %*% fBar_noNA) \n # New locations: force mean to be 0 outside domain\n mu.new.component.temp[,j] = (Knewm %*% KmmInv %*% fBar_noNA) * (indexCompNew[[layer_j]] %in% j)\n \n # \n # Sampling fBar(END) #\n ########################################\n\n \n \n ########################################\n # Sampling rho(START) #\n # MH step\n if(sampleRho) {\n #This commented part is not updated to multidimensional case\n # alpha = pinfo$rho[[layer_j]]$alpha\n # beta = pinfo$rho[[layer_j]]$beta\n # current_rho = rho[i,j]\n # \n # proposal_rho <- runif(1, min = (current_rho-semiWidthRho[j]), max = (current_rho+semiWidthRho[j]))\n # \n # #If acceptable proposal: compute acceptance prob. Otherwise, acceptance prob = 0.\n # if(proposal_rho>0 && proposal_rho<1) {\n # \n # result_logLikProp <- logLikelihood(rho_j=proposal_rho,\n # Y=Y_train,X=X_train,xBar_j=xBar_noNA,fBar_j=fBar_noNA,eta_j=eta[i,j],lambda=lambda[i],\n # mu.component.temp = matrix(mu.component.temp[indexesEligX,],ncol=N),j_index=j)\n # result_logLikCurr <- logLikelihood(rho_j=current_rho,\n # Y=Y_train,X=X_train,xBar_j=xBar_noNA,fBar_j=fBar_noNA,eta_j=eta[i,j],lambda=lambda[i],\n # mu.component.temp = matrix(mu.component.temp[indexesEligX,],ncol=N),j_index=j)\n # \n # logPriorProp <- dbeta(proposal_rho, alpha, beta, log = T)\n # logPriorCurr <- dbeta(current_rho, alpha, beta,log = T)\n # \n # logPriorProp_fBar_j <- mvtnorm::dmvnorm(fBar_noNA,mean=rep(0,m_comp[j]),sigma=result_logLikProp$Kmm, log = T)\n # logPriorCurr_fBar_j <- mvtnorm::dmvnorm(fBar_noNA,mean=rep(0,m_comp[j]),sigma=result_logLikCurr$Kmm, log = T)\n # \n # if(logPriorProp_fBar_j==-Inf && logPriorCurr_fBar_j==-Inf) {\n # logPriorProp_fBar_j <- 0\n # logPriorCurr_fBar_j <- 0\n # }\n # \n # acceptanceProb <- min(1,exp(result_logLikProp$logLik + logPriorProp + logPriorProp_fBar_j - result_logLikCurr$logLik - logPriorCurr - logPriorCurr_fBar_j))\n # } else {\n # acceptanceProb <- 0\n # }\n # \n # #Number of rhos sampled\n # sampledRhos[j]<-sampledRhos[j]+1\n # \n # #Accept or reject with prob acceptanceProb\n # if(runif(1) < acceptanceProb){\n # \n # #Accept! Count of accepted value + 1 \n # acceptCountRhos[j]<-acceptCountRhos[j]+1\n # rho[i,j]<-proposal_rho\n # \n # #If I update rho_j, I also need to update the mean \n # Knewm<-makeKernel(X1=Xnew,\n # X2=xBar_noNA,\n # kinfo=list(eta=eta[i,j],rho=rho[i,j]))\n # \n # #Define prediction of component j with STEP-TAPERING: mean is 0 outside the domain of the component j.\n # mu.component.temp[,j] = 0 \n # mu.component.temp[indexesEligX,j] = result_logLikProp$mu.component.temp.new[,j]\n # mu.new.component.temp[,j] = (Knewm %*% result_logLikProp$KmmInv %*% fBar_noNA) * (indexCompNew[[layer_j]] %in% j)\n # \n # }else{\n # #Reject! \n # rho[i,j]<- current_rho\n # }\n # \n # #Adapt semiWidthRho[j]:\n # # - every burnIn/20 iterations.\n # # - leave last 5% of burnin iterations without adapting semiwidth of proposal.\n # if( i %% (burnIn/20) == 0 && i < (burnIn*19/20+1) )\n # {\n # rate_rho = acceptCountRhos[j]/sampledRhos[j]\n # if(rate_rho>.49 || rate_rho<.39) {\n # semiWidthRho[j]=semiWidthRho[j]*rate_rho/.44\n # }\n # acceptCountRhos[j] <- 0\n # sampledRhos[j] <- 0\n # }\n \n }else{\n \n #If rho is not sampled, set it to fixed value\n rho[i,j,] <- rep(pinfo$rho[[layer_j]], D)\n \n } \n \n # Sampling rho(END) #\n ########################################\n \n \n ########################################\n # Sampling eta(START) #\n # MH step\n if(sampleEta) {\n a_eta = pinfo$eta[[layer_j]]$a\n b_eta = pinfo$eta[[layer_j]]$b\n current_eta = eta[i,j]\n\n proposal_eta <- runif(1, min = (current_eta-semiWidthEta[j]), max = (current_eta+semiWidthEta[j]))\n\n #If acceptable proposal: compute acceptance prob. Otherwise, acceptance prob = 0.\n if(proposal_eta>0) {\n \n result_logLikProp <- logLikelihood(eta_j = proposal_eta,\n Y=Y_train,X=X_train,xBar_j=xBar_noNA,fBar_j=fBar_noNA,rho_j=rho[i,j,],lambda=lambda[i],\n mu.component.temp = matrix(mu.component.temp[indexesEligX,],ncol=N),j_index=j)\n result_logLikCurr <- logLikelihood(eta_j = current_eta,\n Y=Y_train,X=X_train,xBar_j=xBar_noNA,fBar_j=fBar_noNA,rho_j=rho[i,j,],lambda=lambda[i],\n mu.component.temp = matrix(mu.component.temp[indexesEligX,],ncol=N),j_index=j)\n\n logPriorProp <- dgamma(proposal_eta, a_eta, b_eta,log = T)\n logPriorCurr <- dgamma(current_eta , a_eta, b_eta,log = T)\n\n logPriorProp_fBar_j <- mvtnorm::dmvnorm(fBar_noNA,mean=rep(0,m_comp[j]),sigma=result_logLikProp$Kmm, log = T)\n logPriorCurr_fBar_j <- mvtnorm::dmvnorm(fBar_noNA,mean=rep(0,m_comp[j]),sigma=result_logLikCurr$Kmm, log = T)\n\n if(logPriorProp_fBar_j==-Inf && logPriorCurr_fBar_j==-Inf) {\n logPriorProp_fBar_j <- 0\n logPriorCurr_fBar_j <- 0\n }\n\n acceptanceProb <- min(1,exp(result_logLikProp$logLik + logPriorProp + logPriorProp_fBar_j - result_logLikCurr$logLik - logPriorCurr - logPriorCurr_fBar_j))\n } else {\n acceptanceProb <- 0\n }\n print(acceptanceProb)\n #Number of etas sampled\n sampledEtas[j]<-sampledEtas[j]+1\n \n #Accept or reject with prob acceptanceProb\n if(runif(1) < acceptanceProb){\n\n #Accept! Count of accepted value + 1 \n acceptCountEtas[j]<-acceptCountEtas[j]+1\n eta[i,j]<- proposal_eta\n\n #If I update eta_j, I need to update the mean\n Knewm<-makeKernel(X1=Xnew,\n X2=xBar_noNA,\n kinfo=list(eta=eta[i,j],rho=rho[i,j,]))\n\n #Define prediction of component j with STEP-TAPERING: mean is 0 outside the domain of the component j.\n mu.component.temp[,j] = 0 \n mu.component.temp[indexesEligX,j] = result_logLikProp$mu.component.temp.new[,j]\n mu.new.component.temp[,j] = (Knewm %*% result_logLikProp$KmmInv %*% fBar_noNA) * (indexCompNew[[layer_j]] %in% j)\n #print(Knewm)\n } else {\n #Reject!\n eta[i,j]<- current_eta\n }\n \n #Adapt semiWidthEta[j]:\n # - every burnIn/20 iterations.\n # - leave last 5% of burnin iterations without adapting semiwidth of proposal.\n if( i %% (burnIn/20) == 0 && i < (burnIn*19/20+1) ) {\n rate_eta = acceptCountEtas[j]/sampledEtas[j]\n if(rate_eta>.49 || rate_eta<.39) {\n semiWidthEta[j]=semiWidthEta[j]*rate_eta/.44\n }\n acceptCountEtas[j] <- 0\n sampledEtas[j] <- 0\n }\n \n } else {\n #Set eta to fixed value\n eta[i,j] <- 1\n } \n \n # Sampling eta(END) #\n ######################################## \n }\n \n # Save in-sample prediction of this iteration\n mu.temp <- apply(mu.component.temp ,1,sum)\n mu.new.temp <- apply(mu.new.component.temp,1,sum)\n \n ######################################## \n # Sampling lambda(START) #\n \n # Draw lambda, reciprocal of error variance, using gamma normal conjugacy.\n # D_mcmc_overall is the residual in this step of MCMC loop.\n D_mcmc_overall <- Y-mu.temp\n lambda[i] <- rgamma(1,pinfo$a+n/2,pinfo$b+0.5*t(D_mcmc_overall)%*%D_mcmc_overall)\n \n # Sampling lambda(END) #\n ######################################## \n \n #Store predictions only after burnin to save space\n if(i>burnIn) {\n \n #Store predictions at observed locations only if requested (it requires *A LOT* of space if n large)\n if(storePredX==T) {\n #Mean in observed location\n mu[,i-burnIn] <- mu.temp*sdY + meanY\n #Prediction in observed location\n Yhat[,i-burnIn] <- (mu.temp + rnorm(n,sd=sqrt(1/lambda[i])))*sdY + meanY\n #Mean of each component in observed location\n mu.component[[i-burnIn]] <- mu.component.temp*sdY\n } else {\n mu.component[[i-burnIn]] <- NULL\n }\n \n #Predictions of mean in new locations\n mu.new[,i-burnIn] <- mu.new.temp*sdY + meanY\n #Prediction in observed location\n Yhat.new[,i-burnIn] <- (mu.new.temp + rnorm(nNew,sd=sqrt(1/lambda[i])))*sdY + meanY\n #Prediction of mean of each component in new locations\n mu.new.component[[i-burnIn]]<- mu.new.component.temp*sdY\n }\n \n }\n close(pb)\n \n return(list(#data provided as input:\n Y=Y*sdY + meanY, \n X=X, \n Xnew=Xnew, \n #parameters provided as input:\n pinfo=pinfo, minfo=minfo, tinfo=tinfo,\n sampleRho=sampleRho, sampleEta=sampleEta,storePredX=storePredX,\n #MCMC samples:\n mu=mu, #mu has Nmcmc elements, only stored the samples after burn-in\n mu.component=mu.component, #mu.component has Nmcmc elements, only stored the samples after burn-in\n Yhat=Yhat, #Yhat has Nmcmc elements, only stored the samples after burn-in\n mu.new=mu.new, #mu.new has Nmcmc elements, only stored the samples after burn-in\n mu.new.component=mu.new.component, #mu.new.component has Nmcmc elements, only stored the samples after burn-in\n Yhat.new=Yhat.new, #Yhat.new has Nmcmc elements, only stored the samples after burn-in\n xBar=xBar[(burnIn+1):(burnIn+Nmcmc)],\n fBar=fBar[(burnIn+1):(burnIn+Nmcmc)], \n draw.lambda=lambda[(burnIn+1):(burnIn+Nmcmc)],\n draw.rho=rho[(burnIn+1):(burnIn+Nmcmc),,],\n draw.eta=eta[(burnIn+1):(burnIn+Nmcmc),],\n #Info of MH samples\n acceptRateRhos=acceptCountRhos/sampledRhos,\n acceptRateEtas=acceptCountEtas/sampledEtas,\n semiWidthRho=semiWidthRho,\n semiWidthEta=semiWidthEta,\n #Data frame for correspondence between layer and components--e.g., layer=data.frame(comp=c(1,2,3),layer=c(1,2,2))\n layers=layers,\n m_comp=m_comp,m_compActual=m_compActual)\n )\n}\n\n# logLikelihood\n# log-Likelihood of the model, used in MH steps to sample rhos and etas.\nlogLikelihood <- function(Y,X,xBar_j,fBar_j,rho_j,eta_j,lambda,mu.component.temp,j_index){\n \n Knm <- makeKernel(X1=X,\n X2=xBar_j,\n kinfo=list(eta=eta_j,rho=rho_j))\n Kmm <- makeKernel(X1=xBar_j,\n X2=xBar_j,\n kinfo=list(eta=eta_j,rho=rho_j))\n \n #Inversion of Kmm: same trick as before.\n sfu2 <- sum( diag(Kmm)/(dim(Kmm)[1]) )\n sfu <- sqrt(sfu2)\n snu <- sfu/1e3\n snu2 <- snu^2\n Kmm <- Kmm + snu2*diag((dim(Kmm)[1]))\n KmmInv <- chol2inv(chol(Kmm))\n \n #Update the j-th component of the mean\n mu.component.temp[,j_index] = Knm %*% KmmInv %*% fBar_j\n \n #Computation of Lambda_j: same trick as before\n diag_Knm_KmmInv_Kmn <- rep(NA,nrow(X))\n for(iDiag in 1:nrow(X)) { \n diag_Knm_KmmInv_Kmn[iDiag] <- matrix(Knm[iDiag,],ncol=(dim(Kmm)[1])) %*% KmmInv %*% matrix(Knm[iDiag,],nrow=(dim(Kmm)[1]))\n }\n Lambda_j_diag <- rep(1/eta_j,nrow(X)) - diag_Knm_KmmInv_Kmn\n \n #log-likelihood \n # We should compute this:\n # logLikelihood <- mvtnorm::dmvnorm(x=as.vector(Y), \n # mean=rowSums(mu.component.temp), \n # sigma=diag(Lambda_j_diag + 1/lambda ), log = T) \n # However, the covariance matrix is diagonal and mvtnorm::dmvnorm does not take advantage of the diagonal structure to compute its inverse.\n # The computational time was prohibitive for n~10,000. Simply replace the evaluation of the log-likelihood with the pdf of \n # multivariate normal\n \n #Vector of (Y[i] - X[i])^2\n vector_YminMeaSq <- (as.vector(Y) - rowSums(mu.component.temp))^2\n #Vector of sigma^2[i]\n vectorVariances <- (Lambda_j_diag + 1/lambda )\n #log-likelihood\n logLikelihood <- - .5 * sum(log(vectorVariances)) - 0.5 * nrow(X) * log(2 * pi) + #determinant \n - 0.5 * sum(vector_YminMeaSq/vectorVariances) #part in exponent \n \n return(list(logLik=logLikelihood,\n mu.component.temp.new=mu.component.temp,\n Kmm=Kmm,\n KmmInv=KmmInv))\n \n}\n\n\n#generateTree\n# generate a partition tree in the domain, given:\n# - domain: list of length D, each element is a vector c(Xmin,Xmax) in that dimension\n# - the number of layers L\n# - base: vector of length D, each element tells how many times the tree should partition that dimension\ngenerateTree <- function(domain, L, base=rep(2,length(domain))) {\n \n #Dimension\n D <- length(domain)\n \n tinfo <- list()\n #For each layer:\n for(l in 1:L) {\n #Compute the coordinates of the centers of the components in each dimensions\n # and store them in the list list_loc_l \n list_loc_l <- list()\n for(d in 1:D) {\n loc_temp <- seq(from = domain[[d]][1], to = domain[[d]][2], length.out = (2*base[[d]]^(l-1) + 1) )\n #Take the even components: they are the locations\n loc_d <-loc_temp[seq(from=2,to=length(loc_temp),by=2)]\n list_loc_l[[d]] <- loc_d\n }\n #The centers of the components are the D-dimensional grid based on the points in list_loc_l\n tinfo[[l]] <- list(loc = as.matrix(expand.grid(list_loc_l)))\n \n tinfo[[l]]$rad <- matrix(NA, nrow=nrow(tinfo[[l]]$loc), ncol=D)\n for(d in 1:D) {\n tinfo[[l]]$rad[,d] <- (domain[[d]][2]-domain[[d]][1])/(2*base[[d]]^(l-1))\n }\n \n } \n return(tinfo)\n}\n\n\n#ids_X_comp\n#Extract the ids of the X that belong to the component with \n#center 'loc' and radius 'rad'\nids_X_comp <- function(X,loc,rad) {\n D=ncol(X)\n ids_output <- which(rowSums(sapply(1:D, \n function(id_col) {\n abs(X[,id_col, drop = FALSE] - loc[id_col]) <= rad[id_col]\n }\n )\n ) == D)\n return(ids_output)\n}\n\n\nids_X_comp_old <- function(X,loc,rad) {\n absDiff_X_loc <- matrix(apply(X, FUN=function(x){abs(x-loc)}, 1),ncol=nrow(X))\n boolean_by_dim <- matrix(apply(absDiff_X_loc,FUN=function(x){x<=rad},2),ncol=nrow(X))\n boolean_X_comp <- apply(boolean_by_dim, FUN=all, 2)\n}\n\n", "meta": {"hexsha": "087ea0f79fd949811d16ab27cd34708dd84f7425", "size": 39883, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Core/sagpfuns.r", "max_stars_repo_name": "hrluo/SparseAdditiveGaussianProcess", "max_stars_repo_head_hexsha": "6a3a1cbdb38660d0a3629f7e0b58ae6d38863871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Core/sagpfuns.r", "max_issues_repo_name": "hrluo/SparseAdditiveGaussianProcess", "max_issues_repo_head_hexsha": "6a3a1cbdb38660d0a3629f7e0b58ae6d38863871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Core/sagpfuns.r", "max_forks_repo_name": "hrluo/SparseAdditiveGaussianProcess", "max_forks_repo_head_hexsha": "6a3a1cbdb38660d0a3629f7e0b58ae6d38863871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5122767857, "max_line_length": 167, "alphanum_fraction": 0.6139959381, "num_tokens": 11477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.45340119250153516}} {"text": "###################################################################################\n# R-script submitted as Supplementary Information to Seebens et al. (2016) No \n# saturation in the accumulation of alien species worldwide. Nature Communications ....\n#\n# The script is called by the file Rcode_Seebens-etal_InvasionModel_PropPress_MAIN.r\n# which reproduces the modelling results shown in Supplementary Fig. 5 of the article.\n#\n# This file simulates the model scenario: increase related to number of botanic gardens.\n#\n# The model implemented here describes the temporal development of the \n# accumulation of alien species on an island, which were randomly depicted\n# from an arbitrary mainland community. The probability of depicting a species\n# may change during the simulation depending on the scenario to account for increases\n# in propagule and colonisation pressures due to e.g. increases of trade volumes.\n# For further details, consult the article.\n# Five scenarios were simulated assuming different increases in the rate of \n# introduction (constant, linear or exponential increase, related to import \n# volumes or the number of founded botanic gardens).\n#\n# The code is free of use as long as the article is properly cited.\n#\n# Author of code: Hanno Seebens, Frankfurt, Germany\n# 25. August, 2016\n###################################################################################\n\n##### Defintion of objects/variables for simulation ###########################################################\n\nn_spec <- 50000 # number of species of the mainland community\nt_max <- 202000 # max simulation time\n\nn_bins <- 1000 # number of steps abundances of the mainland community are stored\n\nadd <- \"botgar\" # type of increase in propagule pressure, required for output file\n\n## Define temporal development of propagule pressure ###########################################################\n\n## calculate propagule pressure as a function of newly founded botanical gardens ###############################\n# The year of foundation of botanical gardens can be obtained from Botanic Gardens Conservation International\n# (https://www.bgci.org/). We selected the years of foundation for botanic gardens in those countries, which\n# have records of vascular plants in our first record database resulting in 2762 years of foundation:\nbotgar <- c(1971,1832,1898,1929,1988,1980,1989,1947,1924,2006,1963,1995,1997,1988,1999,1855,1952,1928,1877,1997,1956,1971,1996,1984,1964,1967,1987,1902,1901,1993,1887,1901,1949,1926,2005,1993,1981,1966,1983,1985,1970,1886,1957,1984,\n 1946,1978,1988,1965,1976,1998,1988,1941,1967,1988,1953,1818,1978,1951,1968,1955,1982,1990,1981,1991,1988,2003,1994,1965,1864,1965,1989,1992,1984,1986,1984,1970,1980,1964,1980,1958,1961,1992,1961,1928,1960,1970,1981,1968,\n 1929,1986,1988,2001,1981,1933,1898,1966,1976,1970,1816,1992,1986,1987,1985,1976,1932,1932,1970,1969,1988,1983,1969,1895,1964,1982,1974,1914,1947,1887,1954,1909,1952,1993,1987,1997,1754,1950,1973,1980,1910,1954,1983,1966,\n 1979,1960,1981,1922,1978,1980,1985,1797,1899,1985,1952,1970,1937,2011,1902,1962,1991,1986,1984,1994,1998,1991,1968,1974,1985,1998,1990,1991,1992,1997,1998,2000,2003,1961,1808,1994,1938,1978,1997,1948,1930,1967,1959,1976,\n 1993,1967,1926,1970,1942,2000,1985,1967,1998,1980,1931,2000,1924,1936,2000,1990,1950,1966,1999,1980,1970,1998,1971,1952,1972,1975,1958,1973,1916,1971,1904,1979,1968,1908,1904,1968,1999,1987,1994,1970,1970,1969,1960,1956,\n 2006,1972,1955,1951,1977,1982,1985,1983,1991,1985,1959,1989,1985,1986,1980,1964,1929,1927,1956,1985,1956,1952,1871,1981,1986,1938,1983,1934,1980,1947,1954,1929,1958,1976,1974,1976,1955,1963,1983,2010,1956,1976,1976,1962,\n 1956,2007,1959,1955,1985,1981,1915,1959,1980,1986,1982,2004,1955,1982,1979,2001,1983,1968,1960,1979,1969,1997,1988,1968,1960,1976,1967,1963,1889,1902,1968,1996,1929,1936,1922,1975,1954,1980,1901,1956,1961,1969,1931,1961,\n 1927,1963,1958,2002,1943,1923,1970,1858,1976,1936,1933,1991,1976,1942,1958,1928,1875,1960,1961,1984,2010,1958,1988,1902,1678,1985,1982,1960,1978,1924,1936,1987,1953,1993,1957,1986,1977,1689,1953,1988,1976,1947,1942,1986,\n 1992,1979,1979,1989,1899,2008,1970,1948,1983,1958,1970,1857,1903,1985,1986,1999,1987,1987,1905,1987,1990,1593,1901,1982,1965,1624,1994,1867,1995,1626,1777,1969,1986,1970,1986,1924,1988,1993,1992,1906,1932,1924,1965,1887,\n 1843,1975,1968,1912,1845,1912,1953,1936,1971,1978,1879,1912,1968,1818,1989,1936,1955,1874,1905,1979,1945,1927,1868,1948,1945,1609,1736,1970,1967,1965,1927,1593,1586,1912,1970,1669,1864,1963,1973,1928,1946,1975,1977,1803,\n 1901,1914,1975,1882,1984,1927,1950,1977,1885,1952,1903,1998,1846,1776,1910,1890,1905,1970,1965,1950,1835,1965,1947,2000,2004,2000,2007,2001,1984,1820,1963,1771,1771,1954,1928,1951,1922,1952,1961,1912,1930,1964,1978,1962,\n 1962,1960,1923,1975,1964,2019,1973,1963,1964,1965,1985,1971,1975,1918,1971,1991,1961,1986,1971,1906,1979,1948,1958,1934,1947,1976,1963,1786,1958,1963,1787,1908,1968,1934,1951,1953,1964,1973,1970,1930,1964,1967,1981,1972,\n 1980,1958,1961,1979,1978,1946,1966,1959,1980,1979,1979,1968,1972,1969,1963,1959,1817,1852,1941,1968,1931,1850,1795,1948,1968,1994,1958,1948,1930,1933,1954,1949,1971,1954,1987,1985,1972,1998,1981,1568,1979,1990,1828,1938,\n 1858,1955,1984,1984,1771,1990,1904,1545,1959,1990,1980,1967,1994,1953,1980,1966,2001,1774,1954,1807,1989,1545,1933,1985,1720,1981,1955,1979,1967,1984,1988,1961,1968,1953,1991,1964,1965,1876,1938,1964,1842,1962,1951,1983,\n 1990,1985,1955,1969,1961,1961,1984,1985,1952,1965,1930,1980,1971,1921,1976,1969,1939,1974,1976,1985,1974,1976,1971,1969,1967,1961,1950,1967,1957,1933,1958,1954,1933,1953,1924,1964,1958,1964,1911,1953,1968,1929,1958,1955,\n 1961,1945,1684,1988,1980,1979,2002,2002,1948,1990,1940,1907,1990,1938,1922,1956,1997,1958,1923,1997,1958,1781,1925,1980,1987,1987,1926,1981,1974,1982,1976,1970,1981,1986,1989,1971,1974,1982,1977,1967,1990,1979,1979,1986,\n 2002,1980,1982,1985,1978,1929,1983,1976,1979,1959,1987,1983,2005,1993,1994,1987,1993,2005,1990,1993,1970,1978,1991,1989,1980,1999,1949,2002,1976,1968,1974,1950,1997,1952,1961,1982,1863,1863,1910,1951,1927,1947,1966,1926,\n 1868,1999,1954,1948,1976,1978,1958,1986,1969,1814,1971,1991,1973,1989,2006,1912,1999,1965,1973,2007,1959,1968,1968,1977,1980,1947,1930,1925,1951,1946,1960,1963,1989,1984,1925,1924,1947,1933,1925,1974,1890,1811,1953,1986,\n 1960,1768,1878,1906,1951,2000,1970,1987,1901,1971,1991,1987,1903,1920,2000,1953,1856,1968,2018,1952,1913,1983,1991,1903,1960,1903,1960,1986,1859,1942,1967,1950,1982,1892,1965,1977,1959,1967,1927,1913,1849,1989,1996,1853,\n 1967,1970,1982,1969,2008,1957,1874,1962,1934,1958,1976,1991,1922,1921,1979,2006,1967,1965,1966,1999,1987,1969,1989,2003,1987,1976,1991,1934,1988,1918,1952,1979,2003,2000,1952,2007,1755,1994,1945,1965,1986,1567,1962,1986,\n 1950,1986,1964,1923,1860,1981,1970,1859,1968,1589,1968,1950,1925,1937,1943,1927,1946,1965,1896,1954,1945,1977,1931,1966,1906,1999,1896,1990,1902,2006,1953,1993,1993,2011,1941,1978,1968,1988,1993,1913,1919,1990,1999,1972,\n 1950,1964,2009,1949,1935,1980,2003,1898,2001,1945,2000,1877,1930,1931,1963,1930,1934,1921,1935,1928,1974,1977,1934,1965,1912,1796,1946,1963,1933,2001,1963,1988,1977,1925,1929,1829,1903,1997,1906,1996,1955,1934,1971,1971,\n 1670,1922,1817,1950,1950,1965,1948,1946,1921,1964,1673,1910,1975,1898,1997,1967,1621,1923,1972,1953,1966,1836,1951,1961,1950,1889,1978,1968,1960,1926,1856,1991,1996,1971,1986,1938,1904,1969,1970,1981,2000,1995,1986,1907,\n 1948,1960,1986,1980,1995,1968,1976,1985,1889,1963,1982,1982,1935,1970,1981,1922,1984,1991,2000,1991,1940,1892,1911,1997,1964,1984,1984,1991,1872,1992,1987,1972,1907,1891,1965,1966,1910,1900,1831,1972,1990,1975,1971,1912,\n 1934,1967,1961,1966,1870,1968,1966,1768,1958,1956,1977,1908,1890,2004,1873,1873,1933,1845,1927,1958,1929,1930,1970,2002,1977,1999,1895,1981,1938,1947,1959,1965,1983,1926,1974,1936,1997,1885,1927,1936,1962,1990,2000,1999,\n 1951,1979,1955,1976,1990,1966,1980,1932,1999,1934,1873,1965,1975,2000,1990,1999,1963,1961,1926,1972,1951,1973,1992,1991,1950,1994,1989,1993,1981,1959,1939,1961,1974,1947,1984,1985,1983,1933,1931,1984,1971,1978,1953,1983,\n 1948,1987,1965,2001,1995,1982,2000,1925,1887,1996,1973,1939,1935,1974,1939,1978,1937,1981,1964,1922,1935,1963,1929,1970,1930,1918,1930,1956,1967,1999,1974,1992,1988,1926,1978,1970,1935,1926,1925,1989,1998,2007,1964,1960,\n 1967,1974,2001,2004,1906,1978,2005,2009,1937,2006,1957,1988,1931,1983,1968,1954,1981,1971,2002,1929,1987,1989,1948,2000,1990,1985,1991,1969,1922,1996,1961,1997,1929,1952,1934,1969,1974,1953,1955,1972,1985,1993,1962,1967,\n 1946,1976,1953,1940,1922,1974,1980,1898,1936,1899,1971,1966,1959,1907,1974,1929,2000,1971,1909,1928,1988,1970,1931,1995,1917,1960,1988,1903,1934,1923,1934,1931,1884,1969,1936,1929,1950,1964,1942,1938,1900,1958,1895,1959,\n 1929,1964,1988,1904,1958,2001,2008,1962,1983,1960,1934,1947,1963,1993,1955,1970,1961,1979,1976,1897,1932,1939,1967,1979,1952,1978,1893,1925,1928,1981,1963,1978,1991,1941,1976,1926,1972,1986,1959,1984,1925,1980,1963,1888,\n 1999,1998,1959,1915,1973,1988,1961,1980,1916,1964,1937,1879,1993,1973,1903,1969,1993,1926,1964,1987,1973,1983,1832,1996,1975,1971,2002,1994,1972,1934,2003,1911,1912,1907,1958,1906,1999,1878,1936,1949,1903,1998,1998,1972,\n 1985,1859,1965,1975,1989,1938,1976,1934,1977,1974,1994,1927,1929,1969,1977,1932,1997,1945,1964,1952,1964,1958,1985,2002,1999,1967,1937,1989,1986,1997,2001,1980,1961,2000,1957,1960,1972,1931,1950,1990,1926,2001,1816,1927,\n 1916,1990,1852,1875,1975,1983,1958,1898,1972,1969,1955,1915,1901,1962,1930,1976,1908,1958,1979,1993,1972,1973,1956,1991,1967,1950,1962,1947)\n\nbotgar_ts <- as.data.frame(table(botgar),stringsAsFactors=F) # get annual time series of foundations\ncolnames(botgar_ts) <- c(\"Year\",\"BotGar\") # set column names\nbotgar_ts$Year <- as.numeric(botgar_ts$Year) # redefine column types\nbotgar_ts <- subset(botgar_ts,Year<2002) # consider only foundation during the time period of the first record database\nbotgar_ts[,2] <- cumsum(botgar_ts[,2]) # calculate cumulative sum of the annual number of foundations\n\nraw <- cbind(1800:2000,NA) # create dummy file for the full time period to identify gaps in time series of botanic garden foundations\ncolnames(raw) <- c(\"Year\",\"Dummy\")\nbotgar_fullts <-merge(botgar_ts,raw,by=c(\"Year\"),all=T) \nbotgar_fullts[which(is.na(botgar_fullts[,2])),2] <- approx(botgar_fullts[,2],xout=which(is.na(botgar_fullts[,2])),method=\"constant\")$y # fill gaps with constant values\nbotgar_fullts <- subset(botgar_fullts,Year>1799) # cut entries before start of simulation (note that these early botanic gardens are still considered in the cumulative number of foundations)\n\nbotgar_interpol <- approx(botgar_fullts[,1],botgar_fullts[,2],n=t_max) # interpolate annual values to achieve a continuous development of increasing propagule pressure according to the simulation time steps\ntimeaxis <- botgar_interpol[[1]] # identify time axis (for plotting)\n\n# rescale accumulation of botanic gardens to get a propagule pressure comparable to other scenario runs\nm_bg <- botgar_interpol[[2]]\nm_bg <- m_bg/mean(m_bg)*0.05\nm <- m_bg\n###############################################################################################################\n\n\n# define basic characteristics of community size #############################################################\nmlog <- seq(-3,1,length.out=5) # size of communities (defined as mean of log-normal distribution) for different model scenarios\nsdlog <- 300 # standard deviation of log-normal distribution, constant\nrun_tot <- length(mlog)*length(sdlog) # number of model scenarios\n\n\n######### SIMULATION #########################################################################################\n\nisland <- matrix(0,nr=t_max,nc=run_tot+1) # results file\nisland[,1] <- 1:t_max # include time axis in first column \nall_main <- matrix(0,nr=n_bins,nc=run_tot) # store communities (abundances and species)\nx <- 0 # counter\nfor (j in 1:length(mlog)){# loop through model scenarios depending on the number of defined means\n for (i in 1:length(sdlog)){# loop through model scenarios depending on the number of defined standard deviations\n x <- x + 1 # increase counter\n \n ## define mainland community ###############################################\n specabund <- dlnorm((seq(0.1,2,length.out=n_bins)),meanlog=mlog[j],sdlog=1)*10000\n axis1 <- seq(10,10000,length.out=n_bins) # steps of storing individuals per species (for plotting)\n specabund <- ceiling(specabund) # avoid decimals in abundances\n specabund <- round(specabund/sum(specabund)*n_spec) # rescale numbers\n \n tot_spec <- sum(specabund) # number of species\n abundances <- rep(axis1,round(specabund)) # set abundances\n tot_abund <- sum(abundances) # number of individuals\n all_main[,x] <- specabund # store community\n print(tot_spec)\n print(tot_abund)\n \n #### simulation ############################################################################\n for (t in 1:t_max){ # loop through time steps\n \n ## select individual from mainland community and transfer it on the island\n if (runif(1) escala invariante al usar quantiles\n# # tube <- baseboot(data$test, sqrt(punctual), sqrt(mat))\n# # tube[tube < 0] <- 0\n# # tube <- tube^2\n# \n# return(list(punctual = punctual, bunch = mat, tube = tube)) \n# }\n# \n# \n# tube_KDEsm <- function(data) { # only at 90% (hard coded)\n# fit <- sm::sm.density(data$train, h = bw.ucv(data$train), display = \"none\",\n# eval.grid = TRUE, eval.points = data$test)\n# return(list(punctual = fit$estimate, \n# tube = rbind(fit$lower, fit$upper))) \n# }\n# \n# \n# tube_wass <- function(data, alpha = 0.1, nbr = 50, plot = FALSE, ...) {\n# xb <- data$train\n# n <- length(data$train)\n# \n# hs <- hist(xb, breaks = mybreaks(xb, nbr), \n# warn.unused = FALSE, probability = TRUE, plot = plot, ...)\n# \n# m <- length(hs$counts)\n# c <- qnorm(p = 1 - alpha / 2 / m) * sqrt(m / n)\n# \n# ln1 <- c(pmax(sqrt(hs$density) - c, 0)^2, 0)\n# un1 <- c((sqrt(hs$density) + c)^2 , 0)\n# \n# hs2 <- predict.hist(hs, data$test)\n# \n# ln2 <- pmax(sqrt(hs2) - c, 0)^2\n# un2 <- (sqrt(hs2) + c)^2\n# \n# if (plot) {\n# lines(data$test, ln2, type = 's', col = 4, lwd = 2)\n# lines(data$test, un2, type = 's', col = 4, lwd = 2)\n# }\n# \n# return(list(punctual = hs2,\n# tube = rbind(ln2, un2)))\n# }\n \n\n\n## 0. Simulate data ####\n#dd <- list(train = rnorm(1000), test = sort(rnorm(1000)))\n#oo <- tube_wass(dd, plot = TRUE,ylim = c(0, 2))\n#lines(dd$test, oo$punctual, col = 2, lwd = 2)\n#lines(dd$test, oo$tube[1, ], type = 's', col = 4, lwd = 2)\n#lines(dd$test, oo$tube[2, ], type = 's', col = 4, lwd = 2)\n#curve(dchisq(x, 3), add = TRUE, col = 2, lwd = 2)\n\n\n# error_tube(oo$punctual, oo$tube)\n# uno <- gendata(1, 200)\n# bis <- tube_KDE(uno)\n# error_tube(bis$punctual, bis$tube)\n# \n# ter <- BagHistfp(uno, B = 100)\n# \n# qter <- tube_wass(uno)\n# \n# error_tube(ter$punctual, \n# baseboot(uno$test, ter$punctual, na.omit(ter$bunch)))\n# error_tube(ter$punctual, \n# npheuristic(uno$test, ter$punctual, na.omit(ter$bunch)))\n# error_tube(ter$punctual, \n# kfwe(uno$test, ter$punctual, na.omit(ter$bunch), k = 5))\n# error_tube(qter$punctual, qter$tube)\n\n\n## By default all the CI are at 90% (hard coded on sm.density)\nsimulaciones = function(n = 100, # data size \n M = 50, # number of replicata\n B = 150){ # number of bootstrapt samples\n estimators <- c(\"Hist\", \"FP\", \"Kde\", \"Kde_sm\", \"Kde_M\") #, \"wass\")\n densities <- c(\"normal\", \"chi2\", \"mix1\", \"bart\", \"triangular\", \"rara1\", \"rara2\", \"rara3\")\n\n vars2export <- c(\"BagHistfp\", \"Bagkde\", \"bropt\", \"broptfp\", \"dtriangle\", \n \"dberdev\", \"error\", \"ind\", \"rnorMix\", \"MW.nm14\", \"dnorMix\",\n \"MW.nm16\", \"baseboot\" , \"tube_fp\", \"tube_KDEsm\",\"cteboot\",\n \"gendata\", \"kde\", \"mel\", \"melange\", \"mybreaks\", \"onekdeucv\",\n \"predict.hist\", \"predict.hist.x.V2\", \"rash\", \"rberdev\", \"error_tube\",\n \"riskhist\", \"riskfp\",\"rtriangle\", \"simulaciones\", \"tube_hist\", \"tube_KDE\") \n res <- foreach(i = 1:M, .combine = rbind.data.frame,.export = vars2export,\n .packages = c(\"sm\", \"CppFunctions\")) %:% \n foreach(ll = c(1, 3, 5, 8, 11, 13, 20, 21), .combine = rbind) %dopar% {\n\n dd <- gendata(ll, n)\n \n estim_hist <- tube_hist(dd, B = B) #tubo_Hist(dd, B = B)\n estim_fp <- tube_fp(dd, B = B)\n estim_kde <- tube_KDE(dd, B = B)\n estim_kdesm <- tube_KDEsm(dd)\n estim_kdeM <- cteboot(dd$test, estim_kde$punctual, estim_kde$bunch)\n# estim_wass <- tube_wass(dd)\n\n #tube2 <- baseboot(dd$test, estim_fp$punctual, estim_fp$bunch)\n #tube3 <- npheuristic(dd$test, estim_fp$punctual, estim_fp$bunch)\n\n uno <- c( i, ll, 1, error_tube(dd$dobs, estim_hist$tube)) \n dos <- c( i, ll, 2, error_tube(dd$dobs, estim_fp$tube)) \n tres <- c( i, ll, 3, error_tube(dd$dobs, estim_kde$tube)) \n cuatro <- c( i, ll, 4, error_tube(dd$dobs, estim_kdesm$tube))\n cinco <- c( i, ll, 5, error_tube(dd$dobs, estim_kdeM))\n# seis <- c( i, ll, 6, error_tube(dd$dobs, estim_wass$tube))\n \n rbind(uno, dos, tres, cuatro, cinco) #, seis) \n }\n \n colnames(res) <- c(\"nb_iter\", \"density\", \"estimator\", \"coverage\", \"min_width\", \n \"mean_width\", \"max_width\")\n rownames(res) <- NULL\n res$density <- factor(res$density, labels = densities)\n res$estimator <- factor(res$estimator, labels = estimators)\n return(res)\n} \n\n\n\nregisterDoParallel(detectCores()) #detectCores())\n\n#system.time(S <- simulaciones(n = 200, M = 20, B = 10))\nsystem.time(S <- simulaciones(n = 500, M = 100, B = 200))\n\n# save(S, file = \"~/simulationcestubos-S.Rdata\")\n\nSres <- aggregate(S[, c(1, 4:7)],\n by = list(density = S$density, estimator = S$estimator), mean)\n\n\nxtable::xtable(Sres[order(Sres$density), ], digits = 3)\nplot(Sres$coverage, Sres$mean_width, pch = 19, col = as.integer(Sres$estimator))\n\ntab1 <- 100 * xtabs(coverage ~ density + estimator, data = Sres)[, -5]\ntab2 <- xtabs(mean_width ~ density + estimator, data = Sres)[, -5]\n\nxtable::xtable(round(cbind(tab1, tab2), 2))\n\n ", "meta": {"hexsha": "5b774617a129a38851d6d3e9c56651b7ffa3f0c3", "size": 8146, "ext": "r", "lang": "R", "max_stars_repo_path": "src/simulaciones-tubos.r", "max_stars_repo_name": "ThegreatShible/Bagging-of-Density-Estimators", "max_stars_repo_head_hexsha": "b2b1d16790165931bfd3f2f49e083554dc840f9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulaciones-tubos.r", "max_issues_repo_name": "ThegreatShible/Bagging-of-Density-Estimators", "max_issues_repo_head_hexsha": "b2b1d16790165931bfd3f2f49e083554dc840f9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulaciones-tubos.r", "max_forks_repo_name": "ThegreatShible/Bagging-of-Density-Estimators", "max_forks_repo_head_hexsha": "b2b1d16790165931bfd3f2f49e083554dc840f9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9613733906, "max_line_length": 98, "alphanum_fraction": 0.5713233489, "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45290299229929926}} {"text": "######################## FUNCIONES BÁSICAS DE CÁLCULO DE LOS DIV ########################\n# Cálculos de los DIV\n# Método americano:\n\ncalculaDIV_ModeloAmericano_HR <- function(temperaturas, HR, matrizDIV, umbralHR = 85, dataSamplingTime = 30)\n{ \n\t# temperaturas: un vector numérico con los valores de temperaturas (en ºC), pueden estar medidos en cualquier formato temporal\n\t# HR: vector numérico con los valores de humedar relativa (en tanto por ciento 0 a 100), en el mismo formato temporal que \"temperaturas\"\n\t# matrizDIV: matriz de DIV según modelo americano\n\t# dataSamplingTime = valor numérico que indica la granularidad de los datos, en minutos, si la estacion mide en horarios= 60, semihorarios = 30, quinceminutales = 15\n\t# umbralHR: valor numérico, indica el valor de HR por encima del cual se considera que hay agua libre en la atmósfera\n\t\n\t# Totalizar horas humectacion y redondearlas a un entero\n\thorasHumec <- round(sum(ifelse(HR > umbralHR, dataSamplingTime/60, 0)), digits = 0)\n\t# Calcular media temperaturas en horas en las que hay humectación\n\ttempMediaHumec <- round(mean(temperaturas[which(HR > umbralHR)]), digits = 1)\n\n\t# Establecer qué valor de la matrizDIV corresponde a esa humectacion y a esa temperatura\n\tescalaFarenheit <- c(seq(from = 60, to = 94, by = 1), 95)\n\tescalaCelsius <- (escalaFarenheit-32) * 5/9\n\n\tif(tempMediaHumec < 15.2 || tempMediaHumec > 36 || horasHumec == 0)\n\t{\n\t\tDIV = 0\n\t}else\n\t{\n\t\tcolumnaTemperatura <- which.min(abs(escalaCelsius - tempMediaHumec))\n\t\tfilaHumectacion <- (24 - horasHumec + 1)\n\t\t\n\t\tDIV = matrizDIV[filaHumectacion, columnaTemperatura]\n\t}\n\t\n\treturn(list(DIV_HR = DIV,\n\t\t\t\ttemperatura_HR = tempMediaHumec,\n\t\t\t\thorasHumectacion_HR = horasHumec))\n}\n\ncalculaDIV_ModeloAmericano_HumectUmbral <- function(temperaturas, humectaciones, matrizDIV, valorHumectacionMinimo, dataSamplingTime = NULL)\n{\n\t# temperaturas: un vector numérico con los valores de temperaturas (en ºC), pueden estar medidos en cualquier formato temporal\n\t# humectaciones: vector numérico con los valores de humectación (en minutos o porcentaje, ver \"unidadesHumectacion\"), en el mismo formato temporal que \"temperaturas\"\n\t# matrizDIV: matriz de DIV según modelo americano\n\t# valorHumectacionMinimo: Puede ser un tiempo, un porcentaje, etc, que indique qué valor ha de superarse para considerarse que el período de tiempo es húmedo\n\t# dataSamplingTime: no es necesario, pero si no se da se considera que el tiempo de medida es horario. Si se usa es de forma análoga a la función calculaDIV_ModeloAmericano_HR()\n\t\n\t# Totalizar horas humectacion y redondearlas a un entero\n\tif(is.null(dataSamplingTime))\n\t{\n\t\thorasHumec <- round(sum(humectaciones[humectaciones > valorHumectacionMinimo]/60), digits = 0)\n\t}else\n\t{ \n\t\thorasHumec <- round(sum(ifelse(humectaciones > valorHumectacionMinimo, dataSamplingTime/60, 0)), digits = 0)\n\t}\n\t# Calcular media temperaturas en horas humectación\n\ttempMediaHumec <- round(mean(temperaturas[which(humectaciones > valorHumectacionMinimo)]), digits = 1)\n\n\t# Establecer qué valor de la matrizDIV corresponde a esa humectacion y a esa temperatura\n\n\tescalaFarenheit <- c(seq(from = 60, to = 94, by = 1), 95)\n\tescalaCelsius <- (escalaFarenheit-32) * 5/9\n\t\t\n\tif(tempMediaHumec < 15.28 || tempMediaHumec > 35.28 || horasHumec == 0)\n\t{ # por encima de estos valores o con cero humectacion no hay riesgo\n\t\tDIV = 0\n\t}else\n\t{\n\t\tcolumnaTemperatura <- which.min(abs(escalaCelsius - tempMediaHumec))\n\t\tfilaHumectacion <- (24 - horasHumec + 1)\n\t\t\n\t\tDIV = matrizDIV[filaHumectacion, columnaTemperatura]\n\t}\n\t\t\n\t\t\n\treturn(list(DIV_HumectUmbral = DIV,\n\t\t\t\ttemperatura_HumectUmbral = tempMediaHumec,\n\t\t\t\thorasHumectacion_HumectUmbral = horasHumec))\n}\n\n# Método Horario, modelo Rioja:\nCalculaDIV_Horario_ModeloRioja <- function(temperaturas, humectaciones, vectorDIVHorario, valorUmbralMinimo, dataSamplingTime, na.rm = TRUE)\n{\n\t# temperaturas: un vector numérico con los valores de temperaturas (en ºC), su período de tiempo viene dado por dataSamplingTime ejemplo: dataSamplingTime = 60 ==> 1 hora => datos horarios\n\t# humectaciones: un vector numérico con los valores de humectación (en minutos) ó humedad relativa (en tanto por ciento 0-100), idem temperaturas para dataSamplingTime\n\t# valorUmbralMinimo: Puede ser un tiempo p.ej: valorUmbralMinimo = 5; o un porcentaje de HR, p. ej. valorUmbralMinimo = 85, que indique qué valor ha de superarse para considerarse que el período de tiempo es húmedo\n\t# dataSamplingTime: valor numérico que indica la granularidad de los datos, en minutos, la tabla de DIV usada es horaria, si el dataSampling time es diferente se hace una regla de tres\n\t# vectorDIVHorario: vector de DIV según modelo Rioja\n\t\n\t\n\tdf.TempHumect <- data.frame(temperaturas = temperaturas, humectaciones = humectaciones, check.rows = FALSE)\n\t\t\n\t# Obtener qué horas han tenido humectación por encima del umbral\n\tdf.TempHumect$hayHumectacion <- df.TempHumect$humectaciones > valorUmbralMinimo\n\t\t\t\t\n\t# Establecer qué valor del vector de DIV corresponde a esa humectacion y a esa temperatura\n\n\t# Generamos escala de temperaturas de acuerdo a intervalos a artículo Sheng and Teng (1989)\n\tescalaFarenheit <- c(seq(from = 60, to = 94, by = 1), 95)\n\tescalaCelsius <- (escalaFarenheit-32) * 5/9\n\t\n\tdf.TempHumect$DIVHorario <- 0\n\tfor(fila in 1:nrow(df.TempHumect))\n\t{\n\t\tif(df.TempHumect$temperaturas[fila] > escalaCelsius[1] &&\t\t\t\n\t\t\tdf.TempHumect$temperaturas[fila] < (last(escalaCelsius) + 0.5) &&\n\t\t\tdf.TempHumect$hayHumectacion[fila])\n\t\t{\n\t\t\tdf.TempHumect$DIVHorario[fila] <- vectorDIVHorario$DIVHorario[which.min(abs(escalaCelsius - df.TempHumect$temperaturas[fila]))] * dataSamplingTime/60 #dataSamplingTime/60 corrección a horas\n\t\t}\n\t}\n\n\n\tif(any(is.na(temperaturas)) | any(is.na(humectaciones)))\n\t{\n\t\tif(!na.rm) stop(\"Algún NA en vector temperaturas o humectaciones, na.rm = TRUE\")\n\t\twarning(paste(\"Algún NA en vector temperaturas o humectaciones, DIV puede ser no valido en posiciones\",\n\t\t\t\twhich(is.na(temperaturas)), \"vector temperaturas, o\", which(is.na(humectaciones)), \"vector humectaciones\"))\n\t}\n\t\t\n\treturn(list(DIV_Horario_Acumulado = sum(df.TempHumect$DIVHorario, na.rm = TRUE),\n\t\t\t\tDIV_Horario = df.TempHumect$DIVHorario,\n\t\t\t\t df.TempHumect = df.TempHumect)) \n}\n# # TEST\n## Distintas temperaturas en los límites del vectorDIVHorario\n# CalculaDIV_Horario_ModeloRioja(temperaturas = c(15, 16.5, 16, 36, 16, 0), humectaciones = c(30, 30, 0, 30, 30, 30),\n# \t\t\t\t\t\tvectorDIVHorario, valorUmbralMinimo = 5, dataSamplingTime = 60)\n## Error, vectores temperaturas, humectaciones no igual longitud; temperaturas más largo\n# CalculaDIV_Horario_ModeloRioja(temperaturas = c(15, 16.5, 16, 36, 16, 0, 26), humectaciones = c(30, 30, 0, 30, 30, 30),\n# \t\t\t\t\t\tvectorDIVHorario, valorUmbralMinimo = 5, dataSamplingTime = 60)\n## Actuación ante vectores con NA.Error, vectores temperaturas, humectaciones incluyen algún NA\n## Temperaturas\n# CalculaDIV_Horario_ModeloRioja(temperaturas = c(15, 16.5, NA, 36, 16, 0, 26), humectaciones = c(30, 30, 0, 0, 30, 30, 30),\n# \t\t\t\t\t\tvectorDIVHorario, valorUmbralMinimo = 5, dataSamplingTime = 60)\n## Humectaciones\n# CalculaDIV_Horario_ModeloRioja(temperaturas = c(15, 16.5, 16, 36, 16, 0, 26), humectaciones = c(30, 30, 0, NA, 30, 30, 30),\n# \t\t\t\t\t\tvectorDIVHorario, valorUmbralMinimo = 5, dataSamplingTime = 60)\n\n\n######################## FUNCIONES AUXILIARES PARA GENERAR OBJETOS CON LOS RESULTADOS CALCULADOS USANDO DISTINTOS MÉTODOS Y MÉTRICAS ########################\ncalculaDIVAcum <- function(DIV){ # Se usa en ambos modelos (Americano y Rioja), para sumar el DIV diario de ayer y hoy\n\tres <- rep(NA, length(DIV)) # <- c()\n\tres[1] = DIV [1]\n\t\n\tfor(posicion in 2:length(DIV))\n\t{\n\t\tres[posicion] = DIV [posicion] + DIV [posicion - 1]\n\t}\n\treturn(res)\n}\n\n# Función para obtener un objeto (data.frame) con todos los resultados según el modelo americano\ncalculaRiesgoDIV_MODELO_AMERICANO <- function(datosClimaticos, diasCalculo, estacion, matrizDIV, horaInicio, offsetHR, dataSamplingTime, valorHumectacionMinimo)\n{\n\t# horaInicio = \"10\", hora solar a la que se inician los cálculos\n\t# offsetHR = 0 por defecto se calcula el modelo con umbrales de HR de 80 a 92.5%. offsetHR permite modifificar los umbrales, por ejemplo offset = - 5 haría los cálculosa 75, 80 y 85% de umbral\n\n\t\t\n\t# Generar una data.frame igual a la que vamos a construir después en el for (Inicializar variable)\n\tDIV <- data.frame(fecha = as.POSIXct(character()),\n\t\t\t\t\testacion = numeric(),\n\t\t\t\t\tDIV_HumectUmbral = numeric(), T_HumectUmbral = numeric(), HorasHumectacion_HumectUmbral = numeric(),\n\t\t\t\t\tDIV_HR80 = numeric(), T_HR80 = numeric(), HorasHumectacion_HR80 = numeric(),\n\t\t\t\t\tDIV_HR82.5 = numeric(), T_HR82.5 = numeric(), HorasHumectacion_HR82.5 = numeric(),\n\t\t\t\t\tDIV_HR85 = numeric(), T_HR85 = numeric(), HorasHumectacion_HR85 = numeric(),\n\t\t\t\t\tDIV_HR87.5 = numeric(), T_HR87.5 = numeric(), HorasHumectacion_HR87.5 = numeric(),\n\t\t\t\t\tDIV_HR90 = numeric(), T_HR90 = numeric(), HorasHumectacion_HR90 = numeric(),\n\t\t\t\t\tDIV_HR92.5 = numeric(), T_HR92.5 = numeric(), HorasHumectacion_HR92.5 = numeric()\n\t\t\t\t\t)\n\t\t\t\t\t\t\n\tDIV.names <- names(DIV)\n\t\n\t# Calcular el DIV para cada día de los solicitados\n\tfor (dia in diasCalculo)\n\t{\n\t\tdia <- as.POSIXct(dia, origin = \"1970-01-01\")\n\t\tdatos <- datosClimaticos[datosClimaticos$fecha > dia & datosClimaticos$fecha <= dia + 3600*24,] # extraer datos para el día de cálculo\t\t\n\t\t\n\t\tif(nrow(datos) < (1440/dataSamplingTime - 288/dataSamplingTime)) next # dia Incompleto, se acepta la pérdida del 20% de datos\n\t\t\n\t\tres <- data.frame(fecha = dia + 3600*24, estacion = estacion,\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HumectUmbral(datos$temperatura, datos$humectacion, matrizDIV, valorHumectacionMinimo, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 80 - offsetHR, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 82.5 - offsetHR, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 85 - offsetHR, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 87.5 - offsetHR, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 90 - offsetHR, dataSamplingTime),\n\t\t\t\t\tcalculaDIV_ModeloAmericano_HR(datos$temperatura, datos$HR, matrizDIV, umbralHR = 92.5 - offsetHR, dataSamplingTime)\n\t\t\t\t\t) # calcular DIV\n\t\t\n\t\tDIV <- rbind(DIV, res) # unir \n\t}\n\t\n\tnames(DIV) <- DIV.names\n\t\n\t# Insertar el DIV Acumulado\n\tDIV <- data.frame(fecha = DIV$fecha,\n\t\t\t\t\t\testacion = DIV$estacion,\n\t\t\t\t\t\tT_HumectUmbral = DIV$T_HumectUmbral, HorasHumectacion_HumectUmbral = DIV$HorasHumectacion_HumectUmbral,\n\t\t\t\t\t\tDIV_HumectUmbral = DIV$DIV_HumectUmbral, DIV_HumectUmbralAcum = calculaDIVAcum(DIV$DIV_HumectUmbral),\n\t\t\t\t\t\tT_HR80 = DIV$T_HR80, HorasHumectacion_HR80 = DIV$HorasHumectacion_HR80,\n\t\t\t\t\t\tDIV_HR80 = DIV$DIV_HR80, DIV_HR80Acum = calculaDIVAcum(DIV$DIV_HR80),\n\t\t\t\t\t\tT_HR82.5 = DIV$T_HR82.5, HorasHumectacion_HR82.5 = DIV$HorasHumectacion_HR82.5,\n\t\t\t\t\t\tDIV_HR82.5 = DIV$DIV_HR82.5, DIV_HR82.5Acum = calculaDIVAcum(DIV$DIV_HR82.5),\n\t\t\t\t\t\tT_HR85 = DIV$T_HR85, HorasHumectacion_HR85 = DIV$HorasHumectacion_HR85,\n\t\t\t\t\t\tDIV_HR85 = DIV$DIV_HR85, DIV_HR85Acum = calculaDIVAcum(DIV$DIV_HR85),\n\t\t\t\t\t\tT_HR87.5 = DIV$T_HR87.5, HorasHumectacion_HR87.5 = DIV$HorasHumectacion_HR87.5,\n\t\t\t\t\t\tDIV_HR87.5 = DIV$DIV_HR87.5, DIV_HR87.5Acum = calculaDIVAcum(DIV$DIV_HR87.5),\n\t\t\t\t\t\tT_HR90 = DIV$T_HR90, HorasHumectacion_HR90 = DIV$HorasHumectacion_HR90,\n\t\t\t\t\t\tDIV_HR90 = DIV$DIV_HR90, DIV_HR90Acum = calculaDIVAcum(DIV$DIV_HR90),\n\t\t\t\t\t\tT_HR92.5 = DIV$T_HR92.5, HorasHumectacion_HR92.5 = DIV$HorasHumectacion_HR92.5,\n\t\t\t\t\t\tDIV_HR92.5 = DIV$DIV_HR92.5, DIV_HR92.5Acum = calculaDIVAcum(DIV$DIV_HR92.5)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\n\treturn(DIV)\n}\n\n# Función para obtener un objeto (dos data.frames) con los resultados según el modelo Horario, un objeto permite comparar el resultado con el modelo americano\n# el otro es el valor del DIV calculado para cada hora\ncalculaRiesgoDIV_MODELO_RIOJA <- function(datosClimaticos, diasCalculo, estacion, vectorDIVHorario, offsetHR, dataSamplingTime, valorHumectacionMinimo)\n{\n\t# GENERA DOS OBJETOS:\n\t# DIV, que es una data.frame con valores DIARIOS, es un remedo del DIV Americano, aunque no tiene mucho sentido, es sólo por hacer equiparables los conceptos, se calcula a horaInicio (que viene prefijado en diasCalculo)\n\t# DIV_Horario, que es una data.frame con valores HORARIOS, y tiene más sentido que lo anterior y permite integrar los cálculos del DIV para cada hora posteriormente\n\t\n\t# Generar data.frames iguales a las que vamos a construir después en el for\n\tDIV <- data.frame(fecha = as.POSIXct(character()),\n\t\t\t\t\testacion = numeric(),\n\t\t\t\t\tDIV_HumectUmbral = numeric(),\n\t\t\t\t\tDIV_HR80 = numeric(),\n\t\t\t\t\tDIV_HR82.5 = numeric(),\n\t\t\t\t\tDIV_HR85 = numeric(),\n\t\t\t\t\tDIV_HR87.5 = numeric(),\n\t\t\t\t\tDIV_HR90 = numeric(),\n\t\t\t\t\tDIV_HR92.5 = numeric()\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t)\n\t\t\t\t\t\t\n\tDIV.names <- names(DIV)\n\n\tDIV_Horario <- data.frame(DIV_Horario_HumectUmbral = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR80 = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR82.5 = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR85 = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR87.5 = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR90 = numeric(),\n\t\t\t\t\t\t\t\tDIV_Horario_HR92.5 = numeric()\n\t\t\t\t\t\t\t\t)\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\tDIV_Horario.names <- names(DIV_Horario)\n\t\t\n\tfor(dia in diasCalculo) #[dias > first(datosClimaticos$fecha)]){\n\t{\n\t\tdia <- as.POSIXct(dia, origin = \"1970-01-01\")\n\t\tdatos <- datosClimaticos[datosClimaticos$fecha > dia & datosClimaticos$fecha <= dia + 3600*24,] # extraer datos para el día de cálculo\t(dia es un posixct con la hora de inicio del modelo incluida)\t\n\t\n\t\tif(nrow(datos) == 0) next\n\t\t\n\t\tDIV_HumectUmbral = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$humectacion, vectorDIVHorario, valorUmbralMinimo = valorHumectacionMinimo, dataSamplingTime)\n\t\tDIV_HR80 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 80 - offsetHR, dataSamplingTime)\n\t\tDIV_HR82.5 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 82.5 - offsetHR, dataSamplingTime)\n\t\tDIV_HR85 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 85 - offsetHR, dataSamplingTime)\n\t\tDIV_HR87.5 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 87.5 - offsetHR, dataSamplingTime)\n\t\tDIV_HR90 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 90 - offsetHR, dataSamplingTime)\n\t\tDIV_HR92.5 = CalculaDIV_Horario_ModeloRioja(datos$temperatura, datos$HR, vectorDIVHorario, valorUmbralMinimo = 92.5 - offsetHR, dataSamplingTime)\n\t\t\t\t\t\t\n\t\tres <- data.frame(fecha = dia + 3600*24, estacion = estacion,\n\t\t\t\t\tDIV_HumectUmbral$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR80$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR82.5$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR85$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR87.5$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR90$DIV_Horario_Acumulado,\n\t\t\t\t\tDIV_HR92.5$DIV_Horario_Acumulado\t\n\t\t\t\t)\n\t\t\n\t\tDIV <- rbind(DIV, res)\n\t\t\n\t\tres2 <- data.frame(DIV_HumectUmbral$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR80$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR82.5$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR85$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR87.5$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR90$DIV_Horario,\n\t\t\t\t\t\t\tDIV_HR92.5$DIV_Horario\t\t\t\t\t\t\t\n\t\t\t\t\t\t)\n\n\t\tDIV_Horario <- rbind(DIV_Horario, res2) \n\t}\n\t\n\t\n\tnames(DIV) <- DIV.names\n\tnames(DIV_Horario) <- DIV_Horario.names\n\t\n\t# Insertar el DIV Acumulado\n\tDIV <- data.frame(fecha = DIV$fecha,\n\t\t\t\t\t\testacion = DIV$estacion,\n\t\t\t\t\t\tDIV_HumectUmbral = DIV$DIV_HumectUmbral, DIV_HumectUmbralAcum = calculaDIVAcum(DIV$DIV_HumectUmbral),\n\t\t\t\t\t\tDIV_HR80 = DIV$DIV_HR80, DIV_HR80Acum = calculaDIVAcum(DIV$DIV_HR80),\n\t\t\t\t\t\tDIV_HR82.5 = DIV$DIV_HR82.5, DIV_HR82.5Acum = calculaDIVAcum(DIV$DIV_HR82.5),\n\t\t\t\t\t\tDIV_HR85 = DIV$DIV_HR85, DIV_HR85Acum = calculaDIVAcum(DIV$DIV_HR85),\n\t\t\t\t\t\tDIV_HR87.5 = DIV$DIV_HR87.5, DIV_HR87.5Acum = calculaDIVAcum(DIV$DIV_HR87.5),\n\t\t\t\t\t\tDIV_HR90 = DIV$DIV_HR90, DIV_HR90Acum = calculaDIVAcum(DIV$DIV_HR90),\n\t\t\t\t\t\tDIV_HR92.5 = DIV$DIV_HR92.5, DIV_HR92.5Acum = calculaDIVAcum(DIV$DIV_HR92.5)\n\t\t\t\t\t\t)\n\n\treturn(list(DIV = DIV, DIV_Horario = DIV_Horario))\n}\n\n\n# Función que acumula los valores de DIV para un número de registros = numDatos\n# IMPORTANTE: Los valores de temperaturas, humectación y umbral humectación NO SE USAN\n# se pasan sólo por si acaso en el futuro se implementan reseteos en el modelo de acumulación\ncalculaDIVAcumHorario <- function(DIV, temperatura, humectacion, umbralHumectacion, offsetHR = 0, numDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime)\n{\n\tDIVAcumHorario <- rep(NA, length(DIV))\n\tnumHorasDIVesNulo <- rep(NA, length(DIV))\n\t\n\tnumDatos = numDatos * 60/dataSamplingTime # Corrección para considerar el número de registros en cálculos no horarios\n\t\n\tfor(posicion in 1:length(DIV))\n\t{\n\t\tif(DIV[posicion] == 0){# Para cada registro si el DIV es cero se acumulan las horas donde DIV == 0\n\t\t\tnumHorasDIVesNulo[posicion] <- dataSamplingTime/60 + if(posicion > 1) numHorasDIVesNulo[posicion - 1] else 0\n\t\t}else{ # cuando es DIV != 0 se resetea la cuenta\n\t\t\tnumHorasDIVesNulo[posicion] = 0\n\t\t}\n\t\t\n\t\tif(posicion >= numDatos){# Superado el número de datos mínimo se hace el cálculo del DIV\n\t\t\torigen = posicion - numDatos\n\t\t\textracto <- data.frame(temperatura = temperatura,\n\t\t\t\t\t\t\t\t\thumectacion = humectacion,\n\t\t\t\t\t\t\t\t\tnumHorasDIVesNulo = numHorasDIVesNulo,\n\t\t\t\t\t\t\t\t\tDIV = DIV)\n\n\t\t\textracto <- extracto[origen:posicion, ]\n\t\t\t\n\t\t\tif(!is.na(numHorasReseteo)){ # este parámetro puede no estar definido\n\t\t\t\t# Comprobación por temperaturas extremas #!!!\n\t\t\t\t\t#if(any(extracto$temperatura) > umbralMaximo) etc\n\t\t\t\t# Comprobación por humectaciones bajas extremas #!!!\n\t\t\t\t# Comprobación por número de horas DIV > 0\n\t\t\t\tif(any(extracto$numHorasDIVesNulo == numHorasReseteo)){ # Si no hay reseteo la fórmula es como la de antes\n\t\t\t\t\tposicionReseteo <- last(which(extracto$numHorasDIVesNulo == nummHorasReseteo)) # Last() por si hay más de un reseteo\n\t\t\t\t\textracto <- extracto[posicionReseteo:nrow(extracto),] # Detrás del reseteo se pueden acumular más horas secas pero solo se acumula DIV de ahí en adelante\n\t\t\t\t}\n\t\t\t}\n\t\t\tDIVAcumHorario[posicion] <- sum(extracto$DIV, na.rm = TRUE)\n\t\t}\n\t}\n\n\treturn(DIVAcumHorario)\n}\n\n# Función que devuelve un vector de valores lógicos TRUE/FALSE que indican si la lluvia acumulada se considera efectiva o no.\nesLluviaEfectiva <- function(PAcum)\n{\n\tlluviaEfectiva <- logical() # Inicializar variable\n\t\t\n\tlluviaEfectivaHoraria = 1 * 60 / dataSamplingTime # Si llueve más de un litro cada hora = 2 litros a la hora, la lluvia se considera efectiva\n\tlluviaEfectivaPorAcumulacion = 0.2 * 60 / dataSamplingTime # Si llueve en algo en una hora y también la siguiente, aunque sea poca cantidad, se considera efectiva\n\tlluviaEfectivaPorAcumulacion2HorasPrevias = 0.4 # Si llueve en esta hora y ha llovido más de 0.4 en las dos horas anteriores, se considera efectiva\n\t\t\n\tfor(posicion in 1:length(PAcum))\n\t{\n\t\tlluviaEfectiva[posicion] = FALSE\n\t\t\t\n\t\tif(!is.na(PAcum[posicion]) & posicion < length(PAcum)) # si no es NA | En la última posición no se hace el cálculo\n\t\t{\n\t\t\tif(PAcum[posicion] >= lluviaEfectivaHoraria) \n\t\t\t{# Si llueve más de un litro cada media hora = 2 litros a la hora, la lluvia se considera efectiva\n\t\t\t\tlluviaEfectiva[posicion] = TRUE\n\t\t\t\tnext\n\t\t\t}\n\t\t\tif(PAcum[posicion] > lluviaEfectivaPorAcumulacion & sum(PAcum[posicion + 1] > lluviaEfectivaPorAcumulacion)) \n\t\t\t{# Si llueve más de un litro cada media hora = 2 litros a la hora, la lluvia se considera efectiva\n\t\t\t\tlluviaEfectiva[posicion] = TRUE\n\t\t\t\tnext\n\t\t\t}\n\t\t\tif(posicion > 2) # No se puede ejecutar este análisis en las dos primeras posiciones del vector de lluvias\n\t\t\t{# Si llueve en esta hora y ha llovido más de 0.4 en las dos horas anteriores, se considera efectiva\n\t\t\t\tif( PAcum[posicion] > 0 & (PAcum[posicion - 1] + PAcum[posicion - 2]) > 0.4) \n\t\t\t\t{\n\t\t\t\t\tlluviaEfectiva[posicion] = TRUE\n\t\t\t\t\tnext\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn(lluviaEfectiva)\n}\n\n# Función que devuelve un vector de valores lógicos TRUE/FALSE que indican si la temperatura registrada se considera efectiva o no.\nhayTemperaturaEfectiva <- function(temperatura, umbralTempMinima, umbralTempMaxima)\n{\n\thayTemperaturaEfectiva <- ifelse(temperatura >= umbralTempMinima & temperatura < umbralTempMaxima, TRUE, FALSE) \n\treturn(hayTemperaturaEfectiva)\n}\n\n# Función que devuelve un vector de valores lógicos TRUE/FALSE que indican si la temperatura registrada está entre 10 y 13ºC\nestaTemperaturaEntre10y13Grados <- function(temperatura)\n{\n\thayTemperaturaEfectiva <- ifelse(temperatura >= 10 & temperatura < 13 , TRUE, FALSE) \n\treturn(hayTemperaturaEfectiva)\n}\n\n# Función para obtener un objeto (data.frame) con los resultados de las fechas que cumplen infección para ello se consideran los siguientes parámetros:\n# umbralTempMinima ==> mínima temperatura necesaria para que se considere a la espora activa para infectar (13 ºC según bibliografía)\n# umbralTempMaxima ==> máxima temperatura que la espora permite para mantener su poder infetivo (35 ºC según bibliografía)\n# horasAcumuladasParaAparicionInfeccion => horas necesarias para que la germinación sea satisfactoria y la infección se produzca\ncalculaMomentosInfeccion <-function(fecha, temperatura, humectacion, umbralHumectacion, umbralTempMinima = 13, umbralTempMaxima = 35, horasAcumuladasParaAparicionInfeccion = 8){\n\tres <- data.frame(fecha, temperatura, humectacion, stringsAsFactors = FALSE)\n\t\n\tres$hayHumectacion = ifelse(humectacion > umbralHumectacion, TRUE, FALSE)\n\tres$hayTemperaturaOptima = ifelse(temperatura >= umbralTempMinima & temperatura <= umbralTempMaxima, TRUE, FALSE)\n\t\n\tres$horasAcumuladas[1] = if(res$hayHumectacion[1] & res$hayTemperaturaOptima[1]) 1 else 0\n\tfor(posicion in 2:nrow(res)){ # Si se dan condiciones de Humectación y temperatura en esta variable almaceno, para cada registro, el número de horas de condiciones apropiadas\n\t\tres$horasAcumuladas[posicion] = if(res$hayHumectacion[posicion] & res$hayTemperaturaOptima[posicion]) 1 + res$horasAcumuladas[posicion-1] else 0\n\t}\n\t\n\tfechasInfeccion = res$fecha[which(res$horasAcumuladas >= horasAcumuladasParaAparicionInfeccion)]\n\t\n\t\n\tcalculaDiasHastaInfeccion <- function(tempMediaPosterior){ # esta funcion ofrece valores de 1 para T = 30 y 20 para T = 10, de forma lineal\n\t\tif(tempMediaPosterior > 30) tempMediaPosterior = 30\n\t\tif(tempMediaPosterior < 10) tempMediaPosterior = NA\n\t\ttempMediaPosterior <- round(tempMediaPosterior, 0)\n\t\tdiasHastaInfeccion = 30 - tempMediaPosterior + 1\n\t\treturn(diasHastaInfeccion)\n\t}\n\t#calculaDiasHastaInfeccion(32); calculaDiasHastaInfeccion(30); calculaDiasHastaInfeccion(20); calculaDiasHastaInfeccion(10); calculaDiasHastaInfeccion(9)\n\t\n\ttempMediaPosterior = numeric()\n\tdiasHastaInfeccion = integer()\n\tfor(fecha in fechasInfeccion){\n\t\ttemperaturasPosterioresInfeccion <- res$temperatura[res$fecha > fecha]\n\t\t\n\t\tif(length(temperaturasPosterioresInfeccion) > 20*24) temperaturasPosterioresInfeccion = temperaturasPosterioresInfeccion[1:20*24] # Eliminamos más allá de 20 días de datos\n\t\ttempMediaPosterior = c(tempMediaPosterior, mean(temperaturasPosterioresInfeccion))\n\t\tdiasHastaInfeccion = if(length(temperaturasPosterioresInfeccion) > 0) calculaDiasHastaInfeccion(last(tempMediaPosterior)) else NA\n\t}\n\t\n\treturn(data.frame(fechasInfeccion, tempMediaPosterior, diasHastaInfeccion))\t\n}\n\n\n\n######################## FUNCION PRINCIPAL REALIZA TODO EL CONTROL DEL PROCESO DE CÁLCULO DE VALORES DIV Y RIESGO ########################\n###\n### LLAMA A LAS DISTINTAS FUNCIONES AUXILIARES Y GENERA OBJETO DE RESPUESTA CON TODA LA INFORMACIÓN OBTENIDA\n###\n###########################################################################################################################################\ncalculaRiesgoDIV_V20 <- function(estacion, fechaInicio, fechaFin,\n\t\t\t\t\t\t\t\t\tmatrizDIV, vectorDIVHorario,\n\t\t\t\t\t\t\t\t\thoraInicio = \"10\", offsetHR = 0,\n\t\t\t\t\t\t\t\t\tsensorHumect = \"THumecta1\",\n\t\t\t\t\t\t\t\t\torigenDato = \"SWClima\",\n\t\t\t\t\t\t\t\t\tnombreEstacion = NA,\n\t\t\t\t\t\t\t\t\t...)\n{\n\n# horaInicio = \"10\", hora solar a la que se inician los cálculos\n# offsetHR = 0 por defecto se calcula el modelo con umbrales de HR de 85 y 90. offsetHR permite modifificar los umbrales, por ejemplo offset = - 5 haría los cálculosa 75, 80 y 85% de umbral\n# sensorHumect = \"THumecta1\", solo aplicable a datos tipo \"SWClima\"; es previsible que se elimine, en la actualidad se extraen los dos sensores de humectacion del SIAR, el que se especifica queda marcado como el sensor 1 en el proceso, es un error lógico\n# origenDato = \"SWClima\", \"CESENS\", etc\n\n\t# EXTRAER DATOS CLIMÁTICOS\n\tres <- extraeDatosClima(estacion, origenDato, fechaInicio, fechaFin)\n\t\n\tres <- fromJSON(res)\n\t\n\tattach(res)\n\n\t# Formatear variables\n\tdatosClimaticos <- as.data.frame(datosClimaticos)\n\tdatosClimaticos$fecha <- as.POSIXct(datosClimaticos$fecha, origin = \"1970-01-01\")\n\t\t\n\tif(!is.na(nombreEstacion)) nombreEstacionCalculada = nombreEstacion # se da prioridad a lo que traiga esta variable, CESENS no tiene una buena trazabilidad de los nombres ligados a los códigos de estaciones\n\t\n\t# Calcular el DIV para cada día entre fechaInicio y fechaFin\n\t# Obtener secuencia de los días a calcular\n\t# por convenio en modelos nunca empezamos el día en las 00:00 sino en una hora que agrícolamente tenga sentido, generalmente entre las 8 y las 10 UTC (Hora solar en España)\n\tdiasCalculo <- seq.POSIXt(from = as.POSIXct(strftime(paste0(fechaInicio, \" \", horaInicio, \":00\"), tz = \"UTC\")),\n\t\t\t\t\t\tto = as.POSIXct(strftime(paste0(fechaFin, \" \", horaInicio, \":00\"), tz = \"UTC\")),\n\t\t\t\t\t\tby = \"day\")\n\t\t\t\t\t\t\n\tdiasCalculo <- diasCalculo[-length(diasCalculo)] # \tquitamos el último día\n\t\n\tdiasCalculo <- diasCalculo[diasCalculo > first(datosClimaticos$fecha)] # y también quitamos los días donde no haya datos procedentes de la estación\n\t\n\tDIV_AMERICANO <- calculaRiesgoDIV_MODELO_AMERICANO(datosClimaticos, diasCalculo, estacion, matrizDIV, horaInicio, offsetHR, dataSamplingTime, valorHumectacionMinimo)\n\n\tDIV_HORARIO <- calculaRiesgoDIV_MODELO_RIOJA(datosClimaticos, diasCalculo, estacion, vectorDIVHorario, offsetHR, dataSamplingTime, valorHumectacionMinimo)\n\n\tDIV <- DIV_HORARIO$DIV\n\tDIV_Horario <- DIV_HORARIO$DIV_Horario\n\t\n\t\n\tdatosClimaticos$lluviaEfectiva <- esLluviaEfectiva(datosClimaticos$PAcum)\n\tdatosClimaticos$temperaturaEfectiva <- hayTemperaturaEfectiva(datosClimaticos$temperatura, umbralTempMinima = 13, umbralTempMaxima = 35)\n\tdatosClimaticos$temperaturaEntre10y13 <- estaTemperaturaEntre10y13Grados(datosClimaticos$temperatura)\n\t\n\t\n\t# Recortar datos climáticos\n\tdatosClimaticos <- datosClimaticos[datosClimaticos$fecha > DIV$fecha[1]-24*3600,]\n\tdatosClimaticos <- datosClimaticos[datosClimaticos$fecha <= last(DIV$fecha),]\n\t\n\t\n\tDIV_Horario <- data.frame(fecha = datosClimaticos$fecha,\n\t\t\t\t\t\t\testacion = rep(estacion, length(datosClimaticos$fecha)),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HumectUmbral = DIV_Horario$DIV_Horario_HumectUmbral,\n\t\t\t\t\t\t\tDIV_HumectUmbral.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HumectUmbral, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$humectacion, umbralHumectacion = valorHumectacionMinimo,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetHR = offsetHR, numDatos = 2 * 24,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HumectUmbral.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HumectUmbral, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$humectacion, umbralHumectacion = valorHumectacionMinimo,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetHR = offsetHR, numDatos = 7 * 24,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HumectUmbral.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HumectUmbral, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$humectacion, umbralHumectacion = valorHumectacionMinimo,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetHR = offsetHR, numDatos = 14 * 24,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HumectUmbral.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HumectUmbral, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$humectacion, umbralHumectacion = valorHumectacionMinimo,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetHR = offsetHR, numDatos = 21 * 24,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HumectUmbral.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HumectUmbral, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$humectacion, umbralHumectacion = valorHumectacionMinimo,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetHR = offsetHR, numDatos = 28 * 24,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR80 = DIV_Horario$DIV_Horario_HR80,\n\t\t\t\t\t\t\tDIV_HR80.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR80, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 80, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR80.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR80, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 80, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR80.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR80, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 80, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR80.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR80, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 80, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR80.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR80, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 80, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR82.5 = DIV_Horario$DIV_Horario_HR82.5,\n\t\t\t\t\t\t\tDIV_HR82.5.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR82.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 82.5, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR82.5.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR82.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 82.5, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR82.5.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR82.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 82.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR82.5.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR82.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 82.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR82.5.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR82.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 82.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR85 = DIV_Horario$DIV_Horario_HR85,\n\t\t\t\t\t\t\tDIV_HR85.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR85, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 85, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR85.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR85, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 85, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR85.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR85, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 85, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR85.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR85, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 85, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR85.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR85, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 85, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR87. = DIV_Horario$DIV_Horario_HR87.5,\n\t\t\t\t\t\t\tDIV_HR87.5.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR87.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 87.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR87.5.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR87.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 87.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR87.5.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR87.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 87.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR87.5.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR87.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 87.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR87.5.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR87.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 87.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR90 = DIV_Horario$DIV_Horario_HR90,\n\t\t\t\t\t\t\tDIV_HR90.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR90, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR90.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR90, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR90.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR90, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR90.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR90, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR90.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR90, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\t##################### \n\t\t\t\t\t\t\tDIV_Horario_HR92.5 = DIV_Horario$DIV_Horario_HR92.5,\n\t\t\t\t\t\t\tDIV_HR92.5.2dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR92.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 92.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 2 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR92.5.7dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR92.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 92.5, offsetHR = offsetHR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 7 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR92.5.14dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR92.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 92.5, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 14 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR92.5.21dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR92.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 92.5, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 21 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime),\n\t\t\t\t\t\t\tDIV_HR92.5.28dias = calculaDIVAcumHorario(DIV_Horario$DIV_Horario_HR92.5, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 92.5, offsetHR = offsetHR, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumDatos = 28 * 24, numHorasReseteo = NA, dataSamplingTime = dataSamplingTime)\n\t\t\t\t\t\t\t)\n\t\n\tfechasInfeccionHR95.8horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 95, horasAcumuladasParaAparicionInfeccion = 8) \n\tfechasInfeccionHR95.6horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 95, horasAcumuladasParaAparicionInfeccion = 6) \n\tfechasInfeccionHR90.8horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, horasAcumuladasParaAparicionInfeccion = 8)\n\tfechasInfeccionHR90.6horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura,\n\t\t\t\t\t\t\t\tdatosClimaticos$HR, umbralHumectacion = 90, horasAcumuladasParaAparicionInfeccion = 6)\n\t\n\tfechasInfeccionHumectacion.8horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura , datosClimaticos$humectacion, umbralHumectacion = 50)\n\tfechasInfeccionHumectacion.6horas <- calculaMomentosInfeccion(datosClimaticos$fecha, datosClimaticos$temperatura , datosClimaticos$humectacion, umbralHumectacion = 50, horasAcumuladasParaAparicionInfeccion = 6)\n\t\n\t\n\t\n\tvariablesConfiguracion <- data.frame(valorDIV = 1, nombre = 'Sin Riesgo', color = \"khaki\", stringsAsFactors = FALSE) \n\tvariablesConfiguracion <- rbind(variablesConfiguracion, list(valorDIV = 2, nombre = 'Inicio Riesgo', color = \"greenyellow\")) \n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = 3, nombre = 'Riesgo Leve', color = \"yellowgreen\")) \n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = 4, nombre = 'Riesgo Medio', color = \"orange\"))\n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = 5, nombre = 'Riesgo Moderado', color = \"sienna1\"))\n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = 6, nombre = 'Riesgo Alto', color = \"tomato1\"))\n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = NA, nombre = 'Riesgo muy Alto', color = \"red1\"))\n\tvariablesConfiguracion <- rbind(variablesConfiguracion,\tlist(valorDIV = 7, nombre = 'Infección segura', color = \"red3\"))\n\t\t\t\t\t\t\t\t\n\trow.names(variablesConfiguracion) = c('DIV.SinRiesgo', 'DIV1.InicioRiesgo', 'DIV.RiesgoLeve', 'DIV.RiesgoMedio',\n\t\t\t\t\t\t\t\t\t\t'DIV.RiesgoModerado', 'DIV.RiesgoAlto', 'DIV.RiesgoMuyAlto', 'DIV.InfeccionSegura')\n\t\n\t\n\t# Generar objeto respuesta\n\tobjetoRespuesta = list(datosClimaticos = datosClimaticos[datosClimaticos$fecha > diasCalculo[1] & datosClimaticos$fecha <= last(diasCalculo) + 3600*24,],\n\t\t\t\tDIV = DIV,\n\t\t\t\tDIV_AMERICANO = DIV_AMERICANO,\n\t\t\t\tDIV_Horario = DIV_Horario,\n\t\t\t\tfechasInfeccion = list(HR95.8horas = fechasInfeccionHR95.8horas, HR95.6horas = fechasInfeccionHR95.6horas,\n\t\t\t\t\t\t\t\t\tHR90.8horas = \tfechasInfeccionHR90.8horas, HR90.6horas = \tfechasInfeccionHR90.6horas,\n\t\t\t\t\t\t\t\t\thumectacion.8horas = fechasInfeccionHumectacion.8horas, humectacion.6horas = fechasInfeccionHumectacion.6horas),\n\t\t\t\tvariablesConfiguracion = variablesConfiguracion,\n\t\t\t\tfechaUltimoDato = tail(DIV_Horario$fecha, 1),\n\t\t\t\torigenDato = origenDato,\n\t\t\t\testacion = estacion,\n\t\t\t\tnombreEstacion = nombreEstacionCalculada)\n\t\n\tdetach(res)\n\t\n\treturn(objetoRespuesta)\n}\n\n\n# Test\n# \n# estacion = 505\n# fechaInicio = as.POSIXct(\"2018-06-01\", tz = \"UTC\")\n# fechaFin = as.POSIXct(\"2018-10-01\", tz = \"UTC\") #Sys.time()\n # matrizDIV <- read.csv(\"Matriz_DIV.csv\", row.names = 1)\n # vectorDIVHorario <- read.csv(\"Vector_DIVHorario.csv\")\n# DIV505_2018 <- calculaRiesgoDIV_V20(estacion, fechaInicio, fechaFin, matrizDIV, vectorDIVHorario)\n # head(DIV505_2018[,c(1,19, 21)])\n # tail(DIV505_2018[,c(1,19, 21)])\n # summary(DIV505_2018[,c(1,19, 21)])\n\n\n\t\n\t\t\t\t\t\t\n", "meta": {"hexsha": "8a0ebfc169f0f62a1221c232b0a75c7ef413d926", "size": 41721, "ext": "r", "lang": "R", "max_stars_repo_path": "FuncionesCalculoRiesgoCercosporaV2022.2.r", "max_stars_repo_name": "joiiiiiiiiiiii/CERCOSPORA-1", "max_stars_repo_head_hexsha": "59212b781b4449daad9e8b24fa163d7f4ab22e81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FuncionesCalculoRiesgoCercosporaV2022.2.r", "max_issues_repo_name": "joiiiiiiiiiiii/CERCOSPORA-1", "max_issues_repo_head_hexsha": "59212b781b4449daad9e8b24fa163d7f4ab22e81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FuncionesCalculoRiesgoCercosporaV2022.2.r", "max_forks_repo_name": "joiiiiiiiiiiii/CERCOSPORA-1", "max_forks_repo_head_hexsha": "59212b781b4449daad9e8b24fa163d7f4ab22e81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.686695279, "max_line_length": 254, "alphanum_fraction": 0.7290093718, "num_tokens": 13773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4523976074711819}} {"text": "#' Calculate statistics for a BayesODM model\n#'\n#' This function calculates statistics for a BayesODM model.\n#' @param mcmc MCMC object from \\code{trainBayesODM}.\n#' @param focusModel SpatialPolygonsDataFrame with BayesODM model output.\n#' @param rhat Maximum value of rhat by which to conclude a model parameter is sufficiently converged.\n#' @param ... Arguments to pass to \\code{rhatStats}.\n#' @return\n#' @examples\n#' @export\nbayesODMStats <- function(mcmc, focusModel, rhat = 1.1, ...) {\n\t\n\tmeta <- attr(focusModel, 'meta')\n\t\n\t# input stats\n\tdetects <- focusModel@data[ , meta$detect]\n\tefforts <- focusModel@data[ , meta$effort]\n\t\n\t# output stats\n\ttotalSamples <- (meta$niter - meta$nburnin) / meta$thin\n\ttotalParams <- nrow(mcmc$summary$all.chains)\n\tproportConverged <- sum(mcmc$summary$all.chains[ , 'rhat'] < rhat, na.rm=TRUE) / totalParams\n\t\n\tstats <- data.frame(\n\t\n\t\ttotalCounties = nrow(focusModel),\n\t\toccupiedCounties = sum(detects > 0, na.rm=TRUE),\n\t\tcountiesWithNonZeroEffort = sum(efforts > 0, na.rm=TRUE),\n\t\tmeanDetectsToEfforts = mean(detects / efforts, na.rm=TRUE),\n\t\tmaxDetections = max(detects, na.rm=TRUE),\n\t\tmaxEfforts = max(efforts, na.rm=TRUE),\n\t\t\n\t\tmeanPsi = mean(focusModel@data$psi, na.rm=TRUE),\n\t\tmeanPsi95CI = mean(focusModel@data$psi95CI, na.rm=TRUE),\n\t\tmeanP = mean(focusModel@data$p, na.rm=TRUE),\n\t\tmeanP95CI = mean(focusModel@data$p95CI, na.rm=TRUE),\n\t\t\n\t\tniter=meta$niter,\n\t\tnburnin=meta$nburnin,\n\t\tnchains=meta$nchains,\n\t\tthin=meta$thin,\n\t\ttotalSamples=totalSamples,\n\n\t\tproportConverged = proportConverged,\n\t\trhat = rhat,\n\t\ttotalParams = totalParams\n\t\n\t)\n\n\tstats\n\t\n}\n", "meta": {"hexsha": "fdf9a6e31e157128a0de8260fcc1cd929a7eb2be", "size": 1600, "ext": "r", "lang": "R", "max_stars_repo_path": "code/bayesODMStats.r", "max_stars_repo_name": "adamlilith/tropicosMassModeling", "max_stars_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/bayesODMStats.r", "max_issues_repo_name": "adamlilith/tropicosMassModeling", "max_issues_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-10T23:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T23:54:10.000Z", "max_forks_repo_path": "code/bayesODMStats.r", "max_forks_repo_name": "adamlilith/tropicosMassModeling", "max_forks_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1886792453, "max_line_length": 102, "alphanum_fraction": 0.713125, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45236474437683694}} {"text": "#' mph2knots\n#' \n#' Conversion speed from mile per hour in knots.\n#'\n#' @param numeric mph Speed in mile per hour.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords mph2knots\n#' \n#' @export\n#'\n#'\n#'\n#'\nmph2knots<-function(mph)\n{\n return(mph * 0.868976);\n}", "meta": {"hexsha": "1aa544590178d3987ba8112a7e95f71120205599", "size": 341, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mph2knots.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/mph2knots.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/mph2knots.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.05, "max_line_length": 101, "alphanum_fraction": 0.6539589443, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390748, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4516065214499018}} {"text": "MARSSkemcheck <- function(MLEobj) {\n # This checks that the model can be handled by the MARSSkem algorithm\n # Most of this is implementing the restrictions in Summary of Requirements for Degenerate Models in derivation\n MODELobj <- MLEobj$marss\n fixed <- MODELobj$fixed\n free <- MODELobj$free\n par.dims <- attr(MODELobj, \"model.dims\")\n m <- par.dims[[\"x\"]][1]\n n <- par.dims[[\"y\"]][1]\n TT <- par.dims[[\"data\"]][2]\n pseudolim <- 1E-8\n ok <- TRUE\n msg <- NULL\n\n # If TT=2 then kf will break\n if (TT <= 2) {\n msg <- c(msg, \"The number of time steps is <=2.\\nMore than 2 data points are needed to estimate parameters.\\n\")\n ok <- FALSE\n }\n\n ############ Check that if fixed, B is within the unit circle\n for (t in 1:max(dim(free$B)[3], dim(fixed$B)[3])) {\n ifixed <- min(t, dim(fixed$B)[3])\n if (is.fixed(free$B[, , ifixed, drop = FALSE])) { # works on 3D matrices\n # parmat needs MODELobj and par list\n if (is.null(MLEobj$par$B)) tmpparB <- MLEobj$start$B else tmpparB <- MLEobj$par$B\n tmp.MLEobj <- list(marss = MODELobj, par = list(B = tmpparB)) # B is fixed but par might have cols from other times\n parB <- parmat(tmp.MLEobj, \"B\", t = t)$B\n if (!all(abs(Re(eigen(parB, only.values = TRUE)$values)) <= 1)) {\n msg <- c(msg, \" All the eigenvalues of B must be within the unit circle: all(abs(Re(eigen(fixed$B)$values))<=1)\\n\")\n ok <- FALSE\n }\n }\n } # end for over time to check B\n\n ############ Check that if R has 0s, then the corresponding row of A and Z are fixed\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n el <- \"R\"\n # extracts the r=0 rows (or cols)\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n Tmax <- 0\n for (par.test in c(\"R\", \"Z\", \"A\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n\n if (is.null(MLEobj[[\"par\"]])) MLEobj$par <- MLEobj$start\n # Run with MARSSkfss because it has more internal checks and error messages\n MLEobj$kf <- MARSSkfss(MLEobj)\n if (!MLEobj$kf$ok) {\n return(list(ok = FALSE, msg = c(MLEobj$kf$errors, msg)))\n }\n MLEobj$Ey <- MARSShatyt(MLEobj)\n msg.tmp <- NULL\n for (i in 1:TT) {\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , ifixed, drop = FALSE] == 0, 1, all) # fixed rows and 0\n if (any(zero.diags)) {\n II0 <- makediag(as.numeric(zero.diags))\n if (i <= Tmax) {\n for (par.test in c(\"Z\", \"A\")) {\n II <- diag(1, par.dims[[par.test]][2])\n ifree.par <- min(i, dim(free[[par.test]])[3])\n dpart <- sub3D(free[[par.test]], t = ifree.par)\n par.not.fixed <- any(((II %x% II0) %*% dpart) != 0)\n\n if (par.not.fixed) {\n if (par.test == \"Z\") msg <- c(msg, paste(\"t=\", i, \": For method=kem (EM), if an element of the diagonal of R is 0, the corresponding row of Z must be fixed. See MARSSinfo('AZR0').\\n\", sep = \"\"))\n if (par.test == \"A\") msg <- c(msg, paste(\"t=\", i, \": For method=kem (EM), if an element of the diagonal of R is 0, the corresponding row of both A and D must be fixed. See MARSSinfo('AZR0').\\n\", sep = \"\"))\n }\n } # for par.test\n } # if par needs to be tested; don't need to do over all TT just up to Tmax\n\n Z <- parmat(MLEobj, \"Z\", t = i)$Z\n A <- parmat(MLEobj, \"A\", t = i)$A\n Z.R0 <- Z[zero.diags, , drop = FALSE]\n A.R0 <- A[zero.diags, , drop = FALSE]\n y.R0 <- MLEobj$Ey$ytT[zero.diags, i, drop = FALSE]\n y.resid <- y.R0 - Z.R0 %*% MLEobj$kf$xtT[, i, drop = FALSE] - A.R0\n if (any(y.resid > pseudolim)) {\n msg.tmp <- c(msg.tmp, paste(\" Z, A, and y for the R=0 rows at time=\", i, \" do not agree. For the R=0 rows, E(y) must equal Z * E(x) + A.\\n\", sep = \"\"))\n }\n } # any zero.diags\n } # end for loop over time\n if (!is.null(msg)) {\n msg <- c(msg, msg.tmp[1:min(10, length(msg.tmp))]) # error msgs could be really long, only print first 10\n ok <- FALSE\n }\n\n\n ############ Check that II_q^{0} is time constant\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n Tmax <- 0\n for (par.test in c(\"Q\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n II0 <- list()\n for (i in 1:Tmax) {\n for (el in c(\"Q\")) {\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , ifixed, drop = FALSE] == 0, 1, all) # fixed rows\n II0Q <- makediag(as.numeric(zero.diags))\n II0Q <- unname(II0[[el]])\n }\n if (i == 1) {\n II0Q.1 <- II0Q\n } else {\n if (!isTRUE(all.equal(II0Q, II0Q.1))) {\n msg <- c(msg, paste(\"t=\", i, \": The placement of 0 variances in Q must be time constant.\\n\", sep = \"\"))\n ok <- FALSE\n }\n }\n } # end for loop over time\n\n\n ############ Check that if R and Q both have 0s, then the U and Bs are appropriately fixed\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n Tmax <- 0\n for (par.test in c(\"R\", \"Q\", \"U\", \"B\", \"Z\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n II0 <- list()\n for (i in 1:Tmax) {\n for (el in c(\"R\", \"Q\")) {\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , ifixed, drop = FALSE] == 0, 1, all) # fixed rows\n II0[[el]] <- makediag(as.numeric(zero.diags))\n }\n for (el in c(\"B\", \"U\")) {\n ifree <- min(i, dim(free[[el]])[3])\n # I don't know what par$Z will be. I want to create a par$Z where there is a non-zero value for any potentially non-zero Z's\n tmp.MLEobj <- list(marss = MODELobj, par = list(Z = matrix(1, dim(free$Z)[2], 1)))\n tmp.MLEobj$marss$fixed$Z[tmp.MLEobj$marss$fixed$Z != 0] <- 1\n tmp.MLEobj$marss$free$Z[tmp.MLEobj$marss$free$Z != 0] <- 1\n parZ <- parmat(tmp.MLEobj, \"Z\", t = i)$Z\n II <- diag(1, par.dims[[el]][2])\n\n dpart <- sub3D(free[[el]], t = ifree)\n par.not.fixed <- any(((II %x% (II0$R %*% parZ %*% II0$Q)) %*% dpart) != 0)\n\n if (par.not.fixed) {\n msg <- c(msg, paste(\"t=\", i, \": For method=kem (EM), if an element of the diagonal of R & Q is 0, the corresponding row of \", par.test, \" must be fixed.\\n\", sep = \"\"))\n ok <- FALSE\n }\n } # for par.test\n } # end for loop over time\n\n ############ Check that B^{0} is fixed\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n Tmax <- 0\n for (par.test in c(\"B\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n II0 <- list()\n for (i in 1:Tmax) {\n for (el in c(\"Q\")) {\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , ifixed, drop = FALSE] == 0, 1, all) # fixed rows\n II0[[el]] <- makediag(as.numeric(zero.diags))\n }\n for (el in c(\"B\")) {\n ifree <- min(i, dim(free[[el]])[3])\n II <- diag(1, par.dims[[el]][2])\n dpart <- sub3D(free[[el]], t = ifree)\n par.not.fixed <- any(((II %x% II0$Q) %*% dpart) != 0)\n\n if (par.not.fixed) {\n msg <- c(msg, paste(\"t=\", i, \": If an element of the diagonal of Q is 0, the corresponding row and col of \", par.test, \" must be fixed.\\n\", sep = \"\"))\n ok <- FALSE\n }\n } # for par.test\n } # end for loop over time\n\n\n ############ Check that if u^{0} or xi^{0} are estimated, B adjacency matrix is time invariant\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n Tmax <- 0\n for (par.test in c(\"U\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n II0 <- list()\n el <- \"Q\"\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , 1, drop = FALSE] == 0, 1, all) # fixed rows\n II0[[el]] <- makediag(as.numeric(zero.diags))\n\n dpart <- sub3D(free$x0, t = 1)\n test.adj <- any((II0$Q %*% dpart) != 0)\n for (i in 1:Tmax) {\n dpart <- sub3D(free$U, t = 1)\n test.adj <- test.adj & any((II0$Q %*% dpart) != 0) # II0$Q required to be time constant above\n }\n\n if (test.adj) { # means x0^{0} or u^{0} being estimated\n Tmax <- 0\n for (par.test in c(\"U\", \"B\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n for (i in 1:Tmax) {\n el <- \"B\"\n ifree <- min(i, dim(free[[el]])[3])\n # I don't know what par$B will be. I want to create a par$B where there is a non-zero value for any potentially non-zero B's\n tmp.MLEobj <- list(marss = MODELobj, par = list(B = matrix(1, dim(free$B)[2], 1)))\n tmp.MLEobj$marss$fixed[[el]][tmp.MLEobj$marss$fixed[[el]] != 0] <- 1\n tmp.MLEobj$marss$free[[el]][tmp.MLEobj$marss$free[[el]] != 0] <- 1\n adjB <- parmat(tmp.MLEobj, el, t = i)[[el]]\n adjB[adjB != 0] <- 1\n adjB <- unname(adjB)\n if (i == 1) {\n adjB.1 <- adjB\n } else {\n if (!isTRUE(all.equal(adjB, adjB.1))) {\n msg <- c(msg, paste(\"t=\", i, \": If u^{0} or xi^{0} are estimated, the adjacency matrix specified by B must be time constant.\\n\", sep = \"\"))\n ok <- FALSE\n }\n }\n } # end for loop over time\n } # if the adj test needs to be done\n\n ############ Check that II_q^{d} and II_q^{is} are time constant\n # See Summary of Requirements for Degenenate Models in EMDerivations.pdf\n Tmax <- 0\n for (par.test in c(\"Q\")) {\n Tmax <- max(Tmax, dim(fixed[[par.test]])[3], dim(free[[par.test]])[3])\n }\n IIz <- IIp <- OMGz <- OMGp <- IId <- IIis <- list()\n for (i in 1:Tmax) {\n el <- \"Q\"\n ifixed <- min(i, dim(fixed[[el]])[3])\n ifree <- min(i, dim(free[[el]])[3])\n diag.rows <- 1 + 0:(par.dims[[el]][1] - 1) * (par.dims[[el]][1] + 1)\n zero.diags <- is.fixed(free[[el]][diag.rows, , ifree, drop = FALSE], by.row = TRUE) & apply(fixed[[el]][diag.rows, , ifixed, drop = FALSE] == 0, 1, all) # fixed rows\n IIz[[el]] <- makediag(as.numeric(zero.diags))\n IIp[[el]] <- diag(1, par.dims[[el]][1]) - IIz[[el]]\n OMGz[[el]] <- diag(1, par.dims[[el]][1])[diag(IIz[[el]]) == 1, , drop = FALSE]\n OMGp[[el]] <- diag(1, par.dims[[el]][1])[diag(IIp[[el]]) == 1, , drop = FALSE]\n\n # I don't know what par$B will be. I want to create a par$B where there is a non-zero value for any potentially non-zero B's\n tmp.MLEobj <- list(marss = MODELobj, par = list(B = matrix(1, dim(free$B)[2], 1)))\n tmp.MLEobj$marss$fixed$B[tmp.MLEobj$marss$fixed$B != 0] <- 1\n tmp.MLEobj$marss$free$B[tmp.MLEobj$marss$free$B != 0] <- 1\n Adj.mat <- parmat(tmp.MLEobj, \"B\", t = i)$B\n Adj.mat[Adj.mat != 0] <- 1\n Adj.mat <- unname(Adj.mat)\n Adj.mat.pow.m <- matrix.power(Adj.mat, m) # to find all the linkages\n\n Q.0.rows.of.Adj.mat <- OMGz[[el]] %*% Adj.mat.pow.m\n # These are the columns corresponding to the directly stochastic bit: Q.0.rows.of.Adj.mat%*%t(OMGp$Q)\n if (dim(OMGp[[el]])[1] != 0) {\n tmp <- Q.0.rows.of.Adj.mat\n # which rows of the + columns are all zero\n if (dim(Q.0.rows.of.Adj.mat)[1] != 0) tmp <- apply(Q.0.rows.of.Adj.mat %*% t(OMGp[[el]]) == 0, 1, all)\n tmp <- t(OMGz[[el]]) %*% matrix(as.numeric(tmp), ncol = 1) # expand back outl 1s where the deterministic x's are\n IId[[el]] <- makediag(tmp)\n IId[[el]] <- unname(IId[[el]])\n IIis[[el]] <- diag(1, m) - IId[[el]] - IIp[[el]]\n IIis[[el]] <- unname(IIis[[el]])\n } else { # Q all 0\n IId[[el]] <- diag(1, par.dims[[el]][1])\n IIis[[el]] <- diag(0, par.dims[[el]][1])\n }\n if (i == 1) {\n IId.1 <- IId[[el]]\n IIis.1 <- IIis[[el]]\n } else {\n if (!isTRUE(all.equal(IId[[el]], IId.1))) {\n msg <- c(msg, paste(\"t=\", i, \": The location of the deterministic x's must be time constant.\\n\", sep = \"\"))\n ok <- FALSE\n }\n if (!isTRUE(all.equal(IIis[[el]], IIis.1))) {\n msg <- c(msg, paste(\"t=\", i, \": The location of the indirectly stochastic x's must be time constant.\\n\", sep = \"\"))\n ok <- FALSE\n }\n }\n } # end for loop over time\n\n return(list(ok = ok, msg = msg))\n}\n", "meta": {"hexsha": "03b270e930abb9f403f79e3f7918af801fb8c276", "size": 12815, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MARSSkemcheck.r", "max_stars_repo_name": "clward/MARSS", "max_stars_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-01T00:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T00:14:40.000Z", "max_issues_repo_path": "R/MARSSkemcheck.r", "max_issues_repo_name": "clward/MARSS", "max_issues_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/MARSSkemcheck.r", "max_forks_repo_name": "clward/MARSS", "max_forks_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6515679443, "max_line_length": 217, "alphanum_fraction": 0.5507608272, "num_tokens": 4565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4515958347450584}} {"text": "\n # ----------------------------------------------------------------------------------------------\n # predict the maturity of crabs based upon determined data\n # ----------------------------------------------------------------------------------------------\n\n predictmaturity = function(x, method=\"DFA\") {\n # codes\n\n # sex codes\n male = 0\n female = 1\n sex.unknown = 2\n\n # maturity codes\n immature = 0\n mature = 1\n mat.unknown = 2\n\n\n # basic biological limits\n x$mat[ which( x$cw<50 ) ] = immature\n x$mat[ which( x$cw>150 ) ] = mature\n\n # males: order is important .. last is most imperative\n x$mat[ which( x$sex == male & x$shell %in% c(4,5)) ] = mature\n x$mat[ which( x$sex == male & x$cw < 50) ] = immature\n x$mat[ which( x$sex == male & x$cw > 150) ] = mature\n x$mat[ which( x$sex == male & x$chela < 5) ] = immature\n x$mat[ which( x$sex == male & x$chela > 33) ] = mature\n\n # female: sequence is important .. last is most imperative\n x$mat[ which( x$sex == female & x$shell %in% c(4,5)) ] = mature\n x$mat[ which( x$sex == female & x$cw < 30) ] = immature\n x$mat[ which( x$sex == female & x$cw > 80) ] = mature\n x$mat[ which( x$sex == female & x$abdomen < 20) ] = immature\n x$mat[ which( x$sex == female & x$abdomen > 50) ] = mature\n x$mat[ which( x$sex == female & x$gonad %in% c(1,2,3) )] = immature\n x$mat[ which( x$sex == female & x$eggPr == 0 )] = immature\n x$mat[ which( x$sex == female & x$eggPr %in% c(1:4) )] = mature # berried females\n x$mat[ which( x$sex == female & x$eggcol %in% c(1,2,3,4) )] = mature\n\n if (method==\"DFA\") {\n # males\n test.male = -25.32404 * log(x$cw) + 19.775707 * log(x$chela) + 56.649941\n x$mat[ which(x$sex==male & test.male <= 0 ) ] = immature\n x$mat[ which(x$sex==male & test.male > 0 ) ] = mature\n # females\n test.female = 16.422757 * log(x$cw) - 14.756163 * log(x$abdomen) - 14.898721\n x$mat[ which(x$sex==female & test.female > 0 ) ] = immature\n x$mat[ which(x$sex==female & test.female <= 0) ] = mature\n }\n\n if (method==\"logistic.regression\") {\n require(mgcv)\n\n ##TODO- need to add a final step for animals without a SC. Maybe revert to DFA method for these only?\n\n x$rs = NA\n x$mat.predicted = NA\n\n WW = which( x$mat %in% c(immature, mature) )\n MM = which( x$sex==male )\n FF = which( x$sex==female )\n SC = which( x$shell %in% 1:5 )\n cleandata_mm = which( x$cw > 0 & x$chela > 0 )\n cleandata_ff = which( x$cw > 0 & x$abdomen > 0 )\n\n x$mat = as.factor(x$mat)\n x$sex = as.factor(x$sex)\n # x$shell = as.factor(x$shell)\n\n imm = intersect( intersect( intersect( MM, WW ), SC ), cleandata_mm )\n iff = intersect( intersect( intersect( FF, WW ), SC ), cleandata_ff )\n\n modm1 = glm( mat ~ log(cw) + log(chela) + shell, data=x[imm,], family=binomial(link=\"logit\") )\n modf1 = glm( mat ~ log(cw) + log(abdomen) + shell, data=x[iff,], family=binomial(link=\"logit\") )\n\n x$rs[imm] = residuals( modm1 )\n x$rs[iff] = residuals( modf1 )\n\n # reject too large a residual variability\n rs3 = which( abs(x$rs) > 1.96 ) # reject too large a residual variability -- log-scaled ... residual =1 is large\n # these have potentially problematic data inputs in either cw and/or chela. etc\n # assume CW is OK and set all other data in the main dataset to uncertain/missing\n x$chela[rs3] = NA\n x$abdomen[rs3] = NA\n\n\n # update data vectors removing \"bad\" data and redo model\n cleandata_mm = which( x$cw > 0 & x$chela > 0 )\n cleandata_ff = which( x$cw > 0 & x$abdomen > 0 )\n imm = intersect( intersect( intersect( MM, WW ), SC ), cleandata_mm )\n iff = intersect( intersect( intersect( FF, WW ), SC ), cleandata_ff )\n\n modm1 = glm( mat ~ log(cw) + log(chela) + shell, data=x[imm,], family=binomial(link=\"logit\") )\n modf1 = glm( mat ~ log(cw) + log(abdomen) + shell, data=x[iff,], family=binomial(link=\"logit\") )\n\n\n # require( boot ) # inv.logit\n # plot( modm1, trans=inv.logit, rug=T, jit=T, scale=0 )\n # plot( modf1, trans=inv.logit, rug=T, jit=T, scale=0 )\n\n \n # update data vectors removing \"bad\" data and redo model\n cleandata_mm = which( x$cw > 0 & x$chela > 0 )\n cleandata_ff = which( x$cw > 0 & x$abdomen > 0 )\n imm = intersect( intersect( intersect( MM, WW ), SC ), cleandata_mm )\n iff = intersect( intersect( intersect( FF, WW ), SC ), cleandata_ff )\n\n modm1 = glm( mat ~ log(cw) + log(chela) + shell, data=x[imm,], family=binomial(link=\"logit\") )\n modf1 = glm( mat ~ log(cw) + log(abdomen) + shell, data=x[iff,], family=binomial(link=\"logit\") )\n\n # identify inds without maturity indications\n WW = which( !(x$mat %in% c(immature, mature) ) )\n imm = intersect( intersect( intersect( MM, WW ), SC ), cleandata_mm )\n iff = intersect( intersect( intersect( FF, WW ), SC ), cleandata_ff )\n\n x$mat.predicted[imm] = ifelse( predict( modm1, x[imm,], type=\"response\" ) < 0.5, immature, mature )\n x$mat.predicted[iff] = ifelse( predict( modf1, x[iff,], type=\"response\" ) < 0.5, immature, mature )\n\n x$mat[imm] = x$mat.predicted[imm]\n x$mat[iff] = x$mat.predicted[iff]\n\n#animals without shell did not get assigned mat through models to this point so...\n cleandata_mm = which( x$cw > 0 & x$chela > 0 )\n cleandata_ff = which( x$cw > 0 & x$abdomen > 0 )\n NoC= which( is.na(x$shell)) #individuals w/o shell condition\n WW = which( !(x$mat %in% c(immature, mature) ) ) #individuals w/o maturity indications\n\n imm = intersect( intersect( intersect( MM, WW ), NoC ), cleandata_mm )\n iff = intersect( intersect( intersect( FF, WW ), NoC ), cleandata_ff )\n\n modm1 = glm( mat ~ log(cw) + log(chela), data=x[imm,], family=binomial(link=\"logit\") )\n modf1 = glm( mat ~ log(cw) + log(abdomen) , data=x[iff,], family=binomial(link=\"logit\") )\n\n x$mat.predicted[imm] = ifelse( predict( modm1, x[imm,], type=\"response\" ) < 0.5, immature, mature )\n x$mat.predicted[iff] = ifelse( predict( modf1, x[iff,], type=\"response\" ) < 0.5, immature, mature )\n\n x$mat[imm] = x$mat.predicted[imm]\n x$mat[iff] = x$mat.predicted[iff]\n\n\n x$rs = NULL\n x$mat.predicted = NULL\n\n\n }\n\n return(x)\n }\n\n\n", "meta": {"hexsha": "563e18a5280c471a657764a24ffaf519a829c28a", "size": 6381, "ext": "r", "lang": "R", "max_stars_repo_path": "R/predictmaturity.r", "max_stars_repo_name": "jae0/snowcrab", "max_stars_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/predictmaturity.r", "max_issues_repo_name": "jae0/snowcrab", "max_issues_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/predictmaturity.r", "max_forks_repo_name": "jae0/snowcrab", "max_forks_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:57:48.000Z", "avg_line_length": 41.7058823529, "max_line_length": 120, "alphanum_fraction": 0.5663689077, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45143930486096345}} {"text": "#' Mean pairwise distance\n#' \n#' @param comm Community matrix giving sites (rows) by species (columns). Column names should match the\n#' names in the phylogeny\n#' @param phylogeny Phylogeny in the format used by \\code{\\link{ape}}; if missing dis is required\n#' @param dis Species distance matrix; if missing will be extracted from the phylogeny\n#' @param dis.transform Function (e.g., sqrt) to transform distance before computing mpd\n#' @details Computes mean pairwise distance (MPD) for all site pairs (including within and between site MPD)\n#' @return Matrix of pairwise distances; diagonal is witin site (alpha) MPD, other values are pairwise distances (beta MPD)\n#' @useDynLib mbm c_mpd\n#' @export\nmpd <- function(comm, phylogeny, dis, dis.transform)\n{\n\tif(missing(dis))\n\t{\n\t\tif(missing(phylogeny)) stop(\"Either phylogeny or dis matrix must be specified\")\n\t\tdis <- cophenetic(phylogeny)\n\t} else {\n\t\t# do some error checking\n\t\tif((nrow(dis) != ncol(dis)) | any((colnames(dis) != rownames(dis))))\n\t\t\tstop(\"dis must be square with identical row and column names\")\n\t}\n\n\t# make sure all species in comm and in dis match\n\ttaxa <- sort(intersect(colnames(comm), rownames(dis)))\n\tif(length(taxa) < ncol(comm)) \n\t\twarning(ncol(comm) - length(taxa), \" taxa were dropped from comm because they were not in dis\")\n\tif(length(taxa) < nrow(dis))\n\t\twarning(nrow(dis) - length(taxa), \" taxa were dropped from dis because they were not in comm\")\n\tdis <- dis[taxa, taxa]\n\tcomm <- comm[,taxa]\n\t\n\tif(! missing(dis.transform))\n\t\tdis <- dis.transform(dis)\n\t\n\tspMat <- which(comm > 0, arr.ind = TRUE)\n\tspMat <- spMat[order(spMat[,1]),]\n\tsites = spMat[,1] - 1\t# subtract one from indices because C is 0 indexed\n\tspecies = spMat[,2] - 1\n\tcDist <- numeric(nrow(comm)^2)\n\tres <- .C(\"c_mpd\", species=as.integer(species), sites=as.integer(sites), N=as.integer(length(sites)), \n\t\tdist=as.double(dis), K=as.integer(nrow(dis)), dest=as.double(cDist), S=as.integer(nrow(comm)))\n\tmatrix(res$dest, nrow=nrow(comm), ncol=nrow(comm), dimnames=list(rownames(comm), rownames(comm)))\n}\n\n", "meta": {"hexsha": "5f63e7c08003b8795efa11c7e41bb8d63b0077f9", "size": 2068, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mpd.r", "max_stars_repo_name": "mtalluto/mbmtools", "max_stars_repo_head_hexsha": "67a01b24ba2bc214081085559500e7b16f8489f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/mpd.r", "max_issues_repo_name": "mtalluto/mbmtools", "max_issues_repo_head_hexsha": "67a01b24ba2bc214081085559500e7b16f8489f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-19T11:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T10:08:48.000Z", "max_forks_repo_path": "R/mpd.r", "max_forks_repo_name": "mtalluto/mbmtools", "max_forks_repo_head_hexsha": "67a01b24ba2bc214081085559500e7b16f8489f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-25T20:28:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T20:28:51.000Z", "avg_line_length": 44.9565217391, "max_line_length": 123, "alphanum_fraction": 0.7006769826, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4512022599178596}} {"text": "\n\n\n#################\n### SH functions\n#################\n\n#' Wrapper function for limitless regression discontinuity testing and estimation\n#'\n#' In a regression discontinuity design, this function tests for an effect using \\code{testSH},\n#' and inverts the test to estimate a confidence interval and Hodges-Lehmann point estimate.\n#' The test is the test associated with the Z coefficient after fitting\n#' a model from the robustbase suite that uses Z and R as independent variables.\n#' Covariance adjustment is via robust logistic regression if\n#' ytilde is binary, robust linear regression otherwise. In the latter case,\n#' since we're using `robustbase::lmrob` with the `MM` method, the SE used\n#' in the test is of the Huber-White type, allowing for heteroskedasticity\n#' and accounting for propagation of errors from the preliminary fitting\n#' done by the robust regression routine.\n#'\n#' This is the method recommended in version 2 of Limitless\n#' Regression Discontinuity\n#'\n#' @param dat Data set with columns \\code{Z}, \\code{R}, an outcome variable, and (optionally)\n#' an indicator for treatment received, in the case of partial compliance.\n#' @param BW An optional bandwidth \\code{b>0}. The test uses data for subjects with |R|0 & dat$R2)\n mod <- lm(form,dat=dat)\n else mod <- glm(form,dat=dat,family=binomial)\n vcv <- sandwich::sandwich(mod)\n Z.pos.c <- pmatch(\"Z\", names(coef(mod)))\n Z.pos.v <- pmatch(\"Z\", colnames(vcv))\n tstat <- coef(mod)[Z.pos.c]/sqrt(vcv[Z.pos.v, Z.pos.v])\n 2 * pt(-abs(tstat), df=mod$df.residual, lower.tail=T)\n}\n\n\n#' Robust balance test following robust covariate adjustment\n#'\n#' The test is the test associated with the Z coefficient after fitting\n#' a model from the robustbase suite that uses Z and R as independent variables.\n#' Covariance adjustment is via robust logistic regression if\n#' ytilde is binary, robust linear regression otherwise. In the latter case,\n#' since we're using `robustbase::lmrob` with the `MM` method, the SE used\n#' in the test is of the Huber-White type, allowing for heteroskedasticity\n#' and accounting for propagation of errors from the preliminary fitting\n#' done by the robust regression routine.\n#'\n#' This is the method recommended in version 2 of Limitless\n#' Regression Discontinuity\n#'\n#' @param dat Data set with columns \\code{Z}, \\code{R}, and an outcome variable\n#' @param BW A bandwidth \\code{b>0}. The test uses data for subjects with |R|0 & dat$R0}. The test uses data for subjects with |R|0}. The test uses data for subjects with |R|0}. If not provided it will be estimated from the\n#' data\n#' @param outcome A string specifying the name of the outcome variable\n#'\n#' @return a list consisting of\n#' \\describe{\n#' \\item{p.value} The p-value testing no effect\n#' \\item{CI} a vector of confidence limits and the HL treatment effect\n#' \\item{BW} the RDD bandwidth\n#' \\item{bal.pval} a p-value testing for covariate balance\n#' \\item{n} the number of subjects in the window of analysis\n#' \\item{W} the range of R values in the window of analysis\n#' }\n#' @import rdd\n#' @export\n\nik <- function(dat,BW=NULL,outcome){\n mod <- ikTest(dat,BW,varb=outcome,justP=FALSE)\n BW <- mod$bw[1]\n bal.pval=balMult(dat=dat,BW=BW,method='sh',reduced.covars=FALSE)\n list(p.value=mod$p[1],CI=c(mod$ci[1,],est=mod$est[1]),bal.pval=bal.pval,\n W=c(min(abs(dat$R)),BW),n=sum(abs(dat$R)0}. If not provided it will be\n#' estimated from the data\n#' @param varb A string specifying the name of the outcome or covariate variable\n#' @param rhs Ignored\n#' @param justP if TRUE only returns the p-value\n#'\n#' @return if justP=TRUE, returns the p-value for an effect. if justP=FALSE,\n#' returns the fitted RDD model (an object of class \"RD\").\n#' @import rdd\n#' @export\n\nikTest <- function(dat,BW=NULL,varb,rhs=NULL,justP=TRUE,cutpoint=-0.005){\n if(!missing(varb)) dat$Y <- -dat[[varb]]\n if(missing(BW) | is.null(BW))\n mod <- try(RDestimate(Y~R,kernel='rectangular',\n data=dat,cutpoint=cutpoint))\n else mod <- try(RDestimate(Y~R,kernel='rectangular',\n data=dat,bw=BW,cutpoint=cutpoint))\n if(class(mod)=='try-error') return(rep(NA,ifelse(justP,1,5)))\n if(justP) return(mod$p[1])\n mod\n}\n\nikMultBal <- function(dat,BW,xvars,int=FALSE){\n require(systemfit)\n xeq <- if(int) lapply(xvars,function(xx) as.formula(paste0(xx,'~R+Z+R:Z'))) else\n lapply(xvars,function(xx) as.formula(paste0(xx,'~R+Z')))\n names(xeq) <- gsub('_','',xvars)\n\n sur <- systemfit(xeq,data=subset(dat,abs(R)0}. If not provided it will be estimated from the data\n##' @param outcome A string specifying the name of the outcome or covariate variable\n##' @param alpha 1-confidence interval level\n##' @param rhs Ignored\n##' @return list of\n##' \\describe{\n##' \\item{p.value} of Fisher-style no effect hypothesis\n##' \\item{CI} vector of confidence limits, estimate\n##' \\item{bal.pval} balance p-value\n##' \\item{n} number of observations inselected window\n##' \\item{W} window\n##' }\n##' @author lrd author 1\n##' @export\ncft <- function(dat,BW,outcome,alpha=0.05,rhs=NULL){\n if(missing(BW) |is.null(BW))\n BW <- bwMult(dat,balMult.control=list(method='cft',reduced.covars=FALSE))\n\n if(sum(dat$R<0 & -BW0 & dat$R0 & dat$Ralphax))]\n}\n\n\n\n#' Choose a bandwidth using one of several methods\n#'\n#' Method options include Limitless, a permutation-testing method, or the IK method\n#'\n#' @param dat a data.frame. must contain variables `R` (the running variable) and `Z`\n#' (treatment) and, if method='ik', `Y` (outcome) along with these covariates: 'lhsgrade_pct',\n#' 'totcredits_year1','male','loc_campus1','loc_campus2','bpl_north_america','english',\n#' and 'age'\n#' @param alpha the level of the balance test\n#' @param newbal.control list of optional arguments to `newBal`\n#' @param bsw numeric, a sequence of bandwidths to try (in increasing order)\n#'\n#' @return bandwidth choice (scalar)\n#' @export\nbwMult <- function(dat,alpha=0.15,balMult.control=list(method='sh',reduced.covars=FALSE), bws = seq(0,2,0.01)){\n stopifnot(is.list(balMult.control),\n !any(c('dat', 'BW') %in% names(balMult.control)),\n is.numeric(bws) && all(bws >=0),\n length(bws)==1 || !is.unsorted(bws))\n short <- function(w) {\n nbargs <- c(list(dat=dat, BW=w), balMult.control)\n try(do.call(balMult, nbargs))\n }\n\n p <- 0\n i <- length(bws)+1\n while(pcutoff],na.rm=TRUE)\n rminus <- max(R[R