{"text": "library(\"coda\")\n\n# posterior distribution of converged chain \nset.seed(61)\npost0 = mh(n=n, ybar=ybar, n_iter=10e3, mu_init=0.0, cand_sd=0.9)\ntraceplot(as.mcmc(post0$mu[-c(1:500)]))\n\n# posterior distribution of wondering chain \npost1 = mh(n=n, ybar=ybar, n_iter=1e3, mu_init=0.0, cand_sd=0.04)\ntraceplot(as.mcmc(post1$mu[-c(1:500)]))\n\n# posterior distribution wondering chain converged \npost2 = mh(n=n, ybar=ybar, n_iter=100e3, mu_init=0.0, cand_sd=0.04)\ntraceplot(as.mcmc(post2$mu))\n\n# effective sample size - number of independent MC samples (more = greater information)\n\n# effective sample size how many indipendent sampe needed to get the same information\n\n# want chain with low auto correaltion - good converging properties - good chain \n\n# need to check the effective sample size - relyable estimates need a high number of effective sample size \n\n# a chain with high auto correaltion will lead to more sampling to get a good (significant) effective sample\n\n# lesson - drawing from a population who are correlated will take longer to understand the entire distribution\n\nautocorr.plot(as.mcmc(post0$mu))\nautocorr.diag(as.mcmc(post0$mu))\n\nautocorr.plot(as.mcmc(post1$mu))\nautocorr.diag(as.mcmc(post1$mu))\n\nstr(post2)\n\neffectiveSize(as.mcmc(post2$mu)) \n\nautocorr.plot(as.mcmc(post2$mu), lag.max=500)\n\nthin_interval = 400 # how far apart the iterations are for autocorrelation to be essentially 0.\nthin_indx = seq(from=thin_interval, to=length(post2$mu), by=thin_interval)\nhead(thin_indx)\n\npost2mu_thin = post2$mu[thin_indx]\ntraceplot(as.mcmc(post2$mu))\n\ntraceplot(as.mcmc(post2mu_thin))\n\nautocorr.plot(as.mcmc(post2mu_thin), lag.max=10)\n\neffectiveSize(as.mcmc(post0$mu))\n\n?effectiveSize\n\nraftery.diag(as.mcmc(post0$mu))\n\nraftery.diag(as.mcmc(post0$mu), q=0.005, r=0.001, s=0.95)", "meta": {"hexsha": "76690e47550bf9e6c66bc6e5adefea3e0ce244f3", "size": 1779, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/autocorrelation.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/autocorrelation.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/autocorrelation.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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.2105263158, "max_line_length": 110, "alphanum_fraction": 0.7599775155, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6998588062054218}} {"text": "## 2. Useful Qualities of Probability Distributions ##\n\nare_uniforms <- FALSE\nmost_probable_A <- 1\ntotal_probability_B <- 0.2 + 0.2 + 0.2 + 0.2 + 0.3\nis_B_valid <- FALSE\n\n## 4. Example: Sum of Two Dice Rolls ##\n\nprob_2 <- 1/36\nprob_4 <- 3/36\nprob_7 <- 6/36\nprob_10 <- prob_4\n\n## 5. Cumulative Probability ##\n\nprob_leq_6 <- 1/36 + 2/36 + 3/36 + 4/36 + 5/36\nprob_gt_9 <- 6/36\nprob_btwn_6_and_8 <- 5/36 + 6/36 + 5/36\n\n## 8. Probability Distribution Function for the Normal ##\n\nprob_norm_0 <- dnorm(0)\nprob_norm_5 <- dnorm(5, 5, 5)\nprob_norm_1 <- dnorm(-1, 1, 2)", "meta": {"hexsha": "fea86b30afd2d4ffec16ab8d6fc75cb0c4bd10e7", "size": 558, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/5. Hypothesis Testing in R/1. Probability Distributions.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/5. Hypothesis Testing in R/1. Probability Distributions.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "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 Analyst in R/Step 5 - Probability and Statistics/5. Hypothesis Testing in R/1. Probability Distributions.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 22.32, "max_line_length": 57, "alphanum_fraction": 0.6594982079, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6992210785738469}} {"text": "n = 600851475143\n\ni = 2\nwhile (n != 1) {\n if (n %% i == 0) {\n n = n / i\n } else {\n i = i + 1\n }\n}\n\ncat(i, \"\\n\")\n", "meta": {"hexsha": "42be4749bb28bd353f09aae1127a59fdc2bad033", "size": 135, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/pe_0003.r", "max_stars_repo_name": "shanedrabing/project-euler", "max_stars_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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/pe_0003.r", "max_issues_repo_name": "shanedrabing/project-euler", "max_issues_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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/pe_0003.r", "max_forks_repo_name": "shanedrabing/project-euler", "max_forks_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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": 10.3846153846, "max_line_length": 22, "alphanum_fraction": 0.3111111111, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6991597540495992}} {"text": "primes <- c(2, 3, 5, 7, 11, 13)\nisPrime <- function(a) {\n i <- 1\n while (a %% primes[i] > 0) {\n if (primes[i] * primes[i] > a) {\n primes <<- append(primes, a)\n return(TRUE)\n }\n i <- i + 1\n }\n FALSE\n}\n\nprimeSeq <- function() {\n p0 <- 1\n i <- 0\n return(function() {\n if (p0 <= length(primes)) {\n i <<- primes[p0]\n p0 <<- p0 + 1\n return(i)\n }\n i <<- i + 2\n while (!isPrime(i)) {\n i <<- i + 2\n }\n p0 <<- p0 + 1\n return(i)\n })\n}\n\nprimeless <- function(n) {\n r <- c()\n nextPrime <- primeSeq()\n i <- nextPrime()\n while (i < n) {\n r <- append(r, i)\n i <- nextPrime()\n }\n paste(r, collapse=\",\")\n}\n\nfor (line in readLines(tail(commandArgs(), n=1))) {\n cat(sapply(as.integer(line), primeless), sep=\"\\n\")\n}\n", "meta": {"hexsha": "d063777270b66733eede5d238e22ae9b3c01104e", "size": 776, "ext": "r", "lang": "R", "max_stars_repo_path": "moderate/prime_less.r", "max_stars_repo_name": "IlkhamGaysin/ce-challenges", "max_stars_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-06-24T17:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-03T11:44:54.000Z", "max_issues_repo_path": "moderate/prime_less.r", "max_issues_repo_name": "IlkhamGaysin/ce-challenges", "max_issues_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "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": "moderate/prime_less.r", "max_forks_repo_name": "IlkhamGaysin/ce-challenges", "max_forks_repo_head_hexsha": "ac6b8c1fc4b6c098e380b9d694e93e614f6c969b", "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": 16.8695652174, "max_line_length": 52, "alphanum_fraction": 0.4652061856, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6991597497683376}} {"text": "# take input from the user\nnterms = as.integer(readline(prompt=\"How many terms? \"))\n# first two terms\nn1 = 0\nn2 = 1\ncount = 2\n# check if the number of terms is valid\nif(nterms <= 0) {\nprint(\"Plese enter a positive integer\")\n} else {\nif(nterms == 1) {\nprint(\"Fibonacci sequence:\")\nprint(n1)\n} else {\nprint(\"Fibonacci sequence:\")\nprint(n1)\nprint(n2)\nwhile(count < nterms) {\nnth = n1 + n2\nprint(nth)\n# update values\nn1 = n2\nn2 = nth\ncount = count + 1\n}\n}\n}", "meta": {"hexsha": "cdce8fbdc0a2a41559f84e8ecab33c67f998b375", "size": 453, "ext": "r", "lang": "R", "max_stars_repo_path": "print_fibonacci_sequence.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "print_fibonacci_sequence.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "print_fibonacci_sequence.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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.7777777778, "max_line_length": 56, "alphanum_fraction": 0.6644591611, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.6988370735710202}} {"text": "require(adehabitat)\r\nrequire(CircStats)\r\n\r\n\"simm.crw2\" <- function(date=1:100, h = 1, r = 0, R=57.5,\r\n x0=c(0,0), id=\"A1\", burst=id,\r\n typeII=TRUE)\r\n {\r\n if (!require(CircStats))\r\n stop(\"package CircStats required\")\r\n if (typeII)\r\n class(date) <- c(\"POSIX\",\"POSIXct\")\r\n n <- length(date)\r\n dt <- c(diff(unclass(date)))\r\n if (all(dt-dt[1]>1e-7))\r\n stop(\"the time lag between relocations should be constant\")\r\n \r\n \r\n if (h>0) {\r\n v=sqrt(dt)*rchi(n-1) * h\r\n } else {\r\n v=dt/dt*(-h)\r\n\t\t\r\n }\r\n\t\tang<-rwrpnorm(n-2,0,r)\r\n ang=cumsum(c(runif(1,0,2*pi),ang))\r\nx=c(1:n)\r\ny=x\r\nx[1]= x0[1]\r\ny[1] =x0[2]\r\nfor (i in c(2: n)){\r\n\t\tx[i]= x[i-1]+v[i-1]*cos(ang[i-1])\r\n\t\ty[i]= y[i-1]+v[i-1]*sin(ang[i-1])\r\n\t\tRR=(x[i]^2+y[i]^2)\r\n\t\tif ((RR> R^2) && (i< (n-1)) ){\r\n\t\t\t\r\n\t\t\tx[i]= R*x[i]/sqrt(RR)\r\n\t\t\ty[i]= R*y[i]/sqrt(RR)\r\n\t\t\tang2<-rwrpnorm(n-2-i,0,r)\r\n\t\t\tang2=cumsum(c(runif(1,0,2*pi),ang2))\r\n\t\t\tj=c(1:(n-i-1))\r\n\t\t\tang[i+j]=ang2[j]\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n res <- as.ltraj(data.frame(x,y),date, id, burst,\r\n typeII=typeII)\r\n return(res)\r\n }\r\n \r\n# \r\n# \r\n# now levy walks!\r\n \r\n simm.levy2 <- function (date = 1:500, mu = 2, l0 = 1, x0 = c(0, 0), id = \"A1\", R=57.5,\r\n \r\n burst = id, typeII = TRUE)\r\n {\r\n if (typeII)\r\n class(date) <- c(\"POSIX\", \"POSIXct\")\r\n n <- length(date)\r\n dt <- c(diff(unclass(date)))\r\n if (all(dt - dt[1] > 1e-07))\r\n stop(\"the time lag between relocations should be constant\")\r\n ang <- runif(n - 2, -pi, pi)\r\n v = dt * (l0 * (runif(n - 1)^(1/(1 - mu))))\r\n ang = cumsum(c(runif(1, 0, 2 * pi), ang))\r\n# newcode \r\n x=c(1:n)\r\n y=x\r\n x[1]= x0[1]\r\n y[1] =x0[2]\r\n for (i in c(2: n)){\r\n \tx[i]= x[i-1]+v[i-1]*cos(ang[i-1])\r\n \t\ty[i]= y[i-1]+v[i-1]*sin(ang[i-1])\r\n \t\tRR=(x[i]^2+y[i]^2)\r\n \t\tif ((RR> R^2) && (i< (n-1)) ){\r\n \t\t\t\r\n \t\t\tx[i]= R*x[i]/sqrt(RR)\r\n \t\t\ty[i]= R*y[i]/sqrt(RR)\r\n \t\t\tang2<-rwrpnorm(n-2-i,0,r)\r\n \t\t\tang2=cumsum(c(runif(1,0,2*pi),ang2))\r\n \t\t\tj=c(1:(n-i-1))\r\n \t\t\tang[i+j]=ang2[j]\r\n \r\n \t\t\t}\r\n \t\t}\r\n res <- as.ltraj(data.frame(co, si), date, id, burst, typeII = typeII)\r\n return(res)\r\n }\r\n \r\n simm.levycorr <- function (date = 1:500, mu = 2, l0 = 1, x0 = c(0, 0), id = \"A1\", R=57.5,r=0.6,\r\n \r\n burst = id, typeII = TRUE)\r\n {\r\n if (typeII)\r\n class(date) <- c(\"POSIX\", \"POSIXct\")\r\n n <- length(date)\r\n dt <- c(diff(unclass(date)))\r\n if (all(dt - dt[1] > 1e-07))\r\n stop(\"the time lag between relocations should be constant\")\r\n ang<-rwrpnorm(n-2,0,r)\r\n ang=cumsum(c(runif(1,0,2*pi),ang))\r\n v = dt * (l0 * (runif(n - 1)^(1/(1 - mu))))\r\n \r\n # newcode \r\n x=c(1:n)\r\n y=x\r\n x[1]= x0[1]\r\n y[1] =x0[2]\r\n for (i in c(2: n)){\r\n x[i]= x[i-1]+v[i-1]*cos(ang[i-1])\r\n \t\ty[i]= y[i-1]+v[i-1]*sin(ang[i-1])\r\n \t\tRR=(x[i]^2+y[i]^2)\r\n \t\tif ((RR> R^2) && (i< (n-1)) ){\r\n \t\t\t\r\n \t\t\tx[i]= R*x[i]/sqrt(RR)\r\n \t\t\ty[i]= R*y[i]/sqrt(RR)\r\n \t\t\tang2<-rwrpnorm(n-2-i,0,r)\r\n ang2=cumsum(c(runif(1,0,2*pi),ang2))\r\n \t\t\tj=c(1:(n-i-1))\r\n \t\t\tang[i+j]=ang2[j]\r\n \r\n \t\t\t}\r\n \t\t}\r\n res <- as.ltraj(data.frame(co, si), date, id, burst, typeII = typeII)\r\n return(res)\r\n }\r\n \r\n \"simm.crw2pauses\" <- function(date=1:100, h = 1, r = 0, R=57.5,\r\n x0=c(0,0), id=\"A1\", burst=id,\r\n typeII=TRUE,act =0.5)\r\n {\r\n if (!require(CircStats))\r\n stop(\"package CircStats required\")\r\n if (typeII)\r\n class(date) <- c(\"POSIX\",\"POSIXct\")\r\n n <- length(date)\r\n dt <- c(diff(unclass(date)))\r\n if (all(dt-dt[1]>1e-7))\r\n stop(\"the time lag between relocations should be constant\")\r\n #activity of probability 1-ttt\r\n t= runif(n - 1,0,1)\r\n t\r\n t=ifelse(t>act,1,0)\r\n t\r\n \r\n if (h>0) {\r\n v=sqrt(dt)*rchi(n-1) * h*t\r\n } else {\r\n v=dt/dt*(-h)*t\r\n \t\r\n }\r\n \t\tang<-rwrpnorm(n-2,0,r)\r\n ang=cumsum(c(runif(1,0,2*pi),ang))\r\n x=c(1:n)\r\n y=x\r\n x[1]= x0[1]\r\n y[1] =x0[2]\r\n for (i in c(2: n)){\r\n \t\tx[i]= x[i-1]+v[i-1]*cos(ang[i-1])\r\n \t\ty[i]= y[i-1]+v[i-1]*sin(ang[i-1])\r\n \t\tRR=(x[i]^2+y[i]^2)\r\n \t\tif ((RR> R^2) && (i< (n-1)) ){\r\n \t\t\t\r\n \t\t\tx[i]= R*x[i]/sqrt(RR)\r\n \t\t\ty[i]= R*y[i]/sqrt(RR)\r\n \t\t\tang2<-rwrpnorm(n-2-i,0,r)\r\n \t\t\tang2=cumsum(c(runif(1,0,2*pi),ang2))\r\n \t\t\tj=c(1:(n-i-1))\r\n \t\t\tang[i+j]=ang2[j]\r\n \r\n \t\t\t}\r\n \t\t}\r\n \r\n \r\n res <- as.ltraj(data.frame(x,y),date, id, burst,\r\n typeII=typeII)\r\n return(res)\r\n }\r\n \r\n simm.levycorrpauses <- function (date = 1:500, mu = 2, l0 = 1, x0 = c(0, 0), id = \"A1\", R=57.5,r=0.6,act=0.5,\r\n \r\n burst = id, typeII = TRUE)\r\n {\r\n if (typeII)\r\n class(date) <- c(\"POSIX\", \"POSIXct\")\r\n n <- length(date)\r\n dt <- c(diff(unclass(date)))\r\n if (all(dt - dt[1] > 1e-07))\r\n stop(\"the time lag between relocations should be constant\")\r\n ang<-rwrpnorm(n-2,0,r)\r\n ang=cumsum(c(runif(1,0,2*pi),ang))\r\n #activity of probability 1-ttt\r\n t= runif(n - 1,0,1)\r\n t\r\n t=ifelse(t>act,1,0)\r\n t\r\n v = t*dt * (l0 * (runif(n - 1)^(1/(1 - mu))))\r\n \r\n # newcode \r\n x=c(1:n)\r\n y=x\r\n x[1]= x0[1]\r\n y[1] =x0[2]\r\n for (i in c(2: n)){\r\n x[i]= x[i-1]+v[i-1]*cos(ang[i-1])\r\n \ty[i]= y[i-1]+v[i-1]*sin(ang[i-1])\r\n \t\tRR=(x[i]^2+y[i]^2)\r\n \t\tif ((RR> R^2) && (i< (n-1)) ){\r\n \t\t\t\r\n \t\t\tx[i]= R*x[i]/sqrt(RR)\r\n \t\t\ty[i]= R*y[i]/sqrt(RR)\r\n \t\t\tang2<-rwrpnorm(n-2-i,0,r)\r\n ang2=cumsum(c(runif(1,0,2*pi),ang2))\r\n \t\t\tj=c(1:(n-i-1))\r\n \t\t\tang[i+j]=ang2[j]\r\n \r\n \t\t\t}\r\n \t\t}\r\n res <- as.ltraj(data.frame(x, y), date, id, burst, typeII = typeII)\r\n return(res)\r\n }\r\n \r\n#############\r\n############\r\n#########\r\n# i=1\r\n# rrr=0.9\r\n# ttt=0.4\r\n# u <- simm.crw2pauses(1:9000, r = rrr, h=0.75, act=ttt,burst =paste(rrr,ttt,i))\r\n# trajdyn(u)\r\n# plut (sliwinltr(u)\r\n###########\r\n###########\r\n###########\r\n# setwd(\"d:/dokumente/My Dropbox/buridan/buridan_v2.3/simulated_data/simulated_all\")\r\n# \r\n# for (rrr in c(0.8,0.6)) {\r\n# group =ifelse(rrr==0.8,\"corrw_r0.8\",\"corrw_r0.6\")\r\n# for (hhh in c(0.75,1)) {\r\n# group2 =ifelse(hhh==0.75,\"_h0.75\",\"_h1\")\r\n# for (i in 0:9){\r\n# set.seed(872+i)\r\n# \r\n# u <- simm.crw2(1:9000, r = rrr, h=hhh, burst =paste(rrr,hhh,i))\r\n# \r\n# \r\n# data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n# names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n# \r\n# write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n# )\r\n# }\r\n# }\r\n# }\r\n# \r\n# for rrr in c(0,0.8)) {\r\n# group =ifelse(rrr==0.8,\"levycorrelated08\",\"uncorrelated\")\r\n# \r\n# #for (hhh in c(0.75,1)) {\r\n# # group2 =ifelse(hhh==0.75,\"_h0.75\",\"_h1\")\r\n# for (i in 0:9){\r\n# set.seed(872+i)\r\n# \r\n# u <- simm.levycorr(1:9000, r = rrr, mu=3,l0 = 1, burst =paste(rrr,i))\r\n# \r\n# \r\n# data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n# names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n# \r\n# write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n# )\r\n# # }\r\n# }\r\n# }\r\n# ######with activity\r\n# \r\n# setwd(\"D:/dokumente/data/buridan/simulated_data/new\")\r\n# for (rrr in c(0.985,0.983)) {\r\n# group =ifelse(rrr==0.985,\"A\",\"B\")\r\n# \r\n# for (ttt in c(0.4,0.3)) {\r\n# group2 =ifelse(ttt==0.3,\"C\",\"D\")\r\n# for (i in 0:19){\r\n# set.seed(899+i)\r\n# \r\n# u <- simm.levycorrpauses(1:9000, r = rrr, mu=3,l0 = 1, burst =paste(rrr,i), act=ttt)\r\n# \r\n# \r\n# data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n# names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n# \r\n# write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n# )\r\n# }\r\n# }\r\n# }\r\n# \r\n# for (rrr in c(0.95,0.9)) {\r\n# group =ifelse(rrr==0.9,\"corrw_r0.8\",\"corrw_r0.6\")\r\n# for (ttt in c(0.66,0.8)) {\r\n# group2 =ifelse(ttt==0.8,\"_h0.75\",\"_h1\")\r\n# for (i in 0:9){\r\n# set.seed(872+i)\r\n# \r\n# u <- simm.crw2pauses(1:9000, r = rrr, h=0.75, act=ttt,burst =paste(rrr,ttt,i))\r\n# \r\n# \r\n# data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n# names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n# \r\n# write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n# )\r\n# }\r\n# }\r\n# }\r\n\r\n# traj=data\r\n# newtraj= mindistkeep3(traj,0.6,35)\r\n# traj=new_traj\r\n# #####get env ???\r\n# i=c(1:length(traj))\r\n# env$ = env[1]\r\n# \r\n# g_outputdir= \"D:/dokumente/data\"\r\n# rgghome=\"D:/dokumente/My Dropbox/buridan/buridan_v2.2/analysis\"\r\n# ###\r\n# \r\n# bla = paste(c(outputfile,\"t\",g_treshold,\"Pt\",g_duration_slider,\".pdf\"),collapse=\"\")\r\n# pdf(bla)\r\n# setwd(rgghome)\r\n# source (\"scripts/general.r\")\r\n# source (\"scripts/straightness.r\")\r\n# source (\"scripts/occupancy.r\")\r\n# source (\"scripts/thigmotaxis.r\")\r\n# source (\"scripts/angledev.r\")\r\n# source (\"scripts/activity_martin.r\")\r\n# g = dev.off()\r\n# source (\"scripts/saveworkspace2.r\")\r\n# \r\n# \r\n\r\nsetwd(\"D:/dokumente/data/buridan/simulated_data/totestagainstcs_rrr=0.985_ttt=0.3\")\r\n#########\r\n########## make 20 correlated walks\r\n\r\nK=1.5*c(-4:4,-1:1,-3:3,0)\r\nK[1]=2.5\r\nK[2]=-0.5\r\nK[13]=1\r\nJ= sample(K,20)\r\nL= sample(K,20)\r\n#for (rrr in c(0.9963)) { #levy\r\nfor (rrr in c(0.9965)) { #corrwalk\r\ngroup =\"A\"\r\n\r\n for (ttt in c(0.85)) { #corr\r\n # for (ttt in c(0.875)) { #levy\r\n group2 =\"C\"\r\n for (i in 0:19){\r\n set.seed(920+i)\r\n k= 0.7+ K[i+1]/10\r\n \r\n\r\n# u <- simm.levycorrpauses(1:9000, r = rrr, mu=3,l0 = 1, burst =paste(rrr,i), act=ttt)\r\n# u[[1]]$dist[u[[1]]$dist == 0]=NA\r\n# median(u[[1]]$dist, na.rm=TRUE)\r\n # u <- simm.levycorrpauses(1:9000, r = rrr+ J[i+1]/1000000, mu=2.6,l0 = 0.8+ K[i+1]/10, burst =paste(rrr,i), act=ttt)\r\n u <- simm.crw2pauses(1:9000, r = rrr, h=k, act=ttt,burst =paste(rrr,ttt,i))\r\n #print(median(u[[1]]$dist, na.rm=TRUE))\r\n \r\n data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n\r\n write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n )\r\n }\r\n }\r\n}\r\n#########\r\n########## make 20 levy walks\r\n\r\nK=1.5*c(-4:4,-1:1,-3:3,0)\r\nK[1]=2.5\r\nK[2]=-0.5\r\nK[13]=1\r\nJ= sample(K,20)\r\nL= sample(K,20)\r\nfor (rrr in c(0.9963)) { #levy\r\n#for (rrr in c(0.9965)) { #corrwalk\r\ngroup =\"B\"\r\n\r\n #for (ttt in c(0.85)) { #corr\r\n for (ttt in c(0.875)) { #levy\r\n group2 =\"D\"\r\n for (i in 0:19){\r\n set.seed(920+i)\r\n k= 0.7+ K[i+1]/10\r\n \r\n\r\n# u <- simm.levycorrpauses(1:9000, r = rrr, mu=3,l0 = 1, burst =paste(rrr,i), act=ttt)\r\n# u[[1]]$dist[u[[1]]$dist == 0]=NA\r\n# median(u[[1]]$dist, na.rm=TRUE)\r\n u <- simm.levycorrpauses(1:9000, r = rrr+ J[i+1]/1000000, mu=2.6,l0 = 0.8+ K[i+1]/10, burst =paste(rrr,i), act=ttt)\r\n # u <- simm.crw2pauses(1:9000, r = rrr, h=k, act=ttt,burst =paste(rrr,ttt,i))\r\n #print(median(u[[1]]$dist, na.rm=TRUE))\r\n \r\n data=data.frame(c(1:9000),100*c(1:9000),u[[1]]$x,u[[1]]$y,0)\r\n names(data)=c(\"frame\",\"time\",\"x\",\"y\", \"burst\")\r\n\r\n write.table(data,file=paste(group,group2,\"_\",i,\".txt\",sep=\"\",collapse = NULL),append = FALSE,sep = \"\\t\", quote= FALSE, row.names= FALSE\r\n )\r\n }\r\n }\r\n}\r\n\r\n\r\n##### other tests\r\n\r\nttt= 0.88\r\n\r\n\r\nrrr=0.9962\r\nu <- simm.crw2pauses(1:9000, r = rrr, h=0.6, act=ttt,burst =paste(rrr,ttt,i))\r\nv <- simm.levycorrpauses(1:9000, r = rrr, mu=2.6,l0 = 1, burst =paste(rrr,i), act=0.85)\r\nnew_traj <- v\r\n new_traj2 <- mindistkeep3(new_traj, thresholdmin = g_treshold/10, \r\n thresholdmax = 35)\r\nu= new_traj2\r\nv= new_traj2\r\nmedian (abs(u[[1]]$rel.angle), na.rm=TRUE)/pi*180\r\nX=c.activity(u,min_pause_length = 10)\r\nY=c.activity(v,min_pause_length = 10)\r\n#head(X)\r\nsum(X$act[X$act>0])\r\nsum(Y$act[Y$act>0])\r\nspeeds = c.speeds(u)$speed_det\r\nspeeds2 = c.speeds(v)$speed_det\r\nspeeds = speeds[speeds>0]\r\nspeeds2 = speeds2[speeds2>0]\r\nB= c(0:12, 2000)\r\nB=B/2\r\nB\r\nhist(speeds, main=\"correlated\", xlim=c(0,5), breaks = B)\r\nhist(speeds2, main=\"levy\", xlim=c(0,5), breaks = B)\r\nlength(speeds[speeds>0])\r\nlength(speeds2[speeds2>0])\r\n\r\nspeeds = speeds[speeds>0]\r\n speeds = speeds[!speeds>50]\r\n\r\nmedian(speeds, na.rm=TRUE)\r\n\r\n\r\n", "meta": {"hexsha": "831985c9a3f5930ca494e691d13994104e904422", "size": 12740, "ext": "r", "lang": "R", "max_stars_repo_path": "CeTrAn/other_codes/simmulate2.r", "max_stars_repo_name": "brembslab/CeTrAn", "max_stars_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-02-26T12:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T08:36:32.000Z", "max_issues_repo_path": "CeTrAn/other_codes/simmulate2.r", "max_issues_repo_name": "brembslab/CeTrAn", "max_issues_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:08:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-18T13:31:53.000Z", "max_forks_repo_path": "CeTrAn/other_codes/simmulate2.r", "max_forks_repo_name": "brembslab/CeTrAn", "max_forks_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-01-09T13:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-21T12:55:17.000Z", "avg_line_length": 27.8774617068, "max_line_length": 144, "alphanum_fraction": 0.4840659341, "num_tokens": 5072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6988000751922512}} {"text": "#' Compute transitions of a given order\n#'\n#' @param seq a vector containing observations from an stochastic process.\n#' @param order the order of the transitions to be computed (an integer).\n#'\n#' @return an array with the transitions in the format n_{ijk}, where i, j, k are in states(seq).\n#' @export get_contingency_array\n#'\n#' @examples\n#' X <- rbinom(n = 1E5, size = 1, prob = 0.8)\n#' get_contingency_array(X, order = 3)\nget_contingency_array <- function(seq, order){\n ## Many thanks to https://stackoverflow.com/users/3358272/r2evans\n ## https://stackoverflow.com/questions/67004206/speeding-up-r-code-to-compute-higher-order-transitions-in-a-markov-chain\n N <- length(seq)\n states <- sort(unique(seq))\n nstates <- length(states)\n inds <- seq_along(states)\n K <- order + 1\n out <- array(0, dim = rep(nstates, K))\n for (z in K:N){\n pos <- matrix(match(seq[(z - K + 1):z], states), nrow = 1)\n out[pos] <- out[pos] + 1\n }\n return(out)\n}\n#' Compute the likelihood ratio statistic comparing a second-order to a first-order Markov chain model for \\code{seq}\n#'\n#' @param seq a vector containing observations from an stochastic process.\n#'\n#' @return the likelihood ratio statistic (G^2) comparing a second-order model to a first-order one. \n#' @export compute_Gsquared\n#' @details Under the null, G^2 has a chi-square(2) distribution.\n#' @examples\n#' X <- rbinom(n = 1E5, size = 1, prob = 0.8)\n#' compute_Gsquared(X)\ncompute_Gsquared <- function(seq){\n states <- sort(unique(seq))\n nstates <- length(states)\n dt <- get_contingency_array(seq, 2)\n stats <- c()\n for(k in 1:nstates){\n for( i in 1:nstates){\n for(j in 1:nstates){\n nijk <- dt[i , j, k] + 1E-17\n nijp <- sum(dt[i, j, ]) + 1E-17\n npjk <- sum(dt[, j, k]) + 1E-17\n npjp <- sum(dt[, j, ]) + 1E-17\n s <- nijk * log((nijk/nijp)/(npjk/npjp))\n stats <- c(stats, s)\n }\n }\n }\n out <- 2*sum(stats)\n return(out)\n}\n#' Compute the Bayes factor comparing a second-order Markov model to a first-order one.\n#'\n#' @param seq a vector containing observations from an stochastic process.\n#'\n#' @return the approximate Bayes factor comparing a second- to a first-order Markov chain model for \\code{seq}.\n#' @export compute_BF\n#'\n#' @examples\n#' X <- rbinom(n = 1E5, size = 1, prob = 0.8)\n#' compute_BF(X)\ncompute_BF <- function(seq){\n n <- length(seq)\n m <- length(unique(seq))\n Gsq <- compute_Gsquared(seq)\n BF <- (Gsq - 2*log(n))/2\n return(BF)\n}\n#' Thin a sample until the first-order Markov model is preferred.\n#'\n#' @param seq a vector containing observations from an stochastic process.\n#' @param max_k maximum thinning to be tried.\n#'\n#' @return a list containing the selected \\code{k}, the achieved Bayes factor (\\code{BF})\n#' and whether one could indeed find a \\code{k} less than \\code{max_k}\n#' such that the first-order model is preferred.\n#' @export find_k\n#' @details This is the same approach as Raftery & Lewis (1992) \"How many iterations in the Gibbs sampler?\"\n#' @examples\n#' library(markovchain)\n#' M <- 1E4\n#' p <- runif(1)\n#' ( maxA <- min(p/(1-p), 1) ) ## maximum alpha\n#' a <- runif(1, 0, maxA) \n#' b <- exp(log(a) + log(1-p) - log(p)) \n#' mat <- matrix(c(1-a, a, b, 1-b), ncol = 2, nrow = 2, byrow = TRUE)\n#' MC.binary <- new(\"markovchain\",\n#' states = c(\"0\", \"1\"),\n#' transitionMatrix = mat, name = \"Binary\")\n#' out1 <- markovchainSequence(n = M, markovchain = MC.binary, t0 = \"0\")\n#' X1 <- as.numeric(out1)\n#' \n#' rs <- runif(4^2)\n#' mat2 <- structure(c(0.264985809735216, 0.598430024309721, 0.140708602965477, \n#' 0.0566167324620894, 0.278728488803952, 0.0427599923571986, 0.453529988769559, \n#' 0.604004074666218, 0.116827824413052, 0.0358869202453851, 0.181735130309576, \n#' 0.266807259734723, 0.33945787704778, 0.322923063087696, 0.224026277955388, \n#' 0.0725719331369693), .Dim = c(4L, 4L))\n#' MC.binary2nd <- new(\"markovchain\",\n#' states = c(\"00\", \"01\", \"10\", \"11\"),\n#' transitionMatrix = mat2, name = \"Binary2nd\")\n#' out2 <- markovchainSequence(n = M/2, markovchain = MC.binary2nd, t0 = \"01\")\n#' X2 <- as.numeric(strsplit(paste(out2, collapse = \"\"), \"\")[[1]])\n#' find_k(X1)\n#' find_k(X2)\nfind_k <- function(seq, max_k = 10){\n k <- 1\n BF <- compute_BF(seq)\n while(BF > 0){\n k <- k + 1\n inds <- seq.int(1L, length(seq), k)\n BF <- compute_BF(seq = seq[inds])\n if(k >= max_k) break\n }\n return(\n list(\n k = k,\n BF = BF,\n success = (BF < 0) \n )\n )\n}", "meta": {"hexsha": "439fec2ae0e196052dd5c3f107f601b91592eee9", "size": 4461, "ext": "r", "lang": "R", "max_stars_repo_path": "R/order_selection.r", "max_stars_repo_name": "maxbiostat/BinaryMarkovChains", "max_stars_repo_head_hexsha": "e73e37e30ab0b320ae1258563cede187a13d23ef", "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/order_selection.r", "max_issues_repo_name": "maxbiostat/BinaryMarkovChains", "max_issues_repo_head_hexsha": "e73e37e30ab0b320ae1258563cede187a13d23ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-03-02T13:00:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T12:28:46.000Z", "max_forks_repo_path": "R/order_selection.r", "max_forks_repo_name": "maxbiostat/BinaryMarkovChains", "max_forks_repo_head_hexsha": "e73e37e30ab0b320ae1258563cede187a13d23ef", "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.125984252, "max_line_length": 122, "alphanum_fraction": 0.6379735485, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.6987925700412245}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\nfast_cvloo_knn <- function(dset) {\n maxK <- length(dset[,1]) - 1\n classes = unique(dset$class)\n \n ans <- rep(x = 0, times = maxK)\n for (i in 1:length(dset[,1])) {\n # for (i in 1:10) {\n cat(\"\\r\", \"Processing sample \", i, \" of \", length(dset[,1]))\n dataset <- dset[-i,]\n # print(dataset)\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 1:2], dset[i, 1:2])\n }\n sortedDataset <- dataset[order(distance),]\n \n classesCount <- rep(x = 0, times = length(classes))\n names(classesCount) = classes\n for (j in 1:maxK) {\n classesCount[sortedDataset$class[j]] <- classesCount[sortedDataset$class[j]] + 1\n \n classForCurrentK = names(which.max(classesCount))[1]\n if (classForCurrentK == dset$class[i]) {\n ans[j] = ans[j] + 1\n }\n }\n \n }\n cat(\"\\n\")\n for (i in 1:length(ans)) {\n \n ans[i] = ans[i] / length(dset[,1] - 1)\n }\n \n return (ans)\n}\n\nkNN <- function(dataset, points, k, dist = euclidean) {\n answer <- array(dim=c(length(points[,1])))\n \n for (i in 1:length(points[,1])) {\n distance <- array(dim=dim(dataset)[1])\n for (j in 1:dim(dataset)[1]) {\n distance[j] <- dist(dataset[j, 1:2], points[i,])\n }\n sortedDataset <- dataset[order(distance),]\n \n classesCount <- c(0, 0, 0)\n names(classesCount) = unique(dataset$class)\n for (j in 1:k) {\n classesCount[sortedDataset$class[j]] <- classesCount[sortedDataset$class[j]] + 1\n }\n answer[i] = names(which.max(classesCount))[1]\n }\n \n return (answer)\n}\n\ndf = data.frame(x = double(), y = double(), class = character())\n\ndf <- rbind(df, data.frame(x = 122, y = 2208, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 148, y = 1136, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 270, y = 2186, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 271, y = 2016, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 306, y = 1023, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 413, y = 1153, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 503, y = 2013, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 541, y = 971, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 706, y = 1018, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 837, y = 867, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 875, y = 1011, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 927, y = 1915, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 997, y = 897, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1005, y = 529, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1028, y = 1176, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1050, y = 1429, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1125, y = 781, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1144, y = 1061, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1146, y = 1751, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1192, y = 1601, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1264, y = 888, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1275, y = 1412, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1329, y = 576, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1366, y = 1586, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1405, y = 386, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1432, y = 1226, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1597, y = 279, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1615, y = 1604, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1631, y = 1200, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1638, y = 1365, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1765, y = 1262, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1806, y = 1444, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1821, y = 1056, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1896, y = 877, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1993, y = 695, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2027, y = 1415, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2087, y = 889, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2189, y = 674, class = \"class-1\"))\n\nz = array(c(c(1164, 1232)), dim = c(1,2))\n\npar(mfrow=c(1,2), pty=\"s\")\n# LOO CV, looking for the best k\nstats <- fast_cvloo_knn(df)\nplot(1:(length(df[,1]) - 1), stats, type=\"l\", xlab=\"k\", ylab=\"Accuracy\")\n\nmaxPoint = which(stats == max(stats))\npoints((1:(length(df[,1]) - 1))[maxPoint], stats[maxPoint], pch = 19, col = \"red\")\n\nbestK <- which.max(stats)\ncat(\"Best K =\", bestK, \"\\n\")\n\n\ncolors <- c(\"class-1\" = \"blue\", \"class-2\" = \"red\")\nplot(df[, 1:2], bg = colors[paste(df$class)], pch=23, asp=1)\n\nresult <- kNN(df, z, 5)\npoints(z[,1], z[,2], bg = colors[result], pch = 22)\n", "meta": {"hexsha": "eb5eac761bb811ec992a1f03e48930e236a82ecf", "size": 4822, "ext": "r", "lang": "R", "max_stars_repo_path": "1 - Nearest neighbors algorithm/knn-loocv-img-exp.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "1 - Nearest neighbors algorithm/knn-loocv-img-exp.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "1 - Nearest neighbors algorithm/knn-loocv-img-exp.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": 39.2032520325, "max_line_length": 86, "alphanum_fraction": 0.575072584, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6986271789999525}} {"text": "\n## minimum cost network flow model for phase unwrapping\n\n#' @describeIn brcutpuw Network flow algorithm for phase unwrapping\nnetflowpuw <- function(phase, wts=NULL, details=FALSE, trace=1) {\n nr <- nrow(phase)\n nc <- ncol(phase)\n dx <- zernike::wrap(diff(phase))\n dy <- zernike::wrap(t(diff(t(phase))))\n d2x <- dx[,2:nc] - dx[,1:(nc-1)]\n d2y <- dy[1:(nr-1),] - dy[2:nr,]\n ndx <- sum(!is.na(dx))\n ndy <- sum(!is.na(dy))\n charge <- -round((d2y+d2x)/(2*pi))\n \n if (sum(abs(charge), na.rm=TRUE) == 0) {\n cat(\"Phase map is trivial to unwrap, so calling idiffpuw\\n\")\n return(zernike::idiffpuw(phase, ucall=TRUE))\n }\n \n ## these weights are too simple, but this seems to work\n ## better than combining weights from each pixel that\n ## went into a given difference.\n \n if (!is.null(wts)) {\n wts <- wts/max(wts,na.rm=TRUE)\n wx <- wts[-1,]\n wy <- wts[,-1]\n wx <- wx[!is.na(dx)]\n wy <- wy[!is.na(dy)]\n obj <- c(wx, wx, wy, wy)\n } else {\n obj <- rep(1, 2*(ndx+ndy))\n }\n ## the optimal solution will cancel the map's charges\n \n kx <- dx\n kx[!is.na(kx)] <- 1:ndx\n ky <- dy\n ky[!is.na(ky)] <- 1:ndy\n \n ## these are the 1d indexes of the pixels that go into each 2 x 2 loop\n \n k2x1 <- kx[,1:(nc-1)][!is.na(charge)]\n k2x2 <- kx[,2:nc][!is.na(charge)]\n k2y1 <- ky[1:(nr-1),][!is.na(charge)]\n charge <- charge[!is.na(charge)]\n rm(d2x,d2y,kx,ky)\n \n nrow <- length(charge)\n ncol <- 2*(ndx+ndy)\n row <- c(-1., 1., 1., -1., 1., -1., -1., 1.)\n xvals <- rep(row, nrow)\n i_ind <- rep(1:nrow, each=8)\n j_ind <- as.numeric(rbind(k2x1, k2x2, \n k2x1+ndx, k2x2+ndx,\n k2y1+2*ndx, k2y1+2*ndx+1,\n k2y1+2*ndx+ndy, k2y1+2*ndx+ndy+1)\n )\n if (packageVersion(\"Matrix\") >= \"1.3.0\") {\n mat <- Matrix::sparseMatrix(i=i_ind, j=j_ind, x=xvals, dims=c(nrow, ncol), repr=\"T\")\n } else {\n mat <- Matrix::sparseMatrix(i=i_ind, j=j_ind, x=xvals, dims=c(nrow, ncol), giveCsparse=FALSE)\n }\n \n lpout <- rcbc::cbc_solve(obj=obj, mat=mat,\n row_ub=charge,\n row_lb=charge,\n col_lb=rep(0, ncol),\n col_ub=rep(1, ncol),\n cbc_args = list(log=trace, verbose=trace)\n )\n if (rcbc::solution_status(lpout) != \"optimal\") {\n warning(\"non-convergence detected\")\n return(lpout)\n }\n \n dx <- rbind(dx, rep(NA, nc))\n dy <- cbind(dy, rep(NA, nr))\n soln <- lpout$column_solution\n ex <- soln[1:ndx]-soln[(ndx+1):(2*ndx)]\n ey <- soln[(2*ndx+1):(2*ndx+ndy)]-soln[(2*ndx+ndy+1):(2*ndx+2*ndy)]\n ex.m <- dx\n ey.m <- dy\n ex.m[!is.na(dx)] <- ex\n ey.m[!is.na(dy)] <- ey\n puw <- zernike::idiffpuw(phase=phase, dx=dx+2*pi*ex.m, dy=dy+2*pi*ey.m)\n if (details) {\n ex.m[ex.m==0] <- NA\n ey.m[ey.m==0] <- NA\n list(puw=puw, ex=ex.m, ey=ey.m, lpout=lpout)\n } else {\n puw\n }\n \n}\n\n", "meta": {"hexsha": "1049ed150d65c6e025e59eb59eaa6d1f02b4764e", "size": 3000, "ext": "r", "lang": "R", "max_stars_repo_path": "R/netflowpuw.r", "max_stars_repo_name": "mlpeck/lppuw", "max_stars_repo_head_hexsha": "a6535dfba906f1829a21cc7ed453f34b135779d5", "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/netflowpuw.r", "max_issues_repo_name": "mlpeck/lppuw", "max_issues_repo_head_hexsha": "a6535dfba906f1829a21cc7ed453f34b135779d5", "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/netflowpuw.r", "max_forks_repo_name": "mlpeck/lppuw", "max_forks_repo_head_hexsha": "a6535dfba906f1829a21cc7ed453f34b135779d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-06-06T01:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T01:15:21.000Z", "avg_line_length": 30.612244898, "max_line_length": 97, "alphanum_fraction": 0.5226666667, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6986271721654512}} {"text": "library(signal)\n\na0 <- 0.35875\na1 <- 0.48829\na2 <- 0.14128\na3 <- 0.01168\nx <- seq(0.0, 1.0, by=1/40)\nh <- a0 - a1 * cos(2 * pi * x) + a2 * cos(4 * pi * x) - a3 * cos(6 * pi * x)\nh <- B/sum(B)\n\n# Print filter coefficients\npaste(sprintf(\"%.10e\", h), collapse=\", \")\n\nfh <- freqz(h)\n\nop <- par(mfrow = c(1, 2))\n\nplot(fh$f / pi, abs(fh$h), type = \"l\", ylab = \"magnitude\", xlab = \"Frequency\", xlim = c(0, 0.2))\n\nplot(fh$f / pi, 20*log10(abs(fh$h)+1e-5), type = \"l\", ylab = \"dB\", xlab = \"Frequency\", xlim = c(0, 0.2))\n\n\npar(op)\n", "meta": {"hexsha": "f65c5126944721ce052ec5b6cf71022a8c5423a7", "size": 521, "ext": "r", "lang": "R", "max_stars_repo_path": "projects/mcpha/filters/fir_0.r", "max_stars_repo_name": "pjsg/red-pitaya-notes", "max_stars_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "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": "projects/mcpha/filters/fir_0.r", "max_issues_repo_name": "pjsg/red-pitaya-notes", "max_issues_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "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": "projects/mcpha/filters/fir_0.r", "max_forks_repo_name": "pjsg/red-pitaya-notes", "max_forks_repo_head_hexsha": "85faf2ed717c1bb08d350376fe4b366fdc5c56a6", "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": 21.7083333333, "max_line_length": 104, "alphanum_fraction": 0.5335892514, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6985987487463526}} {"text": "a <- as.hexmode(35)\nb <- as.hexmode(42)\nas.integer(a & b) # 34\nas.integer(a | b) # 43\nas.integer(xor(a, b)) # 9\n", "meta": {"hexsha": "c06010d1751608c5f99ce93ce83d1257bf4a2950", "size": 123, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Bitwise-operations/R/bitwise-operations-2.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/Bitwise-operations/R/bitwise-operations-2.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/Bitwise-operations/R/bitwise-operations-2.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": 20.5, "max_line_length": 27, "alphanum_fraction": 0.5284552846, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6985654132724559}} {"text": "install.packages('data.table')\r\ninstall.packages('MASS')\r\ninstall.packages('VGAM')\r\ninstall.packages(\"ggplot2\")\r\ninstall.packages(\"ggrepel\")\r\ninstall.packages('ggpubr')\r\ninstall.packages('ggExtra')\r\ninstall.packages('stargazer')\r\ninstall.packages('corrplot')\r\ninstall.packages('olsrr')\r\ninstall.packages('eply')\r\n\r\nlibrary(data.table)\r\nlibrary(MASS)\r\nlibrary(car)\r\nlibrary(ggplot2)\r\nlibrary(ggrepel)\r\nlibrary(ggpubr)\r\nlibrary(ggExtra)\r\nlibrary(stargazer)\r\nlibrary(nlme)\r\nlibrary(corrplot)\r\nlibrary(Matrix)\r\nlibrary(olsrr)\r\nlibrary(eply)\r\nsetwd(\"C:/Users/Han/Desktop/Box Sync/Stat 501/Final Project\")\r\n\r\ndt_1 = fread('final project dataset 1.txt')\r\ndt_2 = fread('final project dataset 2.txt')\r\n\r\ndt = merge(dt_1,dt_2,by = 'State')\r\n\r\n#[1] 0\r\n## No NA value\r\n\r\n#### 1.\tFind an appropriate linear regression model with M as the dependent variables.\r\n#### Among the independent variables include MA, D, PL, S, B, HT, UR, CR, HS, INC, PL, VT, and UR. \r\n#### Add and subtract variables as you think fit.\r\n#### Notice that you may need to detect influential points, multicollineaity, also do necessary transformation if needed.\r\n\r\ndt1 = dt[,c('State','M','MA','D','PL','S','B','HT','UR','CR','HS','INC','VT')]\r\ndt1[,2:13] = dt1[,2:13][,lapply(.SD,as.numeric)]\r\n# standardize all X\r\ndt1[,3:13] = dt1[,3:13][,lapply(.SD,scale)]\r\n\r\n# orignal EDA\r\ntemp <- ggplot(dt1, aes(x=MA, y=M)) + geom_point() + theme_classic() + geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx11 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=D, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx12 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=PL, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx13 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=S, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx14 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=B, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx15 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=HT, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx16 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=UR, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx17 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=CR, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx18 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=HS, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx19 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=INC, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx110 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1, aes(x=VT, y=M)) + geom_point() + theme_classic()+ geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\nx111 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\ntemp <- ggplot(dt1[-33,], aes(x=MA, y=M)) + geom_point() + theme_classic() + geom_smooth(method = 'lm')+ theme(text = element_text(size=18, face = 'bold'))+\r\n labs(x = 'influential pt temporarily removed MA')\r\nx112 = ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\nggarrange(x11,x112,x12,x13,x14,x15,x16,x17,x18,x19,x110,x111,ncol = 4,nrow = 3)\r\n\r\ntr <- function (m)\r\n{\r\n total_sum <- 0\r\n if(is.matrix(m))\r\n {\r\n row_count <- nrow(m)\r\n col_count <- ncol(m)\r\n if(row_count == col_count)\r\n {\r\n total_sum <-sum(diag(m))\r\n total_sum\r\n }\r\n else\r\n {\r\n message ('Matrix is not square')\r\n }\r\n }\r\n else\r\n {\r\n message( 'Object is not a matrix')\r\n \r\n }\r\n}\r\nNear.Neighbor.Approach = function(x){\r\n x = as.data.frame(x)\r\n rns = x[,1]\r\n x = x[,-1]\r\n rownames(x) = rns\r\n x = as.matrix(x)\r\n \r\n n = nrow(x) ; k = ncol(x)\r\n y = x[,1]\r\n z = matrix(1,n,1)\r\n x[,1] = z\r\n \r\n prx = diag(n) - x %*% ginv(t(x)%*%x) %*% t(x)\r\n E = prx %*% y\r\n V = matrix(0,n,n)\r\n for (i in 1:(n-1)){\r\n for (j in (i+1):n){\r\n d = t(x[i,]-x[j,]) %*% (x[i,]-x[j,])\r\n if (d > 0) {\r\n V[i,j] = -2/d\r\n V[j,i] = -2/d\r\n }\r\n }\r\n }\r\n \r\n for (i in 1:n){\r\n V[i,i] = - sum(V[i,])\r\n }\r\n \r\n B = prx %*% V %*% prx\r\n \r\n NUM = t(E) %*% V %*% E\r\n DEN = t(E) %*% E/(n-k)\r\n STAT = NUM/DEN\r\n MEAN = tr(B)\r\n VAR = 2*((n-k)*tr(B %*% B)-(tr(B))^2)/(n-1)\r\n STAT = (STAT -MEAN)/sqrt(VAR)\r\n STAT = as.numeric(STAT)\r\n return(STAT)\r\n}\r\n\r\nt.1 = Near.Neighbor.Approach(dt1)\r\nn = 50; k = 11\r\np_value = 2* pt(t.1,n-k+2)\r\n\r\n\r\n# temporaliy elimate outliers/influential points\r\n# temporaliy do proper transfer on X\r\n\r\n# Variable selection\r\n\r\nmodel1 = lm(M ~., data = dt1[,2:13])\r\nk1 = ols_best_subset(model1)\r\nplot(k1)\r\nk1\r\nplot(ols_stepaic_both(model1))\r\n\r\nols_stepwise(model1)\r\n# choose the 9th model based on adj r^2, C(p) and AIC\r\ndt1.a = dt1[,-c(1,6,8)]\r\n# multicollinearity\r\nmodel1.a = lm(M ~., data = dt1.a)\r\nols_coll_diag(model1.a)\r\nX.corr.a = cor(dt1.a[,2:10])\r\ncorrplot(X.corr.a,method = 'circle',addCoef.col = 'black')\r\n# lets see if we further delete HS from dt1, how things will chagne\r\ndt1.b = dt1[,-c(1,6,8,11)]\r\n# multicollinearity\r\nmodel1.b = lm(M ~., data = dt1.b)\r\nols_coll_diag(model1.b)\r\nX.corr.b = cor(dt1.b[,2:9])\r\ncorrplot(X.corr.b,method = 'circle',addCoef.col = 'black')\r\n# lets see if we further delete HS from dt1, how things will chagne\r\ndt1.c = dt1[,-c(1,3,6,7,8,10)]\r\n# multicollinearity\r\nmodel1.c = lm(M ~., data = dt1.c)\r\nols_coll_diag(model1.c)\r\nX.corr.c = cor(dt1.c[,2:7])\r\ncorrplot(X.corr.c,method = 'circle',addCoef.col = 'black')\r\n# lets see if we further delete HS from dt1, how things will chagne\r\ndt1.d = dt1[,-c(1,4,6,8,9)]\r\n# multicollinearity\r\nmodel1.d = lm(M ~., data = dt1.d)\r\nols_coll_diag(model1.d)\r\nX.corr.d = cor(dt1.d[,2:7])\r\ncorrplot(X.corr.d,method = 'circle',addCoef.col = 'black')\r\n\r\n# regression and residual and influence diagonostic\r\n\r\nsummary(model1.a)\r\nsummary(model1.b)\r\nsummary(model1.c)\r\nsummary(model1.d)\r\n\r\nols_correlations(model.a)\r\nols_ovsp_plot(model.a)\r\nhttp://www.rsquaredacademy.com/olsrr/articles/influence_measures.html\r\nols_diagnostic_panel(model.a)\r\nols_norm_test(model.a)\r\nols_corr_test(model.a)\r\nols_dfbetas_panel(model.a)\r\n## Run LASSO \r\n# provide an arithmetic series\r\nl1 = seq(from =-7, to =7, by = .001)\r\n# conver to geometric series to use as user provided lambda\r\nl2 = exp(-l1)\r\nset.seed(42)\r\n\r\nfit.lasso.cv = cv.glmnet(x = as.matrix(dt1[,2:12]), y =as.matrix(dt1[,1]),type.measure = 'mse', alpha = 1, family = 'gaussian', nfolds=5, lambda = l2)\r\nfit.ridge.cv = cv.glmnet(x = as.matrix(dt1[,2:12]), y =as.matrix(dt1[,1]),type.measure = 'mse', alpha = 0, family = 'gaussian', nfolds=5, lambda = l2)\r\npar(mfrow=c(1,3))\r\nplot(fit.lasso.cv)\r\nplot(fit.lasso.cv$glmnet.fit, \"norm\", label=TRUE)\r\nplot(fit.lasso.cv$glmnet.fit, \"lambda\", label=TRUE)\r\npar(mfrow=c(1,1))\r\nplot(fit.ridge.cv)\r\nfit.lasso.cv$lambda.1se\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#\r\ndt2 = cbind(dt[,15],dt[,-15])\r\ndt2 = dt2[,c(2,1,3:27)]\r\ndt2[,2:27] = dt2[,2:27][,lapply(.SD,as.numeric)]\r\n# standardize all X\r\ndt2[,3:27] = dt2[,3:27][,lapply(.SD,scale)]\r\n\r\nt.2 = Near.Neighbor.Approach(dt2)\r\nn = 50; k = 25\r\np_value = 2* pt(t.2,n-k+2)\r\n\r\ndt2.a = dt2\r\ndt2.a[,2] = 1/dt2.a[,2]\r\n\r\nt.2.a = Near.Neighbor.Approach(dt2.a)\r\nn = 50; k = 25\r\np_value.2a = 2* pt(t.2.a,n-k+2)\r\ncolnames(dt2.a)[2] = 'inv_MA'\r\nmodel2.a = lm(inv_MA ~., data = dt2.a[,2:27])\r\n\r\ndt2.b = dt2.a\r\ndt2.b[,6:8] = dt2.b[,6:8][,lapply(.SD,rank)]\r\ndt2.b[,6:8] = dt2.b[,6:8]/50\r\ndt2.c = dt2.b[,c(1:8, 12,14:16, 19:20, 23, 26:27)]\r\nmodel2.c = lm(inv_MA ~., data = dt2.c[,2:ncol(dt2.c)])\r\n\r\ntime = proc.time()\r\nk2.c = ols_best_subset(model2.c)\r\nproc.time() - time\r\n\r\nols_norm_test(model2.d)\r\n\r\n\r\ng8 = list()\r\nfor (i in 3:ncol(dt2.a)){\r\n temp <- ggplot(dt2.a, aes_string(x=colnames(dt2.a)[i], y = colnames(dt2.a)[2])) + labs(y ='1/MA') +\r\n geom_point() + theme_classic() + geom_smooth(method = 'lm')+ theme(text = element_text(size=26, face = 'bold'))\r\n g8[[i-2]] <- ggMarginal(temp,type = 'histogram', fill = \"cyan\")\r\n}\r\nggarrange(g8[[1]],g8[[2]],g8[[3]],g8[[4]],g8[[5]],g8[[6]],g8[[7]],\r\n g8[[8]],g8[[9]],g8[[10]],g8[[11]],g8[[12]],g8[[13]],g8[[14]],\r\n g8[[15]],g8[[16]],g8[[17]],g8[[18]],g8[[19]],g8[[20]],\r\n g8[[21]],g8[[22]],g8[[23]],g8[[24]],g8[[25]],ncol = 5,nrow = 5)\r\n\r\nmodel2 = lm(MA ~., data = dt2[,2:27])\r\nk2 = ols_best_subset(model2)\r\nplot(k2)\r\nk2\r\nols_stepaic_both(model2)\r\nols_stepwise(model2)\r\n\r\n\r\n\r\nNear.Neighbor.Approach(dt2)\r\n\r\n\r\n\r\nhttp://www.biostat.jhsph.edu/~iruczins/teaching/jf/ch10.pdf\r\nhttps://stats.stackexchange.com/questions/61217/transforming-variables-for-multiple-regression-in-r\r\nhttp://nymetro.chapter.informs.org/prac_cor_pubs/01-08%20INFORMS_Jan2008.pdf\r\nhttp://www.stat.columbia.edu/~martin/W2024/R10.pdf\r\nhttps://stats.stackexchange.com/questions/214682/stepwise-regression-in-r-how-does-it-work\r\nhttp://www.columbia.edu/~so33/SusDev/Lecture_6.pdf\r\n\r\n\r\n\r\n\r\n## directly do v selection based on R square\r\n\r\n", "meta": {"hexsha": "c4293673519d28fb4848dc005f583d17a3cfcaa1", "size": 9724, "ext": "r", "lang": "R", "max_stars_repo_path": "final project.r", "max_stars_repo_name": "Dr-Spicy/Murder-and-Marriage-Rates-Modeling-using-Linear-Regression-from-U.S.-Bureau-of-the-Census", "max_stars_repo_head_hexsha": "07f183e0ecfb6eb528cd0474a01e0ebdbfe3a943", "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": "final project.r", "max_issues_repo_name": "Dr-Spicy/Murder-and-Marriage-Rates-Modeling-using-Linear-Regression-from-U.S.-Bureau-of-the-Census", "max_issues_repo_head_hexsha": "07f183e0ecfb6eb528cd0474a01e0ebdbfe3a943", "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": "final project.r", "max_forks_repo_name": "Dr-Spicy/Murder-and-Marriage-Rates-Modeling-using-Linear-Regression-from-U.S.-Bureau-of-the-Census", "max_forks_repo_head_hexsha": "07f183e0ecfb6eb528cd0474a01e0ebdbfe3a943", "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.5310344828, "max_line_length": 157, "alphanum_fraction": 0.6171328671, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6985119294445175}} {"text": "#Objetivo: introducir concepto de curva ROC\n\n#limpio la memoria\nrm(list=ls())\ngc()\n\nlibrary(\"data.table\")\n\nsetwd(\"E:/UBA/2019-II/DM en Finanzas/Dropbox Prof/datasets\")\n\n#cargo los datos\ndataset <- fread(\"201902.txt\")\n\n#creo una clase que se 1 cuando es BAJA+2 , y 0 en caso contrario\n#esto me simplifica las cuentas\ndataset[ , clase01:= as.numeric(clase_ternaria==\"BAJA+2\") ]\n\n\n#calculos basicos\nuniverso <- nrow(dataset )\npos_total <- sum(dataset$clase01 )\nneg_total <- universo - pos_total\n\n#tambien podria hacer\nneg_total <- sum( 1 - dataset$clase01 )\n\n\n#----------------\n\n#Dibujo la curva ROC del predicado mcuentas_saldo<= -120000\n\n#positivos del predicado\npos_pred <- sum( dataset[ (mcuentas_saldo<= -120000) , clase01] )\n\n#negativos del predicado\nneg_pred <- sum( dataset[ (mcuentas_saldo<= -120000) , 1 - clase01] )\n\n#Tener en cuenta que los NA's no se estan contando en este predicado !\n\n\n\n#la diagonal de la Curva Roc\nazar_neg <- c( 0, neg_total )\nazar_pos <- c( 0, pos_total )\n\n#grafico\nplot( azar_neg, \n azar_pos, \n type=\"n\",\n main=paste( \"ROC Curve\", \"(mcuentas_saldo<= -120000)\" ),\n xlab=\"neg\", \n ylab=\"pos\", \n pch=19)\n\n#dibujo la diagonal\nlines( azar_neg, azar_pos, type=\"l\" , col=\"black\", lwd=2)\n\n\n#para el predicado creo el vector con los tres puntos\nvneg <- c( 0, neg_pred, neg_total )\nvpos <- c( 0, pos_pred, pos_total )\n\n#dibujo la linea\nlines( vneg, vpos, type=\"l\" , col=\"green\", lwd=2)\n\n\n#Calculo AUC Area Under Curve\ntriangulo_area <- pos_pred*neg_pred/2 \ntrapecio_area <- (pos_pred + pos_total)*(neg_total-neg_pred) / 2\nAUC <- (triangulo_area + trapecio_area ) / (pos_total*neg_total)\n\n\n#----------------------\n# Creo una funcion para automatizar\n\npred_graficar = function(dataset, pcolumna, pvalor )\n{\n #calculos basicos\n universo <- nrow(dataset )\n pos_total <- sum(dataset$clase01 )\n neg_total <- universo - pos_total\n\n pos_pred <- sum( dataset[ get(pcolumna) <= pvalor , clase01] )\n neg_pred <- sum( 1 - dataset[ get(pcolumna) <= pvalor, clase01] )\n\n AUC <- (pos_pred*neg_pred + (pos_pred + pos_total)*(neg_total-neg_pred) ) / (2*pos_total*neg_total)\n\n\n #la diagonal\n azar_neg <- c( 0, neg_total )\n azar_pos <- c( 0, pos_total )\n\n #grafico\n plot( azar_neg, \n azar_pos, \n type=\"n\",\n main=paste( \"ROC Curve\", \"(\", pcolumna, \"<=\", pvalor, \")\", \"AUC=\", AUC ),\n xlab=\"neg\", \n ylab=\"pos\", \n pch=19)\n\n #dibujo la linea del azar\n lines( azar_neg, azar_pos, type=\"l\" , col=\"black\", lwd=2)\n\n #creo el vector con los tres puntos\n vneg <- c( 0, neg_pred, neg_total )\n vpos <- c( 0, pos_pred, pos_total )\n\n #dibujo la curva del predicado\n lines( vneg, vpos, type=\"l\" , col=\"green\", lwd=2)\n\n return( AUC )\n}\n#----------------------\n\n#algunos cortes de la variable mcuentas_saldo\npred_graficar( dataset, \"mcuentas_saldo\", -120000 )\npred_graficar( dataset, \"mcuentas_saldo\", 0 )\npred_graficar( dataset, \"mcuentas_saldo\", 10000 )\n\n#algunos cortes de la variable Visa_mconsumototal\npred_graficar( dataset, \"Visa_mconsumototal\", 200000 )\n\n#una variable que no esta correlacionada con la clase\npred_graficar( dataset, \"cliente_edad\", 40 )\n\n\n#una vieja conocida variable\npred_graficar( dataset, \"Visa_cuenta_estado\", 10 )\n\n#por que esta por debajo de la linea de azar ?\n\n", "meta": {"hexsha": "0cbb537c1f4aebc39e04e498f1c1fe08dda6114e", "size": 3338, "ext": "r", "lang": "R", "max_stars_repo_path": "elementary/ROC_01.r", "max_stars_repo_name": "ktavo/dm-finanzas-2019", "max_stars_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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": "elementary/ROC_01.r", "max_issues_repo_name": "ktavo/dm-finanzas-2019", "max_issues_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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": "elementary/ROC_01.r", "max_forks_repo_name": "ktavo/dm-finanzas-2019", "max_forks_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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": 25.0977443609, "max_line_length": 101, "alphanum_fraction": 0.6548831636, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6985119233752045}} {"text": "\nMaxHit=function(song){\n# song is a vector of 0's and 1's that represents the hits (0) and \n# misses (1) of the notes in order \n\n streak_lengths=diff(c(0,which(song==1),length(song)+1))-1\n max_streak=max(streak_lengths)\n \n # About these commands:\n # which(song==1) returns a vector indicating which on which notes (indices) a miss occurs\n # this is important for you because it will indicate the end of a streak\n # c(0,which(song==1),length(song)+1) creates a vector starting with 0 (indicates the beginning of the song),\n # then the locations of misses, and then the length of the song + 1 (indicates when the song has ended)\n \n return(max_streak)\n}\n\n# Hypothesis test based on the MaxHit method\nMaxHit_test = function(song,B=1000){\n # song is a vector of 0's and 1's that represents the hits (0) \n\t# and misses (1) of the notes in order\n\t# B is the number of new samples to generate\n\t\n\ttest_stat = MaxHit(song)\n\tn = length(song)\n\ttstar_b = numeric(B)\n\tfor(b in 1:B){\n\t\tsong_tmp = sample(song) # for permutation test\n#\t\tsong_tmp = sample(song,replace=T) # for non-parametric bootstrap\n#\t\tsong_tmp = rbinom(n,1,mean(song)) # for parametric bootstrap\n\t\ttstar_b[b] = MaxHit(song_tmp)\n\t}\n\t\n\t# calculate the two-sided p-value from the sampling distribution\n\tpval = 2*min(sum(tstar_b >= test_stat),sum(tstar_b <= test_stat))/B\n\t\t# calculate a one sided p-value\n#\tpval = sum(tstar_b >= test_stat)/B\n\treturn(pval)\n}\n\n# Examples using Songs A and B from Table 1\n\nsongA = c(1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0)\nMaxHit(songA)\nMaxHit_test(songA,5000)\n\n\nsongB = c(0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0)\nMaxHit(songB)\nMaxHit_test(songB,5000)\n", "meta": {"hexsha": "c08974864cfbd5e63d278e680de954b04d85df68", "size": 1675, "ext": "r", "lang": "R", "max_stars_repo_path": "GHSupplementaryFiles/AppendixC/top1streak.r", "max_stars_repo_name": "iramler/guitar_hero_jse", "max_stars_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "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": "GHSupplementaryFiles/AppendixC/top1streak.r", "max_issues_repo_name": "iramler/guitar_hero_jse", "max_issues_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "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": "GHSupplementaryFiles/AppendixC/top1streak.r", "max_forks_repo_name": "iramler/guitar_hero_jse", "max_forks_repo_head_hexsha": "daaa66120705cd66d517bd35a66d4151683f9480", "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.8431372549, "max_line_length": 121, "alphanum_fraction": 0.6895522388, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6985119183727038}} {"text": "=begin\n # sample-groebner02.rb\n\n require \"algebra\"\n \n P = MPolynomial(Rational)\n x, y, z = P.vars \"xyz\"\n f1 = x**2 + y**2 + z**2 -1\n f2 = x**2 + z**2 - y\n f3 = x - z\n \n coeff, basis = Groebner.basis_coeff([f1, f2, f3])\n basis.each_with_index do |b, i|\n p [coeff[i].inner_product([f1, f2, f3]), b]\n p coeff[i].inner_product([f1, f2, f3]) == b #=> true\n end\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "0b4dff19a4650a2cdc6a2811ed90c2f7d31608e0", "size": 396, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-groebner02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-groebner02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-groebner02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.8421052632, "max_line_length": 56, "alphanum_fraction": 0.5555555556, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6981750997461124}} {"text": "#' @name getpolar \n#' @rdname getpolar \n#' @title Calculates the angle of the link between two points to the x-Axis.\n#' @description\n#' This function calculates the angle of a vector defined by two points\n#' in radians. Optionally it can be converted to degrees.\n#' For the use of the Operations-Research-Sweep-Algorithm\n#' an offset angle can be set.\n#' It's als possible return positive values only (2pi will be added).\n#' @param n0 an object of class \\code{\\link{numeric}} with a length of 2 (x/y-coordinates) or a class derived from \\code{\\link{Node}}. Used as origin.\n#' @param n1 an object of class \\code{\\link{numeric}} with a length of 2 (x/y-coordinates) or a class derived from \\code{\\link{Node}}.\n#' @param ... see \\emph{Optional Values}\n#' @section Optional Parameters (\\code{...}):\t\n#' \\subsection{used by getpolar}{\n#' \\describe{ \n#'\t\t\\item{\\code{nonnegative}}{\n#'\t\t\t \\emph{optional} \\code{\\link{logical}}. Indicating if 2pi should be added to negative values. \\strong{Default} is \\code{TRUE}}\n#'\t\t\\item{\\code{deg}}{\n#'\t\t\t \\emph{optional} \\code{\\link{logical}}. Indicating if the result should be converted to degrees. \\strong{Default} is \\code{FALSE}}\n#'\t\t\\item{\\code{log}}{\n#'\t\t\t \\emph{optional} \\code{\\link{logical}}. Indicating if the calculations should be logged. \\strong{Default} is \\code{FALSE}}\n#'\t\t\\item{\\code{offset}}{\n#'\t\t\t \\emph{optional} \\code{\\link{numeric}}. Should be when using rotated coordinate systems. \\strong{Default} is 0. \\strong{Has to be provided in RADIANS!}}\n#' } \n#' }\n#' \\subsection{Forwarded to the follwowing functions}{\t\n#' \\itemize{\n#'\t\t\\item{\\code{...} is currently not forwared.}\n#' }\n#' }\n#'\n#' @keywords radians, polar-angle, polar, coordinates\n#' @export \n#' @return the angle as a value of class \\code{\\link{numeric}}.\n#' @author Dipl. Kfm. Felix Lindemann \\email{felix.lindemann@@hs-neu-ulm.de} \n#' \n#' Wissenschaftlicher Mitarbeiter\n#' Kompetenzzentrum Logistik\n#' Buro ZWEI, 17\n#'\n#' Hochschule fur angewandte Wissenschaften \n#' Fachhochschule Neu-Ulm | Neu-Ulm University \n#' Wileystr. 1 \n#' \n#' D-89231 Neu-Ulm \n#' \n#' \n#' Phone +49(0)731-9762-1437 \n#' Web www.hs-neu-ulm.de \n#'\n#' @references \n#'Bronstein 2008 Bronstein, I. N.: Taschenbuch der Mathematik.\n#'[CD-ROM-Ausg. der 7., voll. ueberarb. und erg. gedr. Ausg.].\n#'Frankfurt: Harri Deutsch, 2008 \nsetGeneric(\"getpolar\", function(n0,n1,...) standardGeneric(\"getpolar\")) \n\n#' @title distance between two \\code{\\link{Node}s}\n#' @description Calculates the euclidian distance between to nodes. Optional this distance can be multiplied by a \\code{costfactor} in order to convert the distance to cost-related value (such as time, costs, ...).\n#' \\deqn{ f(x) = \\sqrt((x_0-x_1)^2 + (y_0-y_1)^2) \\cdot costfactor }{ costfactor * ((x_0-x_1)^2 + (y_0-y_1)^2)^0.5 }\n#' @param n0 an object of class \\code{\\link{numeric}} with a length of 2 (x/y-coordinates) or a class derived from \\code{\\link{Node}}. Used as origin.\n#' @param n1 an object of class \\code{\\link{numeric}} with a length of 2 (x/y-coordinates) or a class derived from \\code{\\link{Node}}.\n#' @param ... \\emph{Optional Parameters} (See Below).\n#' \n#' @section Optional Parameters (\\code{...}): \n#' \\subsection{used by \\code{\\link{getDistance}}}{\n#' \\describe{ \n#' \\item{digits}{non negative Integer value for the number of digitis that has to be rounded to.} \n#' \\item{costfactor}{ \\code{\\link{numeric}} Optional Parameter. Used to transform the distance by a factor into costs. Default is \\code{1}.} \n#' } \n#' }\n#' \\subsection{Forwarded to the follwowing functions}{ \n#' You may want to check these functions for any other optional parameters.\n#' \\itemize{\n#' \\item{\\code{\\link{round}} called, if the parameter \\code{digits} is provided.} \n#' }\n#' } \n#' @name getDistance \n#' @docType methods\n#' @rdname getDistance\n#' @author Dipl. Kfm. Felix Lindemann \\email{felix.lindemann@@hs-neu-ulm.de} \n#' \n#' Wissenschaftlicher Mitarbeiter\n#' Kompetenzzentrum Logistik\n#' Buro ZWEI, 17\n#'\n#' Hochschule fur angewandte Wissenschaften \n#' Fachhochschule Neu-Ulm | Neu-Ulm University \n#' Wileystr. 1 \n#' \n#' D-89231 Neu-Ulm \n#' \n#' \n#' Phone +49(0)731-9762-1437 \n#' Web \\url{www.hs-neu-ulm.de/felix-lindemann/} \n#' \\url{http://felixlindemann.blogspot.de}\nsetGeneric(\"getDistance\", function(n0,n1, ...) standardGeneric(\"getDistance\"))\n\n\n \n", "meta": {"hexsha": "d10355c800fe42a51b87cb09f063b7b4c04c08a2", "size": 4379, "ext": "r", "lang": "R", "max_stars_repo_path": "R/00.Generics.r", "max_stars_repo_name": "felixlindemann/HNUORTools", "max_stars_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/00.Generics.r", "max_issues_repo_name": "felixlindemann/HNUORTools", "max_issues_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/00.Generics.r", "max_forks_repo_name": "felixlindemann/HNUORTools", "max_forks_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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": 43.79, "max_line_length": 215, "alphanum_fraction": 0.6789221283, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.698171504226839}} {"text": "REBOL [\r\n\tTitle: \"Red/System IEEE-754 library\"\r\n\tAuthor: \"Nenad Rakocevic\"\r\n\tFile: \t %IEEE-754.r\r\n\tTabs:\t 4\r\n\tRights: \"Copyright (C) 2000-2011-2015 Eric Long,-2018 Red Foundation. All rights reserved.\"\r\n\tLicense: \"BSD-3 - https://github.com/red/red/blob/master/BSD-3-License.txt\"\r\n\tComment: {\r\n\t\t64-bit split/to-native functions from http://www.nwlink.com/~ecotope1/reb/decimal.r\r\n\t\tAdded 32-bit support, compacted a bit the existing code.\r\n\t}\r\n]\r\n\r\nIEEE-754: context [\r\n\r\n\tspecials: [\r\n\t\tsingle [\r\n\t\t\t#INF\t#{7F800000}\r\n\t\t\t#INF-\t#{FF800000}\r\n\t\t\t#NaN\t#{7F200000}\t\t\t\t\t\t\t;-- Quiet NaN\r\n\t\t\t#0-\t\t#{80000000}\r\n\t\t]\r\n\t\tdouble [\r\n\t\t\t#INF\t#{7FF0000000000000}\r\n\t\t\t#INF-\t#{FFF0000000000000}\r\n\t\t\t#NaN\t#{7FF8000000000000}\t\t\t\t\t;-- Quiet NaN\r\n\t\t\t#0-\t\t#{8000000000000000}\r\n\t\t]\r\n\t]\r\n\r\n\tsplit64: func [\r\n\t\t\"Returns block containing three components of double floating point value\"\r\n\t\tn [number!] /local sign exp frac\r\n\t][\r\n\t\tsign: either negative? n [n: negate n 1][0]\r\n\r\n\t\teither zero? n [exp: frac: 0][\r\n\t\t\teither zero? 1024 - exp: to integer! log-2 n [\r\n\t\t\t\texp: 1023\r\n\t\t\t][\r\n\t\t\t\tif positive? (2 ** exp) - n [exp: exp - 1]\r\n\t\t\t]\r\n\t\t\tfrac: n / (2 ** exp)\r\n\r\n\t\t\teither positive? exp: exp + 1023 [\r\n\t\t\t\tfrac: frac - 1 \t\t\t\t\t;-- drop the first bit for normals\r\n\t\t\t\tfrac: frac * (2 ** 52) \t\t\t\t\t;-- make the remaining fraction an\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t;-- \"integer\"\r\n\t\t\t][\r\n\t\t\t\tfrac: 2 ** (51 + exp) * frac \t\t\t;-- denormals\r\n\t\t\t\texp: 0\r\n\t\t\t]\r\n\t\t]\r\n\t\treduce [sign exp frac]\r\n\t]\r\n\r\n\tto-binary64: func [\r\n\t\t\"convert a numerical value into native binary format\"\r\n\t\tn [number! issue!]\r\n\t\t/rev \"reverse binary output\"\r\n\t\t/local out sign exp frac\r\n\t][\r\n\t\teither issue? n [\r\n\t\t\tout: copy select specials/double next n\r\n\t\t][\r\n\t\t\tset [sign exp frac] split64 n\r\n\t\t\tout: make binary! 8\r\n\t\t\tloop 6 [\r\n\t\t\t\tinsert out to char! byte: frac // 256\r\n\t\t\t\tfrac: frac - byte / 256\r\n\t\t\t]\r\n\t\t\tinsert out to char! exp // 16 * 16 + frac\r\n\t\t\tinsert out to char! exp / 16 + (128 * sign)\r\n\t\t]\r\n\t\teither rev [copy reverse out][out]\r\n\t]\r\n\r\n\tsplit32: func [\r\n\t\t\"Returns block containing three components of single floating point value\"\r\n\t\tn [number!] /local sign exp frac\r\n\t][\r\n\t\tsign: either negative? n [n: negate n 1][0]\r\n\r\n\t\teither zero? n [exp: frac: 0][\r\n\t\t\teither zero? 128 - exp: to integer! log-2 n [\r\n\t\t\t\texp: 127\r\n\t\t\t][\r\n\t\t\t\tif positive? (2 ** exp) - n [exp: exp - 1]\r\n\t\t\t]\r\n\t\t\tfrac: n / (2 ** exp)\r\n\r\n\t\t\teither positive? exp: exp + 127 [\r\n\t\t\t\tfrac: frac - 1\r\n\t\t\t\tfrac: frac * (2 ** 23) \t\t\t\t\t;-- make the remaining fraction an \"integer\"\r\n\t\t\t][\r\n\t\t\t\tfrac: 2 ** (22 + exp) * frac \t\t\t;-- denormals\r\n\t\t\t\texp: 0\r\n\t\t\t]\r\n\t\t\tfrac: to integer! frac + .5\r\n\t\t]\r\n\t\treduce [sign exp frac]\r\n\t]\r\n\r\n\tto-binary32: func [\r\n\t\t\"convert a numerical value into native binary format\"\r\n\t\tn [number! issue!]\r\n\t\t/rev \"reverse binary output\"\r\n\t\t/local out sign exp frac\r\n\t][\r\n\t\teither issue? n [\r\n\t\t\tout: copy select specials/single next n\r\n\t\t][\r\n\t\t\tset [sign exp frac] split32 n\r\n\t\t\tout: make binary! 4\r\n\t\t\tloop 2 [\r\n\t\t\t\tinsert out to char! byte: frac // 256\r\n\t\t\t\tfrac: frac - byte / 256\r\n\t\t\t]\r\n\t\t\tinsert out to char! exp * 128 // 256 + frac\r\n\t\t\tinsert out to char! exp / 2 + (128 * sign)\r\n\t\t]\r\n\t\teither rev [copy reverse out][out]\r\n\t]\r\n]", "meta": {"hexsha": "407b16f02d02be0e934a40f46d73a7607a12d06f", "size": 3193, "ext": "r", "lang": "R", "max_stars_repo_path": "system/utils/IEEE-754.r", "max_stars_repo_name": "toomasv/red", "max_stars_repo_head_hexsha": "ca0a2d5d5ff7864ab77cf9aefe04822cc881cb58", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-03-30T16:10:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-15T13:57:45.000Z", "max_issues_repo_path": "system/utils/IEEE-754.r", "max_issues_repo_name": "toomasv/red", "max_issues_repo_head_hexsha": "ca0a2d5d5ff7864ab77cf9aefe04822cc881cb58", "max_issues_repo_licenses": ["BSL-1.0", "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": "system/utils/IEEE-754.r", "max_forks_repo_name": "toomasv/red", "max_forks_repo_head_hexsha": "ca0a2d5d5ff7864ab77cf9aefe04822cc881cb58", "max_forks_repo_licenses": ["BSL-1.0", "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.75, "max_line_length": 95, "alphanum_fraction": 0.5706232383, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6979499024033825}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 08\n\nrm(list = ls())\n\nobserved <- c(38, 55, 54, 41, 62)\n\n\n\n(k <- length(observed))\n# 5\n\n(n <- sum(observed))\n# 250\n\n(expected <- n * 1 / k )\n# 50\n\n(Q <- sum((observed - expected) ^ 2 / expected))\n# 8.2\n\n(pvalue <- 1 - pchisq(Q, df = k - 1))\n# 0.0845206445489823\n", "meta": {"hexsha": "9ef69a9ff4956429140ebbd591d9343556bc7295", "size": 353, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-08.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-08.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-08.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "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": 14.7083333333, "max_line_length": 63, "alphanum_fraction": 0.5892351275, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6978984964620596}} {"text": "# Prediction efficiency in two ways\nprediction_accuracy <- function(predicted, empirical) {\n # Parameters:\n # predicted matrix of predicted interactions\n # empirical matrix of empirical interactions\n\n # Output vector of a, b, c, d, and TSS\n # a number of links predicted (1) and observed (1)\n # b number predicted (1) but not observed (0)\n # c number predicted absent (0) but observed (1)\n # d number of predicted absent (0) and observed absent (0)\n # TSS TSS = (ad-\u0002bc)/[(a+c)(b+d)]\n # \"[...] quantifies the proportion of prediction success relative to false predictions\n # and returns values ranging between 1 (perfect predictions) and \u00021 (inverted forecast)\n # (Allouche, Tsoar & Kadmon 2006).\" Gravel et al. 2013\n # ScoreY1 Fraction of 1 correctly predicted a / (a + c)\n # ScoreY0 Fraction of 0 correctly predicted d / (b + d)\n # FSS FSS = ScoreY1 + ScoreY0 / sum(a, b, c, d)^2\n\n if(identical(colnames(predicted), colnames(empirical)) == FALSE ||\n identical(rownames(predicted), rownames(empirical)) == FALSE ||\n identical(dim(predicted), dim(empirical)) == FALSE) {\n print('matrices need to have same dimensions and row and column names')\n break\n }\n\n efficiency <- numeric(8)\n names(efficiency) <- c('a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')\n\n for(i in 1:ncol(predicted)){\n for(j in 1:nrow(predicted)) {\n if(predicted[i,j] == 1 && empirical[i,j] == 1) {\n efficiency[1] <- efficiency[1] + 1\n } else if(predicted[i,j] == 1 && empirical[i,j] == 0) {\n efficiency[2] <- efficiency[2] + 1\n } else if(predicted[i,j] == 0 && empirical[i,j] == 1) {\n efficiency[3] <- efficiency[3] + 1\n } else if(predicted[i,j] == 0 && empirical[i,j] == 0) {\n efficiency[4] <- efficiency[4] + 1\n }\n }\n }\n\n a <- efficiency[1]\n b <- efficiency[2]\n c <- efficiency[3]\n d <- efficiency[4]\n\n efficiency[5] <- ((a * d) - (b * c)) / ((a + c) * (b + d)) # TSS\n efficiency[6] <- a / (a + c) # ScoreY1\n efficiency[7] <- d / (b + d) # ScoreY0\n efficiency[8] <- (a + d) / sum(a, b, c, d) # FSS\n\n return(efficiency)\n}\n", "meta": {"hexsha": "16bb050256cef003ce99d04c2c76429b39ebd9d3", "size": 2461, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/prediction_accuracy.r", "max_stars_repo_name": "david-beauchesne/predicting_interactions", "max_stars_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-08-12T11:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-09T18:16:12.000Z", "max_issues_repo_path": "Script/prediction_accuracy.r", "max_issues_repo_name": "david-beauchesne/predicting_interactions", "max_issues_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-12T14:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T15:25:21.000Z", "max_forks_repo_path": "Script/prediction_accuracy.r", "max_forks_repo_name": "david-beauchesne/predicting_interactions", "max_forks_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-12T10:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-12T10:46:53.000Z", "avg_line_length": 43.9464285714, "max_line_length": 109, "alphanum_fraction": 0.519707436, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6978166565506566}} {"text": "#@reemuru\n#data mining\n#k-means clustering\n\n#intialize library for kmeans clustering and elbow method\nlibrary(NbClust)\nlibrary(factoextra)\n\n#set the working directory\nsetwd(\"./k-means/\")\n\n#reproducible output\nset.seed(1234)\n\n#load sensor readings file with headers in the first row \nsensors<-read.csv(file = \"sensor_readings_24.csv\", header = TRUE, sep = \",\")\n\n#summary stats\nsummary(sensors)\n\n#dataset structure\nstr(sensors)\n\n#Class variable distribution\nplot(sensors$Class)\n\n#create correlation matrix with heatmap\ncormat <- round(cor(sensors[1:24]),2)\nhead(cormat)\nlibrary(reshape2)\nmelted_cormat <- melt(cormat)\nhead(melted_cormat)\nlibrary(ggplot2)\nggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) +\n geom_tile()\n\n#copy the dataset\nsensors2<-sensors\n#remove the class variable\nsensors2$Class<-NULL\n\n#scale the dataset\nsensors2[1:24]<-scale(sensors2[1:24])\n\n#store the model with 4 clusters\nkc<-kmeans(sensors2, 4, iter.max = 40)\n\n\n#print the model output\nprint(kc)\n\n#between sum of squares\nkc$betweenss\n\n#compare the model with the classes\ntable(sensors$Class, kc$cluster)\n\n#model variations\n#K-means method with k=2\nkc<-kmeans(sensors2, 2, iter.max = 20)\nkc\nkc$betweenss\n#K-means method with k=3\nkc<-kmeans(sensors2, 3, iter.max = 30)\nkc\nkc$betweenss\n#K-means method with k=5\nkc<-kmeans(sensors2, 5, iter.max = 50)\nkc\nkc$betweenss\n\n#minimum within cluster sum of squares with 3 clusters\n\n#model refinement\n#the object is only moving clockwise therefore slight turns should be removed\n#subset for no slight turns and re-factor\nmodsensors <- subset(sensors, sensors$Class!=\"Slight-Left-Turn\")\nmodsensors <- subset(modsensors, modsensors$Class!=\"Slight-Right-Turn\")\nmodsensors$Class<-factor(modsensors$Class)\n\n#verify dataset structure\nstr(modsensors)\n\n#copy the modified dataset\nmodsensors2<-modsensors\n\n#remove class from copied dataset\nmodsensors2$Class<-NULL\n\n#scale the dataset\nmodsensors2[1:24]<-scale(modsensors2[1:24])\n\n#K-means method with k= 2\nkc<-kmeans(modsensors2, 2, iter.max = 20)\n\n#cross-tabulation\ntable(modsensors$Class, kc$cluster)\n\n#dataviz\n#verify cluster selection with the elbow method, within groups sum of squares\nfviz_nbclust(modsensors2, kmeans, method = \"wss\") +\n geom_vline(xintercept = 2, linetype = 2)+\n labs(subtitle = \"Elbow method\")\n\nclusplot(modsensors2, kc$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)\n\n#higher dimensional plot\n#dataviz\nlibrary(rgl)\nnewkc <- data.frame(modsensors2, K=kc$cluster)#Include the number of cluster in the data set\npcdf <- princomp(modsensors2,cor=T,score=T)\nsummary(pcdf)#Compute the validity of each component/dimension\nplot3d(pcdf$scores, col=newkc$K)#Create a 3D plot", "meta": {"hexsha": "f847fe74bb0314c869057c1d6d9819a0ddd48c89", "size": 2660, "ext": "r", "lang": "R", "max_stars_repo_path": "k-means/k-means.r", "max_stars_repo_name": "reemuru/data_mining", "max_stars_repo_head_hexsha": "6ca0b2405dbc38b39495a30913db439eae68d5f6", "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": "k-means/k-means.r", "max_issues_repo_name": "reemuru/data_mining", "max_issues_repo_head_hexsha": "6ca0b2405dbc38b39495a30913db439eae68d5f6", "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": "k-means/k-means.r", "max_forks_repo_name": "reemuru/data_mining", "max_forks_repo_head_hexsha": "6ca0b2405dbc38b39495a30913db439eae68d5f6", "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": 23.5398230088, "max_line_length": 92, "alphanum_fraction": 0.7654135338, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6977784394494375}} {"text": "return(switch(kernel,\n gaussian = 1/(2*sqrt(pi)),\n rectangular = sqrt(3)/6,\n triangular = sqrt(6)/9,\n epanechnikov = 3/(5*sqrt(5)),\n biweight = 5*sqrt(7)/49,\n cosine = 3/4*sqrt(1/3 - 2/pi^2),\n optcosine = sqrt(1-8/pi^2)*pi^2/16\n ))", "meta": {"hexsha": "c5e820f9f06aac9d20f6558f37da53ebfc8e8491", "size": 399, "ext": "r", "lang": "R", "max_stars_repo_path": "testData/parser/r/NewLineAfterKeywordArgument.r", "max_stars_repo_name": "DeagleGross/Rplugin", "max_stars_repo_head_hexsha": "8a2cfd87f732e658b3de07a202c058a9a9d63f11", "max_stars_repo_licenses": ["MIT", "BSD-2-Clause", "Apache-2.0"], "max_stars_count": 171, "max_stars_repo_stars_event_min_datetime": "2015-01-25T11:23:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T23:19:46.000Z", "max_issues_repo_path": "testData/parser/r/NewLineAfterKeywordArgument.r", "max_issues_repo_name": "DeagleGross/Rplugin", "max_issues_repo_head_hexsha": "8a2cfd87f732e658b3de07a202c058a9a9d63f11", "max_issues_repo_licenses": ["MIT", "BSD-2-Clause", "Apache-2.0"], "max_issues_count": 224, "max_issues_repo_issues_event_min_datetime": "2015-01-17T04:19:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T12:19:10.000Z", "max_forks_repo_path": "testData/parser/r/NewLineAfterKeywordArgument.r", "max_forks_repo_name": "DeagleGross/Rplugin", "max_forks_repo_head_hexsha": "8a2cfd87f732e658b3de07a202c058a9a9d63f11", "max_forks_repo_licenses": ["MIT", "BSD-2-Clause", "Apache-2.0"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2015-02-10T20:30:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T10:24:32.000Z", "avg_line_length": 44.3333333333, "max_line_length": 56, "alphanum_fraction": 0.35839599, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6977692368123619}} {"text": "# James Rekow\r\n\r\nfirstDeriv = function(y, deltax = 1){\r\n \r\n # ARGS: y - numeric vector of y-values\r\n # deltax - mesh width of corresponding x-values\r\n #\r\n # RETURNS: a numeric vector of the same length as y whose elements are the\r\n # centered first derivative of y at each interior point, and one-sided\r\n # derivatives of y at the endpoints\r\n \r\n N = length(y)\r\n return((0.5 / deltax) * c(2 * (y[2] - y[1]), (y[3:N] - y[1:(N - 2)]), 2 * (y[N] - y[N - 1])))\r\n \r\n} # end firstDeriv function\r\n", "meta": {"hexsha": "d8002ec53c6b5cde93fa7f5d9991da898ce71669", "size": 536, "ext": "r", "lang": "R", "max_stars_repo_path": "firstDeriv.r", "max_stars_repo_name": "JamesRekow/GLV_Model", "max_stars_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "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": "firstDeriv.r", "max_issues_repo_name": "JamesRekow/GLV_Model", "max_issues_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-08T20:21:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T20:21:25.000Z", "max_forks_repo_path": "firstDeriv.r", "max_forks_repo_name": "JamesRekow/GLV_Model", "max_forks_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "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.5, "max_line_length": 96, "alphanum_fraction": 0.5671641791, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6976768855375334}} {"text": "#!/usr/bin/env Rscript\n\n# This implementation uses a custom function on a vector rather than a \n# loop which is kinda neat, but can be memory consuming.\n\nnumslices <- 100000000\n\nargs <- commandArgs(trailingOnly=TRUE)\n\nif (length(args)>0) {\n numslices <- strtoi(args)\n}\n\ncat(\"Calculating PI using:\\n\")\ncat(\" \", numslices, \"slices\\n\")\ncat(\" 1 process\\n\")\n\nstart <- Sys.time()\n\n# Define our function\ny <- function(x) {\n 1/(1+(x^2))\n}\n\n# Sum our function applied to the slices.\nmypi <- (4 * sum(y((1.0/numslices) * (0.5:numslices-0.5))))/numslices\n\nstop <- Sys.time()\nelapsed <- stop - start\n\ncat(\"Obtained value of PI:\", mypi, \"\\n\")\ncat(\"Time taken:\", elapsed, \"seconds\\n\")\n\n", "meta": {"hexsha": "5a2c2dd3da5fff918a3389799e9ae7514d6d1cfd", "size": 675, "ext": "r", "lang": "R", "max_stars_repo_path": "r_pi_func_dir/pi.r", "max_stars_repo_name": "adrianjhpc/pi_examples", "max_stars_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-04-13T11:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:22:06.000Z", "max_issues_repo_path": "r_pi_func_dir/pi.r", "max_issues_repo_name": "adrianjhpc/pi_examples", "max_issues_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-05-24T11:28:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T16:22:17.000Z", "max_forks_repo_path": "r_pi_func_dir/pi.r", "max_forks_repo_name": "adrianjhpc/pi_examples", "max_forks_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-12T15:08:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T09:35:21.000Z", "avg_line_length": 19.8529411765, "max_line_length": 71, "alphanum_fraction": 0.6607407407, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6975354087221204}} {"text": "#!/usr/bin/env Rscript\n\n# Author : Bhishan Poudel\n# Date : Feb 11, 2016\n# Program :\n\n# Setting working directory\nthis.dir <- dirname(parent.frame(2)$ofile)\nsetwd(this.dir)\n\n# Start device driver to save output\n#postscript( file = \"milkyway.eps\", height = 12, width = 8)\n\n# Read magnitudes for Milky Way and M 31 globular clusters\nGC1 <- read.table(\"GlobClus_MWG.dat\",\n header = T)\nGC2 <- read.table(\"GlobClus_M31.dat\",\n header = T)\nK1 <- GC1[, 2]\nK2 <- GC2[, 2]\ncat(\"summary of K1 \\n\")\nprint(summary(K1))\ncat(\"\\n summary of K1 \\n\")\nprint(summary(K2))\n\n# Three estimates of the distance modulus to M 31\nDMmn <- mean(K2) - mean(K1)\nprint(DMmn)\nsigDMmn <- sqrt(var(K1) / length(K1) + var(K2) / length(K2))\nprint(sigDMmn)\nDMmed <- median(K2) - median(K1)\nprint(DMmed)\nsigDMmed <-\n sqrt(mad(K1) ^ 2 / length(K1) + mad(K2) ^ 2 / length(K2))\nprint(sigDMmed)\nwilcox.test(K2, K1, conf.int = T)\n\n# e.d.f., quantile and Q-Q plots for globular cluster magnitudes\nplot(\n ecdf(K1),\n cex.points = 0,\n verticals = T,\n xlab = \"K (mag)\",\n ylab = \"e.d.f.\",\n main = \"\"\n)\nplot(\n ecdf(K2 - 24.90),\n cex.points = 0,\n verticals = T,\n add = T\n)\ntext(-7.5, 0.8, lab = \"MWG\")\ntext(-10.5, 0.9, lab = \"M 31\")\npar(mfrow = c(1, 3))\nqqplot(\n K1,\n K2 - 24.90,\n pch = 20,\n cex.axis = 1.3,\n cex.lab = 1.3,\n xlab = \"MWG\",\n ylab = \"M31 - 24.90\",\n main = \"\"\n)\nqqnorm(\n K1,\n pch = 20,\n cex.axis = 1.3,\n cex.lab = 1.3,\n main = \"\"\n)\nqqline(K1, lty = 2, lwd = 1.5)\ntext(-2.5, -6, pos = 4, cex = 1.3, 'MWG normal QQ plot')\nqqnorm(\n K2 - 24.90,\n pch = 20,\n cex.axis = 1.3,\n cex.lab = 1.3,\n main = \"\"\n)\nqqline(K2 - 24.90, lty = 2, lwd = 1.5)\ntext(-3, -7.5, pos = 4, cex = 1.3, 'M31 normal QQ plot')\npar(mfrow = c(1, 1))\n\n# Plot e.d.f. with confidence bands\n#install.packages('sfsmisc')\nlibrary('sfsmisc')\necdf.ksCI(K1, ci.col = 'black')\n\n# Nonparametric tests for normality\n#install.packages('nortest')\nlibrary(nortest)\nprint(cvm.test(K1))\nprint(cvm.test(K2))\nprint(ad.test(K1))\nprint(ad.test(K2))\n\n\n\n# Turn off device driver\n#dev.off()\n", "meta": {"hexsha": "ce5880749e2fb20e465e2950768cdcd5f476ba54", "size": 2119, "ext": "r", "lang": "R", "max_stars_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap5/milkyway.r", "max_stars_repo_name": "bhishanpdl/AstroSeminar_OU", "max_stars_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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": "AstroSeminar2019Spring/ModernStatistics_R/chap5/milkyway.r", "max_issues_repo_name": "bhishanpdl/AstroSeminar_OU", "max_issues_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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": "AstroSeminar2019Spring/ModernStatistics_R/chap5/milkyway.r", "max_forks_repo_name": "bhishanpdl/AstroSeminar_OU", "max_forks_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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.572815534, "max_line_length": 64, "alphanum_fraction": 0.584237848, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.6974473444606049}} {"text": "closest.pairs <- function(x, y=NULL, ...){\n # takes two-column object(x,y-values), or creates such an object from x and y values\n if(!is.null(y)) x <- cbind(x, y)\n\n distances <- dist(x)\n min.dist <- min(distances)\n point.pair <- combn(1:nrow(x), 2)[, which.min(distances)]\n\n cat(\"The closest pair is:\\n\\t\",\n sprintf(\"Point 1: %.3f, %.3f \\n\\tPoint 2: %.3f, %.3f \\n\\tDistance: %.3f.\\n\",\n x[point.pair[1],1], x[point.pair[1],2],\n x[point.pair[2],1], x[point.pair[2],2],\n min.dist),\n sep=\"\" )\n c( x1=x[point.pair[1],1],y1=x[point.pair[1],2],\n x2=x[point.pair[2],1],y2=x[point.pair[2],2],\n distance=min.dist)\n }\n", "meta": {"hexsha": "72cbacc69f824864fb876a347b4db68c08e84aa0", "size": 712, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-3.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/Closest-pair-problem/R/closest-pair-problem-3.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/Closest-pair-problem/R/closest-pair-problem-3.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": 37.4736842105, "max_line_length": 90, "alphanum_fraction": 0.5210674157, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.697388856634866}} {"text": "#' Global empirical relation method for paleoslope inversion\n#'\n#' \\code{trampush_slp} calculates the slope of an ancient river, provided you know the flow depth and the grain size of the bed material. Implemented from Trampush et al. (2014)\n#' @param Dbed The median grain size of bedload sediments in meters.\n#' @param H The paleoflow depth in meters.\n#' @return Returns a vector \\code{S}, the dimensionless slope.\n#' @export\n\n## Inversion for Paleoslope based on Trampush 2014\n## Eric Barefoot\n## April 2018\n\n# This function provides functionality for computing paleoslope based on a method described by Sheila Trampush in a 2014 paper.\n\n# describe inputs and other stuff needed\n\n# Trampush et al. use a Bayesian approach for paleohydraulic inversion, meaning that the coefficients that they describe for the empirical fit each have a distribution. They provide percentiles for the distribution in their Table 1.\n# In this way, we can ascribe ranges for the coefficients, and potentially provide a range of estimates of paleoslope accordingly. I think this means we can have confidence intervals, but I'm not sure about that.\n# Initially, the user is allowed to select a percentile, and that percentile will be chosen for each parameter.\n\n# In the future, users should be allowed to vary each parameter individually.\n\ntrampush_slp = function(Dbed, H, perc = 50) {\n\n a0sp = smooth.spline(y = c(-2.14, -2.10, -2.08, -2.05, -2.01), x = c(2.5,25,50,75,97.5))\n a1sp = smooth.spline(y = c(0.222, 0.244, 0.254, 0.266, 0.287), x = c(2.5,25,50,75,97.5))\n a2sp = smooth.spline(y = c(-1.18, -1.12, -1.09, -1.06, -1.00), x = c(2.5,25,50,75,97.5))\n\n logS = predict(a0sp, x = perc)$y + predict(a1sp, perc)$y * log10(Dbed) + predict(a2sp, perc)$y * log10(H)\n\n return(S = 10^logS)\n\n}\n", "meta": {"hexsha": "57d35d05af9c888d0334709c15e15f175333ee1a", "size": 1776, "ext": "r", "lang": "R", "max_stars_repo_path": "R/trampush_slope_method.r", "max_stars_repo_name": "ericbarefoot/paleohydror", "max_stars_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "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/trampush_slope_method.r", "max_issues_repo_name": "ericbarefoot/paleohydror", "max_issues_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-17T16:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-17T16:32:53.000Z", "max_forks_repo_path": "R/trampush_slope_method.r", "max_forks_repo_name": "ericbarefoot/paleohydror", "max_forks_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "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.2352941176, "max_line_length": 232, "alphanum_fraction": 0.7291666667, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657177, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6972559373250949}} {"text": "library(tidyverse)\n\nnobs <- 256^3\ntable_id_only <- tibble(id = 1:nobs)\ntable_rgb_full <- mutate(table_id_only,\n red = (id-1)%/%(256^2),\n green = ((id-1)%%(256^2))%/%256,\n blue = ((id-1)%%(256^2))%%256,\n # For the formula below, see https://www.w3.org/TR/WCAG20-TECHS/G17.html\n red_srgb = red / 255,\n green_srgb = green / 255,\n blue_srgb = blue / 255,\n r = ifelse(red_srgb > 0.03928,\n ((red_srgb + 0.055)/1.055)^2.4,\n red_srgb / 12.92),\n g = ifelse(green_srgb > 0.03928,\n ((green_srgb + 0.055)/1.055)^2.4,\n green_srgb / 12.92),\n b = ifelse(blue_srgb > 0.03928,\n ((blue_srgb + 0.055)/1.055)^2.4,\n blue_srgb / 12.92),\n luminance = 0.2126*r + 0.7152*g + 0.0722*b,\n contrast_ratio = round((luminance + 0.05)/0.05, digits = 2),\n # https://en.wikipedia.org/wiki/Hue#Defining_hue_in_terms_of_RGB\n max = ifelse( red >= green & red >= blue, red,\n ifelse( green > red & green >= blue, green, blue)\n ),\n min = ifelse( red <= green & red <= blue, red,\n ifelse( green < red & green <= blue, green, blue)\n ),\n chroma = max - min,\n hue = round(ifelse( chroma == 0, NA,\n ifelse( max == red & min == blue, 60*(green-min)/chroma,\n ifelse( max == green & min == blue, 60*(2-(red-min)/chroma),\n ifelse( max == green & min == red, 60*(2+(blue-min)/chroma),\n ifelse( max == blue & min == red, 60*(4-(green-min)/chroma),\n ifelse( max == blue & min == green, 60*(4+(red-min)/chroma), 60*(6-(blue-min)/chroma))\n )\n )\n )\n )\n ))\n)\n\ntable_rgb <- select(table_rgb_full, id, red, green, blue, contrast_ratio, hue, chroma)\nwrite_csv(table_rgb, \"rgbColorCodes.csv\")\n", "meta": {"hexsha": "eafffb013cc2cc3073b6d82fceaeb9d39c35f12c", "size": 1989, "ext": "r", "lang": "R", "max_stars_repo_path": "server/prisma/rgbColorCodes.r", "max_stars_repo_name": "masakudamatsu/equiluminant-color-picker", "max_stars_repo_head_hexsha": "2c5d92fa0a1482e7664673f0672db70106893535", "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": "server/prisma/rgbColorCodes.r", "max_issues_repo_name": "masakudamatsu/equiluminant-color-picker", "max_issues_repo_head_hexsha": "2c5d92fa0a1482e7664673f0672db70106893535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 75, "max_issues_repo_issues_event_min_datetime": "2020-10-01T07:12:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T12:33:42.000Z", "max_forks_repo_path": "server/prisma/rgbColorCodes.r", "max_forks_repo_name": "masakudamatsu/equiluminant-color-picker", "max_forks_repo_head_hexsha": "2c5d92fa0a1482e7664673f0672db70106893535", "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.3191489362, "max_line_length": 109, "alphanum_fraction": 0.4806435395, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6972051222001596}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 07\n\nrm(list = ls())\n\nobserved <- c(20, 30, 20, 25, 15, 10)\n\n(k <- length(observed))\n# 6\n\n(n <- sum(observed))\n# 120\n\n(expected <- n * 1 / k )\n# 20\n\n\n(Q <- sum((observed - expected) ^ 2 / expected))\n# 12.5\n\n(pvalue <- 1 - pchisq(Q, df = k - 1))\n# 0.0285431233261675\n", "meta": {"hexsha": "20fb03544552407bf6a35dc48272c2cb26f47abd", "size": 357, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-07.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-07.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-07.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "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": 15.5217391304, "max_line_length": 63, "alphanum_fraction": 0.5910364146, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.697183764714605}} {"text": "# https://www.hackerrank.com/challenges/s10-normal-distribution-1/problem\nlibrary(\"magrittr\")\nxbar <- 20\nstdx <- 2\n\nq1 <- 19.5\nq2lower <- 20\nq2upper <- 22\n\n\na1 <- pnorm(q1, mean = xbar, sd = stdx)\nhour20 <- pnorm(q2lower, mean = xbar, sd = stdx)\nhour22 <- pnorm(q2upper, mean = xbar, sd = stdx)\na2 <- hour22 - hour20\n\nhour18 <- pnorm(18, mean = xbar, sd = stdx)\n\nsixeight <- hour22 - hour18 #should be about 68% since it's mean +- 1 sd\nround(a1, digits = 3) %>% cat(\"\\n\")\nround(a2, digits = 3) %>% cat()", "meta": {"hexsha": "d0606660f0cbfeefcf1d33c59c69e27f10cd40d9", "size": 503, "ext": "r", "lang": "R", "max_stars_repo_path": "HackerRankNormalDistribution1.r", "max_stars_repo_name": "DU-ds/MiscRScripts", "max_stars_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "HackerRankNormalDistribution1.r", "max_issues_repo_name": "DU-ds/MiscRScripts", "max_issues_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "HackerRankNormalDistribution1.r", "max_forks_repo_name": "DU-ds/MiscRScripts", "max_forks_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": 25.15, "max_line_length": 73, "alphanum_fraction": 0.6401590457, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.696994392517792}} {"text": "# This function samples k indices from 1:n starting with very dense sampling\n# (every value) and then getting more and more sparse\n\n#' Sampling for qq plots\n#' \n#' Returns k indices between 1:max.idx (x) such that -log(x/n) is uniformly\n#' distributed. This is useful to reduce overplotting when plotting\n#' log-transformed uniform data (such as p-values in a qq plot).\n#' \n#' @examples\n#' n <- 1e5\n#' x <- sort(runif(n))\n#' thin.idx <- thin(n, 500)\n#' par(mfcol=c(1, 2))\n#' plot(-log10(1:n/n), -log10(x), ann=FALSE)\n#' plot(-log10(thin.idx/n), -log10(x[thin.idx]), ann=FALSE)\n#' \n#' @export\nthin <- function(n, k=2000, max.idx=n) {\n \n if ( max.idx > n ) max.idx <- n\n if ( max.idx <= k ) return (1:max.idx)\n \n # Generate k samples between 1 and max.idx\n # such that -log10(x/n) is uniformly distributed\n x <- round(max.idx*exp(-(k:1)/k*log(n)))\n \n # Ensure each x is unique (Equivalently, diff(x) != 0)\n prev <- 0\n offset <- 0\n \n for ( i in 1:k ) {\n if ( x[i] + offset == prev ) {\n offset <- offset + 1\n } else if ( x[i] + offset > prev + 1 && offset > 0 ) {\n if ( x[i] > prev ) {\n offset <- 0\n } else {\n offset <- prev + 1 - x[i]\n }\n }\n prev <- x[i] <- x[i] + offset\n }\n \n x\n}\n\n#' Fast QQ plots\n#' \n#' QQ plots with lots of points can be slow. Since most of the points overlap\n#' we don't actually have to plot all of them (and in most cases the output\n#' will be identical.)\n#' \n#' This function will take a value k (default 2000) and sample that many\n#' pvalues in an intelligent way such that we don't lose information, then\n#' plot the log observed vs expected pvals in a nice way.\n#' \n#' The optimal value of k depends on the resolution/size of the plot. Very high\n#' resolution or very large plots may need larger k to look correct.\n#' \n#' Additional arguments in ... are passed to plot().\n#' \n#' @export\nfastqq <- function(pvals, k=2000, ...) {\n \n np <- length(pvals)\n thin.idx <- thin(np, k)\n \n thin.cint.95 <- qbeta(0.95, thin.idx, np - thin.idx + 1)\n thin.cint.05 <- qbeta(0.05, thin.idx, np - thin.idx + 1)\n \n thin.logp.exp <- -log10(thin.idx/np)\n thin.logp.obs <- -log10(pvals[order(pvals)[thin.idx]])\n \n plot(thin.logp.exp, thin.logp.obs, xlab=expression(-log[10](p[expected])), ylab=expression(-log[10](p[observed])), ...)\n abline(0, 1, col='gray', lty=2)\n lines(thin.logp.exp, -log10(thin.cint.95), lty=2, col='red')\n lines(thin.logp.exp, -log10(thin.cint.05), lty=2, col='red')\n}\n\n#' @export\nthin.qqplot <- function(pvals, thin.idx=NULL, k=2000, ...) {\n warning('This function is deprecated, use fastqq')\n fastqq(pvals, k, ...)\n}", "meta": {"hexsha": "89838f06d9b5c5ab665c3d421c8bc96c6a4e7d67", "size": 2625, "ext": "r", "lang": "R", "max_stars_repo_path": "R/qq_plot.r", "max_stars_repo_name": "sushilashenoy/zoom.plot", "max_stars_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-30T22:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-14T22:13:21.000Z", "max_issues_repo_path": "R/qq_plot.r", "max_issues_repo_name": "sushilashenoy/zoom.plot", "max_issues_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-30T22:17:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-23T16:18:28.000Z", "max_forks_repo_path": "R/qq_plot.r", "max_forks_repo_name": "sushilashenoy/zoom.plot", "max_forks_repo_head_hexsha": "036aa60980fdf7d86b5168f08e63aa13ca1f9e4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-20T19:14:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T19:14:21.000Z", "avg_line_length": 30.8823529412, "max_line_length": 121, "alphanum_fraction": 0.619047619, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6968270189937095}} {"text": "garage1=c(17.6,20.2,19.5,11.3,13.0,16.3,15.3,16.2,12.2,14.8,21.3,22.1,16.9,17.6,18.4)\r\ngarage2=c(17.3,19.1,18.4,11.5,12.7,15.8,14.9,15.3,12.0,14.2,21.0,21.0,16.1,16.7,17.5)\r\nt.test(garage1,garage2,paired = TRUE)\r\ntvalue=qt(1-0.05,14)\r\n# t>tvale we reject H0 and conclude that mean repair estimate for garage I is greater than that for garage II\r\n\r\n", "meta": {"hexsha": "97924a58cd1bbf4677659dec5aeb73c8b9d3d34e", "size": 350, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH6/EX6.8/Ex6_8.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH6/EX6.8/Ex6_8.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH6/EX6.8/Ex6_8.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 50.0, "max_line_length": 112, "alphanum_fraction": 0.6742857143, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.696816098303901}} {"text": "#' rexp\n#' \n#' Generate from a exponential distribution using a gpu.\n#' \n#' @details\n#' We use the cuRAND uniform generator together with the fact that if\n#' \\eqn{X \\sim U(0, 1)} then \\eqn{Y = -\\lambda^{-1}\\log(X) \\sim Exp(\\lambda)}.\n#' \n#' @param n\n#' The number of values to generate\n#' @param rate\n#' Parameter for exponential random variables.\n#' @param seed \n#' Seed for the random number generation.\n#' @param type\n#' 'double' or 'float'\n#' \n#' @references\n#' Casella, G. and Berger, R.L., 2002. Statistical inference (Vol. 2). Pacific\n#' Grove, CA: Duxbury.\n#' \n#' Rizzo, M.L., 2007. Statistical computing with R. Chapman and Hall/CRC.\n#' \n#' @useDynLib curand R_curand_rexp\n#' @export\nrexp = function(n, rate=1, seed=getseed(), type=\"double\")\n{\n type = match.arg(tolower(type), c(\"double\", \"float\"))\n type = ifelse(type == \"double\", TYPE_DOUBLE, TYPE_FLOAT)\n \n if (n < 0)\n stop(\"invalid arguments\")\n else if (n == 0)\n {\n if (type == TYPE_DOUBLE)\n return(numeric(0))\n else\n return(float(0))\n }\n \n n1 = floor(sqrt(n))\n n2 = n - n1*n1\n \n if (rate < 0 || is.badval(rate))\n {\n warning(\"NAs produced\")\n ret = setnan(n1, n2, type)\n }\n else\n ret = .Call(R_curand_rexp, as.integer(n1), as.integer(n2), as.double(rate), as.integer(seed), type)\n \n if (type == TYPE_DOUBLE)\n ret\n else\n float32(ret)\n}\n", "meta": {"hexsha": "27bec71b77352b673daeded8f78a296a74626031", "size": 1349, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rexp.r", "max_stars_repo_name": "wrathematics/curand", "max_stars_repo_head_hexsha": "16cc314d89673a138a6fd840b0b3f4ecaa96aa69", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-10-16T14:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-13T07:06:16.000Z", "max_issues_repo_path": "R/rexp.r", "max_issues_repo_name": "wrathematics/curand", "max_issues_repo_head_hexsha": "16cc314d89673a138a6fd840b0b3f4ecaa96aa69", "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/rexp.r", "max_forks_repo_name": "wrathematics/curand", "max_forks_repo_head_hexsha": "16cc314d89673a138a6fd840b0b3f4ecaa96aa69", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-14T03:17:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-14T03:17:23.000Z", "avg_line_length": 23.6666666667, "max_line_length": 103, "alphanum_fraction": 0.6197183099, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.696739330615994}} {"text": "#\r\n# SimpMCMCJpeg.r\r\n#\r\n# modified from SimpMCMC.r, but output is now jpeg files....\r\n# -------------------\r\n#\r\n# SimplMCMC.r\r\n# January 24,2011\r\n# This file will generate an MCMC sample of normal data \r\n# and produce a series of plots for this data\r\n#\r\n# NOTE: all plot files are saved to directory: \r\n# \"c:/mike workstation/bayescourse9/plots.\" \r\n# You may want to change this....\r\n#\r\n\r\n# prior\r\nmu0<-66; theta<-4; alp<-1; bet<-25\r\n\r\n# data\r\nx<-c(64, 73, 64, 63, 69, 71)\r\nxbar<-mean(x)\r\nn<-length(x)\r\n\r\n# starting values\r\nmuStart<-20;tauStart<-0.0025;\r\n\r\n# MCMC parameters\r\nnbig<-50000; \r\nset.seed(333); # The purpose of set.seed is to get the same random values\r\n\r\nif(T){ # set to true to rerun the MCMC\r\n# Initialize chain\r\nmu<-rep(nbig, 0)\r\ntau<-rep(nbig,0)\r\n\r\nmu[1]<-muStart; tau[1]<-tauStart\r\n\r\nmu0p<- (theta*mu0+n*xbar)/(theta+n) # does not change in loop\r\nalpp<-alp+(0.5)*(n+1) # does not change in loop\r\n\r\ntau0p<-rep(nbig,0)\r\nbetp<-rep(nbig,0)\r\n\r\nfor(i in 2:nbig){\r\n\t# sample mu\r\n\ttau0p[i]<-tau[i-1]*(n+theta)\r\n\tmu[i]<-rnorm(1,mean=mu0p,sd=1/sqrt(tau0p[i]))\r\n\t\r\n\t# sample tau\r\n\tbetp[i]<- bet+ 0.5*( sum( (x-mu[i])^2) + theta*(mu[i]-mu0p)^2)\r\n\ttau[i]<-rgamma(1,alpp,betp[i])\r\n}\r\n}\r\n# the following command will give the first 20 values:\r\n cbind(mu,tau)[1:20,]\r\n\r\n# The next group of plots will plot the values as the get sampled in time. \r\n#\r\n# Please note, that the below command write the plots to a JPEG file\r\n# to the directory: ``\\verb+c:/mike workstation/bayescourse9/plots+''. If you \r\n# don't have such a directory, then you need to create it or better yet, change\r\n# the directory name in the below commands.\r\n\r\n\r\n#\r\n# plots the values as they get sampled in time\r\n#\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Sd.jpg\")\r\n\r\niind1<-seq(1:60)\r\n\r\nplot(mu[iind1],tau[iind1],type=\"n\", xlab=\"mu\", ylab=\"tau\")\r\nlines(mu[1:60],tau[1:60],type=\"b\", cex=2)\r\ntitle(main=\"First 60 values\")\r\n\r\ndev.off()\r\n##################################\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7S2c.jpg\")\r\n\r\nplot(mu[2:60],tau[2:60],type=\"p\", xlab=\"mu\", ylab=\"tau\",\r\ncex=1.5, xlim=c(55,75), ylim=c(0,.2),\r\nmain=\"First 60 values, dropped first value\")\r\n\r\ndev.off()\r\n\r\n# The next set of commands compares the sampled joint distribution from the \r\n# MCMC method versus sampling the joint distribution using the know joint \r\n# distribution given in the second lecture. Note, the below code uses the \r\n# function \\verb+kde2d(...)+ which requires that the package \"MASS\" is loaded \r\n# in R. \r\n\r\nlibrary(MASS)\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7S2e.jpg\")\r\n\r\ncontour(kde2d(mu[2:nbig],tau[2:nbig]),\r\nxlab=\"mu\", ylab=\"tau\",\r\ncex=1.5, xlim=c(55,75), ylim=c(0,.2),nlevels=19,\r\nmain=\"Joint Distribution: MCMC\")\r\n\r\ndev.off()\r\n\r\n#####\r\nxa1<-4;xb1<-71.797\r\nxmu0<-66.80; xthep<-10\r\nxn<-50000\r\nxgam<-rgamma(xn,xa1,xb1)\r\nxmu<-rnorm(xn,mean=xmu0, sd=1/sqrt(xthep*xgam))\r\n#####\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7S2f.jpg\")\r\n\r\ncontour(kde2d(xmu,xgam),\r\nxlab=\"mu\", ylab=\"tau\",\r\ncex=1.5, xlim=c(55,75), ylim=c(0,.2),nlevels=19,\r\nmain=\"Joint Distribution: IID sample\")\r\n\r\ndev.off()\r\n\r\n\r\n# The next group of plots are for the trace plots. These plots are a simple \r\n# time plot of one of the parameters which is sampled with the MCMC algorithm. \r\n# That is, for a parameter $\\theta$, let the m-th step sampled value be \r\n# $\\theta^{(m)}$. Then, the plot is simply $m$ versus $\\theta^{(m)}$. \r\n\r\n\r\n\r\n##########################################\r\n#\r\n# trace plots\r\n#\r\n##########################################\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Ta.jpg\")\r\n\r\niind2<-seq(1,200)\r\nplot(iind2,mu[iind2],type=\"l\", xlab=\"Iteration number\", ylab=\"mu\",\r\ncex=1.5, \r\nmain=\"Trace plot for mu\")\r\n\r\ndev.off()\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Tb.jpg\")\r\n\r\niind2<-seq(1,200)\r\niind2a<-seq(6,200)\r\n\r\nplot(iind2a,mu[iind2a],type=\"l\", xlab=\"Iteration number\", ylab=\"mu\",\r\ncex=1.5, main=\"Trace plot for mu, dropping first 5 obs\")\r\n\r\ndev.off()\r\n\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Td.jpg\")\r\n\r\niind2<-seq(1,200)\r\niind2a<-seq(6,200)\r\n\r\nplot(iind2a,tau[iind2a],type=\"l\", xlab=\"Iteration number\", ylab=\"tau\",\r\ncex=1.5, \r\nmain=\"Trace plot for tau, dropping first 5 obs\")\r\n\r\ndev.off()\r\n\r\n# The following sequence of plots show the estimated density of $\\mu$ \r\n# calculated from a sample from a MCMC chain, from a sample of the \r\n# independent distribution, and a plot of the true posterior marginal \r\n# distribution.\r\n\r\n\r\n\r\n##########################################\r\n#\r\n# density plots\r\n#\r\n##########################################\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Dma.jpg\")\r\n\r\nplot(density(mu[-(1:5)]),type=\"l\", xlab=\"mu\", ylab=\" \",\r\ncex=1.5, xlim=c(55,75), main=\"Estimate mu by MCMC\")\r\n\r\ndev.off()\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Dmb.jpg\")\r\n\r\nplot(density(mu[-(1:5)]),type=\"l\", xlab=\"mu\", ylab=\" \",\r\ncex=1.5, xlim=c(55,75), main=\"Estimate mu by Independent Sampling\")\r\nlines(density(xmu),type=\"l\")\r\n\r\ndev.off()\r\n\r\njpeg(file=\"c:/mike workstation/bayescourse9/plots/lec2Ex7Dmc.jpg\")\r\n\r\nplot((dd<-density(mu[-(1:5)])),type=\"l\", xlab=\"mu\", ylab=\" \",\r\ncex=1.5, xlim=c(55,75),\r\nmain=\"True density of mu\", col=1)\r\n\r\nlines(density(xmu),type=\"l\", col=2)\r\nxx<-dd$x\r\nc2<-1/sqrt( xb1/xa1/xthep)\r\ntt<-(xx-xmu0)*c2\r\nddt<-dt(tt,2*xa1)*c2\r\nlines(xx,ddt,type=\"l\",col=3)\r\n\r\ndev.off()\r\n\r\n\r\n", "meta": {"hexsha": "bbd381e9651fdd92f7a141b30702b5ec80c2134d", "size": 5470, "ext": "r", "lang": "R", "max_stars_repo_path": "hw2bayes2019/Comp Code Files/Comp Code Files/SimpMCMCJpeg.r", "max_stars_repo_name": "FaizanKhalidMohsin/UofT_BayesianInference_Course", "max_stars_repo_head_hexsha": "22f15ae068b4e6352ab9680bbe4f78a9edfb2ecd", "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": "hw2bayes2019/Comp Code Files/Comp Code Files/SimpMCMCJpeg.r", "max_issues_repo_name": "FaizanKhalidMohsin/UofT_BayesianInference_Course", "max_issues_repo_head_hexsha": "22f15ae068b4e6352ab9680bbe4f78a9edfb2ecd", "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": "hw2bayes2019/Comp Code Files/Comp Code Files/SimpMCMCJpeg.r", "max_forks_repo_name": "FaizanKhalidMohsin/UofT_BayesianInference_Course", "max_forks_repo_head_hexsha": "22f15ae068b4e6352ab9680bbe4f78a9edfb2ecd", "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": 25.9241706161, "max_line_length": 81, "alphanum_fraction": 0.6254113346, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6967293895911688}} {"text": "=begin\n # sample-gaussian-elimination01.rb\n\n require \"algebra\"\n M = MatrixAlgebra(Rational, 5, 4)\n a = M.matrix{|i, j| i + j}\n a.display #=>\n #[0, 1, 2, 3]\n #[1, 2, 3, 4]\n #[2, 3, 4, 5]\n #[3, 4, 5, 6]\n #[4, 5, 6, 7]\n a.kernel_basis.each do |v|\n puts \"a * #{v} = #{a * v}\"\n #=> a * [1, -2, 1, 0] = [0, 0, 0, 0, 0]\n #=> a * [2, -3, 0, 1] = [0, 0, 0, 0, 0]\n end\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "85646e40f8623b4bcdbabe7d3e9ea3eee2f0ba95", "size": 412, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-gaussian-elimination01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-gaussian-elimination01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-gaussian-elimination01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.6, "max_line_length": 43, "alphanum_fraction": 0.4247572816, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6965050881594209}} {"text": "\"%gcd%\" <- function(u, v) {ifelse(u %% v != 0, v %gcd% (u%%v), v)}\n\n\"%lcm%\" <- function(u, v) { abs(u*v)/(u %gcd% v)}\n\nprint (50 %lcm% 75)\n", "meta": {"hexsha": "f3cc2bdc5dc7c28d2b7054b6eeb27e59f30d17ef", "size": 139, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Least-common-multiple/R/least-common-multiple.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "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/Least-common-multiple/R/least-common-multiple.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/Least-common-multiple/R/least-common-multiple.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": 23.1666666667, "max_line_length": 66, "alphanum_fraction": 0.4604316547, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.696387483581475}} {"text": "=begin\n[(())] \n= AlgebraicExtensionField\n((*(Algebraic Extension Field)*))\n\nA class represents the algebraic extension field.\n\n== File Name:\n* ((|algebraic-Extension-feild.rb|))\n\n== SuperClass:\n\n* ((|ResidueClassRing|))\n\n== Included Module\n\n(none)\n\n== Associated Methods:\n\n--- Algebra.AlgebraicExtensionField(field, obj){|x| ... }\n Same as ((<::create>)).\n\n== Class Method\n\n--- ::create(k, obj){|x| ... }\n Returns the extension field ((|k[x]/(p(x))|))\n of the field ((|k|)) by \n the polynomial ((|p(x)|)) of the variable ((|x|)), \n where ((|obj|)) represents the ((|x|)).\n\n The class methods ((<::var>)), ((<::def_polys>)) and ((<::env_ring>))\n are defined for the return value.\n \n Example: Create the field ((|F|)) extended by (({x**2 + x + 1 == 0}))\n from ((|Rational|)).\n require \"rational\"\n require \"polynomial\"\n require \"residue-class-ring\"\n F = Algebra.AlgebraicExtensionField(Rational, \"x\") {|x| x**2 + x + 1}\n x = F.var\n p( (x-1)** 3 / (x**2 - 1) ) #=> -3x - 3\n\n--- ::to_ary\n Returns (({[self, var]})).\n\n Example: Define AlgebraicExtensionField and variables simulteniously\n require \"rational\"\n require \"algebraic-extension-field\"\n F, a = Algebra.AlgebraicExtensionField(Rational, \"a\") {|a| a**2 + a + 1}\n\n--- ::var\n Returns the residue class of ((|x|)).\n This method is defined for the residue class ring, ((|k[x]/(p(x))|))\n which is the return value of ((<::create>)).\n\n--- ::modulus\n Returns the element ((|p(x)|)) of ((|k[x]|)) .\n This method is defined for the residue class ring, ((|k[x]/(p(x))|))\n which is the return value of ((<::create>)).\n\n--- ::def_polys\n Returns the array of ((<::modulus>))'s of size ((|n|)).\n Where ((|self|)) is defined recursively as the \n ((|AlgebraicExtensionField|)) \n of height ((|n|)) and base field ((|k0|)). \n This method is defined for the residue class ring ((|k[x]/(p(x))|))\n which is the return value of ((<::create>)).\n\n\n\n Example: Make the extension field of cubic roots of 2, 3, 5 over Rational.\n require \"algebra\"\n # K0 == Rational\n K1 = AlgebraicExtensionField(Rational, \"x1\") { |x|\n x ** 3 - 2\n }\n K2 = AlgebraicExtensionField(K1, \"x2\") { |y|\n y ** 3 - 3\n }\n K3 = AlgebraicExtensionField(K2, \"x3\") { |z|\n z ** 3 - 5\n }\n\n p K3.def_polys #=> [x1^3 - 2, x2^3 - 3, x3^3 - 5]\n\n x1, x2, x3 = K1.var, K2.var, K3.var\n f = x1**2 + 2*x2**2 + 3*x3**2\n f0 = f.abs_lift\n\n p f0.type #=> (Polynomial/(Polynomial/(Polynomial/Rational)))\n p f0.type == K3.env_ring #=> true\n\n p f #=> 3x3^2 + 2x2^2 + x1^2\n p f0.evaluate(x3.abs_lift, x2.abs_lift, x1.abs_lift)\n #=> x3^2 + 2x2^2 + 3x3^2\n\n\n--- ::env_ring\n Returns the multi-variate polynomial ring ((|k0[x1, x2,.., xn]|)).\n Where ((|self|)) is defined recursively as the \n ((|AlgebraicExtensionField|)) \n of height ((|n|)) and base field ((|k0|)). \n This method is defined for the residue class ring ((|k[x]/(p(x))|))\n which is the return value of ((<::create>)).\n\n--- ::ground\n Return the polnomial ring ((|k[x]|)) which is the ground ring of\n the residue class ring.\n\n== Methods\n--- abs_lift\n Returns the lift of self in ((<::env_ring>)).\n ( = ((|k0[x1, x2,.., xn] |)) ).\n\n--- [](n)\n Returns the coeffcient of degree (()). Same as (({lift[n]})).\n\n Example: Fibonacci Series\n require \"algebra\"\n t = AlgebraicExtensionField(Integral, \"t\"){|x| x**2-x-1}.var\n (0..10).each do |n|\n p( (t**n)[1] ) #=> 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55\n end\n\n=end\n", "meta": {"hexsha": "1fbd049bb85f8e9e84afe7fdf6ef8fa383227fc1", "size": 3656, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/algebraic-extension-field.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/algebraic-extension-field.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/algebraic-extension-field.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.7874015748, "max_line_length": 78, "alphanum_fraction": 0.5579868709, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6963803993009271}} {"text": "N <- 10000\n\nts1 <- 1:N\nts2 <- 1:N\n\nexperiment <- function () {\n\tt <- 0\n\trepeat {\n\t\toutcome <- sample(2, 1, prob=c(1/4, 3/4))\n\t\tif (outcome == 1) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tt <- t + 1\n\t\t}\n\t}\n\tt\n}\n\n\nfor (i in 1:N) {\n\tts1[i] <- experiment()\n\tts2[i] <- ts1[i] + experiment()\n}\n\n# exercise (i)\nprint(summary(ts1))\nbarplot(table(ts1)/N)\n# exercise (ii)\nbarplot(table(ts2)/N)", "meta": {"hexsha": "84516085d068617c8abf2c8d7cceaaadb74fea63", "size": 366, "ext": "r", "lang": "R", "max_stars_repo_path": "probability_theory_practicals/ex3/solution.r", "max_stars_repo_name": "prokls/math-lecture-notes", "max_stars_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-11-25T01:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T14:47:36.000Z", "max_issues_repo_path": "probability_theory_practicals/ex3/solution.r", "max_issues_repo_name": "prokls/math-lecture-notes", "max_issues_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:56:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-02T09:32:40.000Z", "max_forks_repo_path": "probability_theory_practicals/ex3/solution.r", "max_forks_repo_name": "prokls/math-lecture-notes", "max_forks_repo_head_hexsha": "d1a94e128d13ce4399a9cc55323b2f8e0d9494fd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-24T14:42:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-25T11:00:11.000Z", "avg_line_length": 12.6206896552, "max_line_length": 43, "alphanum_fraction": 0.5327868852, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6962289923717513}} {"text": "# Calculates the Mandelbrot set (https://en.wikipedia.org/wiki/Mandelbrot_set)\n# through the first 20 iterations of the equation z = z^2 + c plotted for\n# different complex constants c.\n\ninstall.packages(\"caTools\")\nlibrary(caTools) # for write.gif\njet.colors <- colorRampPalette(c(\"green\", \"blue\", \"red\", \"cyan\", \"#7FFF7F\",\n \"yellow\", \"#FF7F00\", \"red\", \"#7F0000\"))\nm <- 1000 # define size\nC <- complex(real=rep(seq(-1.8,0.6, length.out=m), each=m),\n imag=rep(seq(-1.2,1.2, length.out=m), m))\nC <- matrix(C,m,m) # reshape as square matrix of complex numbers\nZ <- 0\nX <- array(0, c(m,m,20)) # initialize output 3D array\nfor (k in 1:20) {\n Z <- Z^2+C # the central difference equation\n X[,,k] <- exp(-abs(Z)) # capture results\n}\nwrite.gif(X, \"Mandelbrot.gif\", col=jet.colors, delay=900)\n", "meta": {"hexsha": "d473e238d9cef37c9172895ef9ba1701836a8063", "size": 836, "ext": "r", "lang": "R", "max_stars_repo_path": "mandelbrot.r", "max_stars_repo_name": "theDrake/r-experiments", "max_stars_repo_head_hexsha": "fb3f7b77f348cbda2ee0eeaf2cbbd2c595ae4b8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-09-03T04:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T04:37:34.000Z", "max_issues_repo_path": "mandelbrot.r", "max_issues_repo_name": "theDrake/r-experiments", "max_issues_repo_head_hexsha": "fb3f7b77f348cbda2ee0eeaf2cbbd2c595ae4b8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T19:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T19:48:43.000Z", "max_forks_repo_path": "mandelbrot.r", "max_forks_repo_name": "theDrake/r-experiments", "max_forks_repo_head_hexsha": "fb3f7b77f348cbda2ee0eeaf2cbbd2c595ae4b8b", "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.8, "max_line_length": 78, "alphanum_fraction": 0.6291866029, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938533, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.696019157358353}} {"text": "fitDistToX <- function (x, dist) {\n tx <- dist$x; ty <- dist$y\n y <- numeric(length(x))\n for (i in seq(x)) {\n j <- bsearchtools::lb(tx, x[i])\n if (j <= 1) {\n y[1:i] <- ty[1]\n next\n }\n if (j > length(tx)) {\n y[i:length(x)] <- ty[length(ty)]\n break\n }\n y[i] <- (ty[j] - ty[j-1]) / (tx[j] - tx[j-1]) * (x[i] - tx[j]) + ty[j]\n }\n return(list(x=x,y=y))\n}\n\nsampleFromPopDist <- function (n, popDist, seed=1234) {\n set.seed(seed)\n return (sample(popDist$x, n, prob = (popDist$y) / sum(popDist$y), replace = TRUE))\n}\n\nKLdistance <- function(sampleDist, popDist) {\n x <- popDist$x\n modifSampleDist <- fitDistToX(x, sampleDist)\n lp <- -log(modifSampleDist$y)\n lq <- -log(popDist$y)\n dx <- diff(modifSampleDist$x)\n dx <- c(dx, dx[length(dx)])\n kl <- (modifSampleDist$y * lp / lq) * dx\n kl[is.na(kl)] <- 0\n return (sum(kl))\n}\n\nL2distance <- function (sampleDist, popDist) {\n x <- popDist$x\n modifSampleDist <- fitDistToX(x, sampleDist)\n dx <- diff(modifSampleDist$x)\n dx <- c(dx, dx[length(dx)])\n l2 <- sum((modifSampleDist$y - popDist$y)^2 * dx)\n return (l2)\n}\n\naddRandomNoise <- function (vec, noise) {\n newVec <- numeric(length(vec))\n for (i in seq(vec)) {\n newVec[i] <- vec[i] + rnorm (1,0,noise)\n }\n return (newVec)\n}\n\n\n\n\n", "meta": {"hexsha": "c550940bea4214d1e9e3aec128027d113dc10c85", "size": 1282, "ext": "r", "lang": "R", "max_stars_repo_path": "R/density/tools.r", "max_stars_repo_name": "Tan-Furukawa/badzupa2", "max_stars_repo_head_hexsha": "a5641c9987ea9819b336d4f903b49e4c19ce6c47", "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/density/tools.r", "max_issues_repo_name": "Tan-Furukawa/badzupa2", "max_issues_repo_head_hexsha": "a5641c9987ea9819b336d4f903b49e4c19ce6c47", "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/density/tools.r", "max_forks_repo_name": "Tan-Furukawa/badzupa2", "max_forks_repo_head_hexsha": "a5641c9987ea9819b336d4f903b49e4c19ce6c47", "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.8928571429, "max_line_length": 84, "alphanum_fraction": 0.5663026521, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6959200149487967}} {"text": "\r\n\r\n# Goal: Given two vectors of data,\r\n# superpose their CDFs\r\n# and show the results of the two-sample Kolmogorov-Smirnoff test\r\n\r\n# The function consumes two vectors x1 and x2.\r\n# You have to provide a pair of labels as `legendstrings'.\r\n# If you supply an xlab, it's used\r\n# If you specify log - e.g. log=\"x\" - this is passed on to plot.\r\n# The remaining args that you specify are sent on into ks.test()\r\ntwo.cdfs.plot <- function(x1, x2, legendstrings, xlab=\"\", log=\"\", ...) {\r\n stopifnot(length(x1)>0,\r\n length(x2)>0,\r\n length(legendstrings)==2)\r\n hilo <- range(c(x1,x2))\r\n\r\n par(mai=c(.8,.8,.2,.2))\r\n plot(ecdf(x1), xlim=hilo, verticals=TRUE, cex=0,\r\n xlab=xlab, log=log, ylab=\"Cum. distribution\", main=\"\")\r\n grid()\r\n plot(ecdf(x2), add=TRUE, verticals=TRUE, cex=0, lwd=3)\r\n legend(x=\"bottomright\", lwd=c(1,3), lty=1, bty=\"n\",\r\n legend=legendstrings)\r\n\r\n k <- ks.test(x1,x2, ...)\r\n text(x=hilo[1], y=c(.9,.85), pos=4, cex=.8,\r\n labels=c(\r\n paste(\"KS test statistic: \", sprintf(\"%.3g\", k$statistic)),\r\n paste(\"Prob value: \", sprintf(\"%.3g\", k$p.value))\r\n )\r\n )\r\n k\r\n}\r\n\r\nx1 <- rnorm(100, mean=7, sd=1)\r\nx2 <- rnorm(100, mean=9, sd=1)\r\n\r\n# Check error detection --\r\ntwo.cdfs.plot(x1,x2)\r\n\r\n# Typical use --\r\ntwo.cdfs.plot(x1, x2, c(\"X1\",\"X2\"), xlab=\"Height (metres)\", log=\"x\")\r\n\r\n# Send args into ks.test() --\r\ntwo.cdfs.plot(x1, x2, c(\"X1\",\"X2\"), alternative=\"less\")\r\n\r\n", "meta": {"hexsha": "d676fb38040dce51516cc2d2aef59d620bfd88ef", "size": 1459, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p10.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p10.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p10.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.3958333333, "max_line_length": 73, "alphanum_fraction": 0.5853324195, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.6957593891915217}} {"text": "# Example : 1 Chapter : 2.3 page no : 57\n#Matrix multiplication as dotproduct of row and column\nA<-matrix(c(3,4,5,6),nrow=2,ncol=2,byrow=T)\nx<-c(2,1)\nB<-A%*%x\nB\nAx<-c()\nfor(i in 1:2){\n Ax<-c(Ax,sum(A[i,]*x))\n}\nAx<-matrix(Ax,ncol=1)\nAx", "meta": {"hexsha": "7dcd7475f81f382c90d56e4562cfdfcda531e6a7", "size": 244, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.1/Ex2.3_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.1/Ex2.3_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.1/Ex2.3_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 20.3333333333, "max_line_length": 54, "alphanum_fraction": 0.5983606557, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6955981742358472}} {"text": "next.perm <- function(p) {\n n <- length(p)\n i <- n - 1\n r = T\n for (i in seq(n - 1, 1)) {\n if (p[i] < p[i + 1]) {\n r = F\n break\n }\n }\n\n j <- i + 1\n k <- n\n while (j < k) {\n x <- p[j]\n p[j] <- p[k]\n p[k] <- x\n j <- j + 1\n k <- k - 1\n }\n\n if(r) return(NULL)\n\n j <- n\n while (p[j] > p[i]) j <- j - 1\n j <- j + 1\n\n x <- p[i]\n p[i] <- p[j]\n p[j] <- x\n return(p)\n}\n\nprint.perms <- function(n) {\n p <- 1:n\n while (!is.null(p)) {\n cat(p, \"\\n\")\n p <- next.perm(p)\n }\n}\n\nprint.perms(3)\n# 1 2 3\n# 1 3 2\n# 2 1 3\n# 2 3 1\n# 3 1 2\n# 3 2 1\n", "meta": {"hexsha": "768b2992542a5971165a7cbc3558460ff5cc1aa1", "size": 581, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Permutations/R/permutations-1.r", "max_stars_repo_name": "mbirabhadra/RosettaCodeData", "max_stars_repo_head_hexsha": "ba8067c3b7e68156d666c9a802c07cdacecc14ea", "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/Permutations/R/permutations-1.r", "max_issues_repo_name": "p0l4r/RosettaCodeData", "max_issues_repo_head_hexsha": "ba8067c3b7e68156d666c9a802c07cdacecc14ea", "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/Permutations/R/permutations-1.r", "max_forks_repo_name": "p0l4r/RosettaCodeData", "max_forks_repo_head_hexsha": "ba8067c3b7e68156d666c9a802c07cdacecc14ea", "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": 11.8571428571, "max_line_length": 32, "alphanum_fraction": 0.3597246127, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6955760686620246}} {"text": "\n# #This will be a different path if in the lab or at home\n# dird=\"E:\\\\OneDrive\\\\MATH4753\\\\DATAxls\\\\\" # 2017\n# \n# #my function to read data \n# myread=function(csv){\n# fl=paste(dird,csv,sep=\"\")\n# read.table(fl,header=TRUE,sep=\",\")\n# }\n# #EASY WAY TO READ IN FILES\n\n#spruce.df=myread(\"SPRUCE.csv\")#MS pg478\n\nspruce.df = read.csv(\"SPRUCE.csv\")\n\n#with(spruce.df, dput(list(D=BHDiameter,H=Height), \n #file=\"spruce.dat\"))\n# Or use \n#spruce.df=read.table(file.choose(),header=TRUE,sep=\",\")\n\n#get wd\ngetwd()\n\n#Top six lines\ntail(spruce.df)\n\n#Plot the points\nwindows()\n\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\n\nlibrary(ggplot2)\nwindows()\ng = ggplot(spruce.df,mapping = aes(x = BHDiameter, y = Height)) + \n geom_point()\nprint(g)\n\ng = g+ geom_smooth(formula = y~ log(x), method = \"lm\", col = \"steelblue\")\ng = g + geom_smooth(formula = y ~ x, method = \"lm\", col = \"Black\")\ng = g + geom_smooth(formula = y~ x+ I(x^2), method =\"lm\", col = \"Red\")\nprint(g)\n\ng = g + geom_smooth(formula = y~ poly(x,3), method =\"lm\", col = \"green3\")\ng\n\n\n\n#load s20x library and make lowess smoother\nlibrary(s20x)\n\ntrendscatter(Height~BHDiameter,f=0.5,data=spruce.df)\n# Now make the linear model\nspruce.lm=lm(Height~BHDiameter,data=spruce.df)\nsummary(spruce.lm)\n#residuals created from the linear model object\nheight.res=residuals(spruce.lm)\n\n#fitted values made from the linear model object\nheight.fit=fitted(spruce.lm)\n\nwindows()\n#Make the plot using the plot function \nplot(height.fit,height.res)\n\n# Put a lowess smoother through res vs fitted\ntrendscatter( height.fit,height.res)\n\n# Quick way to make a residual plot\nplot(spruce.lm, which =1)\n\n# Two plots testing normality\nwindows()\nnormcheck(spruce.lm,shapiro.wilk = TRUE)\n\n\n## Quadratic object using the linear model\nquad.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)\nsummary(quad.lm)\nadd1(spruce.lm,.~.+I(BHDiameter^2))\nanova(spruce.lm)\nanova(quad.lm)\nanova(spruce.lm,quad.lm)\ncubic.lm=lm(Height~BHDiameter + I(BHDiameter^2)+I(BHDiameter^3),data=spruce.df)\nanova(cubic.lm)\nadd1(quad.lm,.~.+I(BHDiameter^3))\n#add to the scatter plot\nwindows()\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\ncoef(quad.lm)\nnames(quad.lm)\nquad.lm$coef[2]\n\nmyplot=function(x){\n 0.86089580 +1.46959217*x -0.02745726*x^2\n }\n \n #Or more general method\nmyplot=function(x){\n quad.lm$coef[1] +quad.lm$coef[2]*x + quad.lm$coef[3]*x^2\n } \n \ncurve(myplot, lwd=2, col=\"steelblue\",add=TRUE)\n \n \nplot(quad.lm, which=1)\n\nplot(spruce.lm,which=1)\nnormcheck(quad.lm,shapiro.wilk = TRUE)\n\n\nsummary(quad.lm)\n\npredict(quad.lm, data.frame(BHDiameter=c(3,6,8)))\n\n\nciReg(quad.lm)\n\n\n\npredict(quad.lm, data.frame(BHDiameter=c(15,18,20)))\n\nanova(spruce.lm,quad.lm)\n\ndata = 15:24\npredict20x(quad.lm,data.frame(BHDiameter = data, `I(BhDiameter)^2`=data^2))\n\nanova(quad.lm)\nanova(spruce.lm)\n\nheight.qfit=fitted(quad.lm)\n\nRSS=with(spruce.df, sum((Height-height.qfit)^2))\nRSS\nMSS = with(spruce.df, sum((height.qfit-mean(Height))^2))\nMSS\n\nTSS = with(spruce.df, sum((Height-mean(Height))^2))\nTSS\n\n\nMSS/TSS\n\n\ncooks20x(quad.lm)\n\n\n#Now remove the 24th datum and reanalyze data\n\nquad2.lm=lm(Height~BHDiameter + I(BHDiameter^2) , data=spruce.df[-24,])\nsummary(quad2.lm)\nsummary(quad.lm)\n\n\n###############################################################################\n\n#some other code you might need\n#The following code plots residuals\nwindows()\n#Plot the data\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,max(Height)),xlim=c(0,max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\n#Make a quadratic model\nquad.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)\n\n# Find the coefficients\ncoef(quad.lm)\n\n#Make a function that produces heights for inputs \"x\"\nmyplot=function(x){\n 0.86089580 +1.46959217*x -0.02745726*x^2\n }\n\n# add the quadratic to the points \ncurve(myplot, lwd=2, col=\"steelblue\",add=TRUE)\n\n#Place segments (residuals) on the plot (except for the 3 largest cooks distances. 18, 21, 24)\nwith(spruce.df[-c(18,21,24),],segments(BHDiameter, Height, BHDiameter, height.qfit[-c(18,21,24)]) )\nwith(spruce.df[c(18,21,24),],segments(BHDiameter, Height, BHDiameter, height.qfit[c(18,21,24)], col=\"Red\", lwd=3) )\nwith( spruce.df, arrows(5,Height[24], BHDiameter[24], Height[24],lwd=2,col=\"Blue\"))\nwith(spruce.df,text(2,Height[24], paste(\"Highest Cook's\",\"\\n\", \"distance\",sep=\" \")))\nwith(spruce.df, text(BHDiameter,Height, 1:36,cex=0.5,pos=4))\n #########################################################################\n\n\nlayout(matrix(1:4,nr=2,nc=2,byrow=TRUE))\n\n#Lets look at where the plots will go\nlayout.show(4)\n\n#Plot the data\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n# add the line\nabline(spruce.lm)\n\n\n#make a new plot\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\nabline(spruce.lm)\n\n#make yhat the estimates of E[Height | BHDiameter]\nyhat=with(spruce.df,predict(spruce.lm,data.frame(BHDiameter)))\nyhat=fitted(spruce.lm)\n# Draw in segments making the residuals (regression errors)\nwith(spruce.df,{\nsegments(BHDiameter,Height,BHDiameter,yhat)\n})\n\nRSS=with(spruce.df,sum((Height-yhat)^2))\n\nRSS\n\n#make a new plot\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\n#make nieve model\nwith(spruce.df, abline(h=mean(Height)))\nabline(spruce.lm)\n\n#make the explained errors (explained by the model)\nwith(spruce.df, segments(BHDiameter,mean(Height),BHDiameter,yhat,col=\"Red\"))\nMSS=with(spruce.df,sum((yhat-mean(Height))^2))\nMSS\n\n# Total error\n#make a new plot\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\nylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)), \nmain=\"Spruce height prediction\",data=spruce.df)\n\nwith(spruce.df,abline(h=mean(Height)))\nwith(spruce.df, segments(BHDiameter,Height,BHDiameter,mean(Height),col=\"Green\"))\nTSS=with(spruce.df,sum((Height-mean(Height))^2))\nTSS\nRSS + MSS\nMSS/TSS\n\nsummary(spruce.lm)\n\n#obtain coefft values\ncoef(spruce.lm)\n\n#Calculate new y values given x\npredict(spruce.lm, data.frame(BHDiameter=c(15,18,20)))\n\nanova(spruce.lm)\n\nspruce2.lm=lm(Height~BHDiameter + I(BHDiameter^2),data=spruce.df)\nsummary(spruce2.lm)\n\n\n### More on the problem\nwindows()\nplot(Height~BHDiameter,bg=\"Blue\",pch=21,cex=1.2,\n ylim=c(0,1.1*max(Height)),xlim=c(0,1.1*max(BHDiameter)), \n main=\"Spruce height prediction\",data=spruce.df)\n\nyhatt=with(spruce.df,fitted(spruce2.lm))\nwith(spruce.df,plot(BHDiameter,yhatt,col=\"Red\")\n)\n\nsum(residuals(spruce2.lm)^2)\nplot(yhatt~BHDiameter,data=spruce.df,type=\"p\")\nsummary(spruce2.lm)\nanova(spruce2.lm)\nanova(spruce.lm,spruce2.lm)\nMSS\nRSS\n\n## piecewise linear model in R\n## Model y = b0 + b1x + b2(x-xk)*(x>xk)\n## You will need to change the code appropriately\nsp2.df=within(spruce.df, X<-(BHDiameter-20)*(BHDiameter>20)) # this makes a new variable and places it within the same df\nsp2.df\n\nlmp=lm(Height~BHDiameter + X,data=sp2.df)\ntmp=summary(lmp)\nnames(tmp)\nmyf = function(x,coef){\n coef[1]+coef[2]*(x) + coef[3]*(x-18)*(x-18>0)\n}\nplot(spruce.df,main=\"Piecewise regression\")\nmyf(0, coef=tmp$coefficients[,\"Estimate\"])\ncurve(myf(x,coef=tmp$coefficients[,\"Estimate\"] ),add=TRUE, lwd=2,col=\"Blue\")\nabline(v=18)\ntext(18,16,paste(\"R sq.=\",round(tmp$r.squared,4) ))\n", "meta": {"hexsha": "dc9ec3fe8a59cec829a860ed935bc1b3926025de", "size": 7606, "ext": "r", "lang": "R", "max_stars_repo_path": "Lab4/lab4.r", "max_stars_repo_name": "nbpreussOU/MATH4753PREU0001", "max_stars_repo_head_hexsha": "62590c6345fa165e53d4e32210fa04c7688ce4f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-30T15:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T02:07:58.000Z", "max_issues_repo_path": "Lab4/lab4.r", "max_issues_repo_name": "nbpreussOU/MATH4753PREU0001", "max_issues_repo_head_hexsha": "62590c6345fa165e53d4e32210fa04c7688ce4f9", "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": "Lab4/lab4.r", "max_forks_repo_name": "nbpreussOU/MATH4753PREU0001", "max_forks_repo_head_hexsha": "62590c6345fa165e53d4e32210fa04c7688ce4f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-03T04:29:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T18:06:36.000Z", "avg_line_length": 25.26910299, "max_line_length": 121, "alphanum_fraction": 0.6978701026, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.695524670123255}} {"text": "General_Euler <- function(num_of_paths, num_of_steps, mu, sigma, Texp=1, X0=0, convert_y_to_x=function(y) y, convert_x_to_y=function(x) x){\n # Simulate a 1-dimensional process using Monte Carlo with the standard Euler scheme.\n # This can be used to simulate the payoff of an option and calculate the implied volatility smile.\n #\n # Args:\n # num_of_paths (integer): The number of Monte Carlo paths\n # num_of_steps (integer): The number of steps in each Monte Carlo path\n # mu (function): The drift coefficient, a function of t (numeric) and X (array-like) returning a scalar\n # sigma (function): The diffusion coefficient, a function of t (numeric) and X (array-like) returning a scalar\n # Texp (Optional[numeric]): Time, in years, to simulate process. Defaults to 1.\n # X0 (Optional[numeric]): Initial value for the estimator process, X. Defaults to 0.\n # convert_y_to_x (Optional[function]): A function to convert Y_t to X_t. Defaults to X_t <- Y_t\n # convert_x_to_y (Optional[function]): A function to convert X_t to Y_t. Defaults to Y_t <- X_t\n # Raises:\n # Error: If mu is not a function.\n # Error: If sigma is not a function.\n # Returns:\n # (list of function(s)): Currently returns a list holding a function which runs a simulation\n if (!is.function(mu)) stop('mu must be a function')\n if (!is.function(sigma)) stop('sigma must be a function')\n\n dt <- Texp / num_of_steps\n Y0 <- convert_x_to_y(X0)\n\n run_monte_carlo <- function(g_maker, strikes, num_paths_to_plot=FALSE){\n # Runs the Monte Carlo simulation to calculate E[g(X_T)] for different strikes.\n #\n # Args:\n # g_maker (function): A function that returns a function f(x) <- g(x,K)\n # strikes (array-like): An array of strikes to pass in to g_maker\n # num_paths_to_plot (Optional[integer or logical]): How many paths should be plotted. Defaults to FALSE (no plot). If TRUE, defaults to 100.\n # Returns:\n # (array-like): A array of E[g(X_T)] for the range of strikes\n\n # Simulates the process X_t across time.\n # X is a 2-dimensional matrix with each row representing a path and each entry within it a single timestep.\n\n dW <- matrix(rnorm(num_of_paths*num_of_steps,sd=sqrt(dt)), nrow=num_of_paths, ncol=num_of_steps)\n\n # Generate the process Y using the Lamperti transform version of the process X\n \n # Initialize Y0. More efficient to just initialize all values as Y0\n Y <- matrix(Y0, nrow=num_of_paths, ncol=num_of_steps+1)\n\n # Step through time\n for (i in 1:num_of_steps){\n t <- (i-1)*dt\n Y[,i+1] <- Y[,i] + mu(t, Y[,i]) * dt + sigma(t, Y[,i]) * dW[,i]\n }\n\n # Plotting\n if (num_paths_to_plot != FALSE){ # Plots the first num_paths_to_plot paths.\n if (num_paths_to_plot == TRUE) num_paths_to_plot <- 100 # Default value\n num_paths_to_plot <- min(num_paths_to_plot, num_of_paths)\n #matplot plots columns so we transpose\n matplot(seq(0, Texp, Texp/num_of_steps), t(convert_y_to_x(Y[1:num_paths_to_plot,])), main=sprintf('Generated paths (first %i paths) - Euler scheme',num_paths_to_plot), xlab='t', ylab='X_t', type='l', lty=1)\n }\n \n # Final prices for each path (Undo the Lamperti transform)\n X_Ts <- convert_y_to_x(Y[,ncol(Y)])\n\n # Returns the mean of psi across all paths for each strike\n # return(vapply(strikes, function(K) mean(g_maker(K)(X_Ts)), FUN.VALUE=1))\n\n # Calculates prices for each path by row, each strike by column\n price_matrix <- vapply(strikes, function(K) g_maker(K)(X_Ts), FUN.VALUE=numeric(num_of_paths))\n print(data.frame(K=strikes, Variance=diag(var(price_matrix)))) # Diagonals of cov mtx are column variances\n return(colMeans(price_matrix))\n }\n \n # Return a list holding the function so we can call it object oriented style\n return(list(run_monte_carlo=run_monte_carlo))\n}\n", "meta": {"hexsha": "6358faa8d65a4bc1907efddd0ba5021a0b687168", "size": 4079, "ext": "r", "lang": "R", "max_stars_repo_path": "one_dimension/general_euler.r", "max_stars_repo_name": "scotthounsell/exact-simulation", "max_stars_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T18:46:57.000Z", "max_issues_repo_path": "one_dimension/general_euler.r", "max_issues_repo_name": "scotthounsell/exact-simulation", "max_issues_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "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": "one_dimension/general_euler.r", "max_forks_repo_name": "scotthounsell/exact-simulation", "max_forks_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "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": 55.1216216216, "max_line_length": 218, "alphanum_fraction": 0.6580044128, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6954666232768476}} {"text": "#' convert quantile to normal with mean 0.5 and variance such that ci% are found within the range (0,1)\n\nquantile_to_normal = function( x, mean =0.5, ci=0.999 ) {\n\n xmin = min( x[ which(x>0) ], na.rm=T )\n xmax = max( x[ which(x<1) ], na.rm=T )\n\n pr = {1 - ci} / 2 # one-tailed prob in normal approximation desired\n zsd = 2 * abs( qnorm( pr, mean=0, sd=1) ) # range in x required to have ci% of the population, two tailed\n rsd = 1 / zsd # sd required for population to fit in (0,1)\n\n zscore = qnorm( x, mean=mean, sd=rsd )\n\n xx = which( x>=1 | zscore > 1)\n if (length(xx) > 0 ) zscore[ xx ] = 1\n\n nn = which( x<=0 | zscore < 0)\n if (length(nn) > 0 ) zscore[ nn ] = 0\n\n return (zscore)\n}\n", "meta": {"hexsha": "be641eb458d865be2a828581c66452379b3e0ee3", "size": 699, "ext": "r", "lang": "R", "max_stars_repo_path": "R/quantile_to_normal.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/quantile_to_normal.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/quantile_to_normal.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 31.7727272727, "max_line_length": 108, "alphanum_fraction": 0.6037195994, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6954591558387738}} {"text": "#install.packages(\"GA\")\nlibrary(GA)\n\n# Funkcja przykładowa z dokumentacji\n# f <- function(x) (x^2+x)*cos(x) # Badana funkcja\n# lbound <- -10 # Dolne ograniczenie funkcji\n# rbound <- 10 # Górne ogranicznie funkcji\n\nf <- function(x) x*sin(10*pi*x)+1\nlbound <- -1\nrbound <- 2\n\nfA <- function(x) -f(x) # Funkcja odwrotna do badanej, ponieważ minimalizujemy funkcję\n\n# Genetic algorithm\nGA <- ga(\n type = \"real-valued\",\n fitness = fA,\n lower = c(th = lbound), upper = rbound,\n popSize = 50, maxiter = 1000, run = 100\n)\nsummary(GA)\nplot(GA)\n\ncurve(f, from = lbound, to = rbound, 1000) # rysowanie wykresy funkcji\n#points(GA@solution, GA@fitnessValue, col = 2, pch = 19) # ozaczanie punktu na wykresie / tutaj szukanego ekstremum w zakresie\npoints(GA@solution, f(GA@solution), col = 2, pch = 19) # Musimy uzyskać wartość z funkcji wyjściowej, gdyż badamy funkcje odwrotną\n", "meta": {"hexsha": "3f210dcae31d18eec5514325785703757c5fe62b", "size": 873, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ga/func/2d/ga_minimum_of_func.r", "max_stars_repo_name": "reyzeer/algorytmy-genetyczne", "max_stars_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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/ga/func/2d/ga_minimum_of_func.r", "max_issues_repo_name": "reyzeer/algorytmy-genetyczne", "max_issues_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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/ga/func/2d/ga_minimum_of_func.r", "max_forks_repo_name": "reyzeer/algorytmy-genetyczne", "max_forks_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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.1785714286, "max_line_length": 130, "alphanum_fraction": 0.6930126002, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6954591528711326}} {"text": "point_in_polygon <- function(polygon, p) {\n count <- 0\n for(side in polygon) {\n if ( ray_intersect_segment(p, side) ) {\n count <- count + 1\n }\n }\n if ( count %% 2 == 1 )\n \"INSIDE\"\n else\n \"OUTSIDE\"\n}\n\nray_intersect_segment <- function(p, side) {\n eps <- 0.0001\n a <- side$A\n b <- side$B\n if ( a$y > b$y ) {\n a <- side$B\n b <- side$A\n }\n if ( (p$y == a$y) || (p$y == b$y) ) {\n p$y <- p$y + eps\n }\n if ( (p$y < a$y) || (p$y > b$y) )\n return(FALSE)\n else if ( p$x > max(a$x, b$x) )\n return(FALSE)\n else {\n if ( p$x < min(a$x, b$x) )\n return(TRUE)\n else {\n if ( a$x != b$x )\n m_red <- (b$y - a$y) / (b$x - a$x)\n else\n m_red <- Inf\n if ( a$x != p$x )\n m_blue <- (p$y - a$y) / (p$x - a$x)\n else\n m_blue <- Inf\n return( m_blue >= m_red )\n }\n }\n}\n", "meta": {"hexsha": "054b92396694092b68f194e7227a0e89de642589", "size": 853, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Ray-casting-algorithm/R/ray-casting-algorithm-1.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/Ray-casting-algorithm/R/ray-casting-algorithm-1.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/Ray-casting-algorithm/R/ray-casting-algorithm-1.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": 18.9555555556, "max_line_length": 44, "alphanum_fraction": 0.427901524, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6951195897616613}} {"text": "StandardizeFeatures<-function(training.set,test.set=NULL,stddev=FALSE) {\n\t# Subtracts away mean feature vector in each column, given a dataset\n\t# (assumes no subject.id column); can also divide by std deviation\n\t#\n\t# Args:\n\t#\ttraining.set: dataset of training variables\n\t#\ttest.set: dataset of test variables\n\t#\t- if NULL, training set is standardized with training variables \n\t#\t- if given, test set is standardized with training variables \n\t#\tsd: switch for whether standard deviations are divided\n\t#\n\t# Returns:\n\t#\t a dataset standardized columns\n \n \t# Calculate mean and sd vector\n\tmean<-apply(training.set,2,mean,na.rm=TRUE)\n\tsd<-apply(training.set,2,sd,na.rm=TRUE)\n \n \tif (is.null(test.set)) {\n \t\ttraining.set<-sweep(training.set,2,mean,\"-\")\n \t\tif (!stddev) {\n \t\t\treturn(training.set)\n \t\t}\n \t\telse {\n \t\t\treturn(sweep(training.set,2,sd,\"/\"))\n \t\t}\n\t}\n\telse {\n\t\ttest.set<-sweep(test.set,2,mean,\"-\")\n\t\tif (!stddev) {\n\t\t\treturn(test.set)\n\t\t}\n\t\telse {\n\t\t\t return(sweep(test.set,2,sd,\"/\"))\n\t\t}\n\t}\n}\n\n#mean slope: -5.325687e-01\n#sd slope: 1.076365e+00 \n", "meta": {"hexsha": "7f952ce2a8df1f3a31b485ea7b7bd5473156358d", "size": 1062, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/R/standardize_features.r", "max_stars_repo_name": "ltfang/alsprize4life", "max_stars_repo_head_hexsha": "35592bffc1332778b723b330e86e6fbde8b60118", "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/standardize_features.r", "max_issues_repo_name": "ltfang/alsprize4life", "max_issues_repo_head_hexsha": "35592bffc1332778b723b330e86e6fbde8b60118", "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/standardize_features.r", "max_forks_repo_name": "ltfang/alsprize4life", "max_forks_repo_head_hexsha": "35592bffc1332778b723b330e86e6fbde8b60118", "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": 25.9024390244, "max_line_length": 72, "alphanum_fraction": 0.6723163842, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6950680612359086}} {"text": "###############\r\n## Section 4 ##\r\n###############\r\n\r\n#install.packages(\"ordinal\")\r\nlibrary(ordinal)\r\nlibrary(MASS)\r\n\r\nsetwd(\"C:\\\\dc_book\\\\Replication_Files_Element\")\r\n\r\nfinancedata <- read.csv(\"ANES_2016.csv\", header=T) \r\n\r\n\r\n###############\r\n## Table 4.1 ##\r\n###############\r\n\r\nfinance.ologit <- clm(as.ordered(prospective_persfin) ~ pred_favored_win+health+mortgage+gender+age, data = financedata, link=\"logit\")\r\nfinance.ologit.results <- cbind(finance.ologit$coefficients, sqrt(diag(vcov(finance.ologit))), confint.default(finance.ologit, level=0.95))\r\nN <- length(finance.ologit$fitted.values)\r\ncolnames(finance.ologit.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(finance.ologit.results, digits=3)))\r\nprint(N)\r\n\r\n## Note: Warning about formula can be ignored -- clm mistakenly throws an error for long formulas\r\n\r\n###############\r\n## Table 4.2 ##\r\n###############\r\n\r\nbeta <- finance.ologit$coefficients\r\ncovmat.beta <- vcov(finance.ologit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- apply(finance.ologit$model[,-1], 2, median)\r\n\r\nhypo.case.A <- baseline.x\r\n\r\nhypo.case.B <- baseline.x\r\nhypo.case.B[\"pred_favored_win\"] <- 0\r\n\r\n# multiply by -1 because the formula is tau - XB\r\nhypo.matrix.A <- matrix(hypo.case.A, 4, 5, byrow=TRUE) * -1\r\nhypo.matrix.tau.A <- cbind(diag(4), hypo.matrix.A)\r\n\r\nhypo.matrix.B <- matrix(hypo.case.B, 4, 5, byrow=TRUE) * -1\r\nhypo.matrix.tau.B <- cbind(diag(4), hypo.matrix.B)\r\n\r\n\r\nsimprob.A <- plogis(betadraw%*%t(hypo.matrix.tau.A))\r\nsimprob.A.1 <- simprob.A[,1]\r\nsimprob.A.2 <- simprob.A[,2] - simprob.A[,1]\r\nsimprob.A.3 <- simprob.A[,3] - simprob.A[,2]\r\nsimprob.A.4 <- simprob.A[,4] - simprob.A[,3]\r\nsimprob.A.5 <- 1 - simprob.A[,4]\r\n\r\nsimprob.B <- plogis(betadraw%*%t(hypo.matrix.tau.B))\r\nsimprob.B.1 <- simprob.B[,1]\r\nsimprob.B.2 <- simprob.B[,2] - simprob.B[,1]\r\nsimprob.B.3 <- simprob.B[,3] - simprob.B[,2]\r\nsimprob.B.4 <- simprob.B[,4] - simprob.B[,3]\r\nsimprob.B.5 <- 1 - simprob.B[,4]\r\n\r\n\r\nsimprob.diff.1 <- simprob.B.1 - simprob.A.1\r\nsimprob.diff.2 <- simprob.B.2 - simprob.A.2\r\nsimprob.diff.3 <- simprob.B.3 - simprob.A.3\r\nsimprob.diff.4 <- simprob.B.4 - simprob.A.4\r\nsimprob.diff.5 <- simprob.B.5 - simprob.A.5\r\n\r\n\r\nall.results <- cbind(\r\nsimprob.A.1, simprob.B.1, simprob.diff.1, \r\nsimprob.A.2, simprob.B.2, simprob.diff.2, \r\nsimprob.A.3, simprob.B.3, simprob.diff.3, \r\nsimprob.A.4, simprob.B.4, simprob.diff.4, \r\nsimprob.A.5, simprob.B.5, simprob.diff.5)\r\n\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nfirst.differences <- cbind(t(quantiles), sds)\r\ncolnames(first.differences) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(first.differences) <- c(\"Much Worse:Yes\", \"Much Worse:No\", \"Much Worse:Diff\", \"Somewhat Worse:Yes\", \"Somewhat Worse:No\", \"Somewhat Worse:Diff\", \"The Same:Yes\", \"The Same:No\", \"The Same:Diff\", \"Somewhat Better:Yes\", \"Somewhat Better:No\", \"Somewhat Better:Diff\", \"Much Better:Yes\", \"Much Better:No\", \"Much Better:Diff\")\r\nprint(round(first.differences, digits=3))\r\n\r\n################\r\n## Figure 4.1 ##\r\n################\r\n\r\nbeta <- finance.ologit$coefficients\r\ncovmat.beta <- vcov(finance.ologit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- apply(finance.ologit$model[,-1], 2, median)\r\nbaseline.matrix <- matrix(baseline.x, 4, 5, byrow=TRUE) * -1 # multiply by -1 because the formula is t - XB\r\nbaseline.matrix.tau <- cbind(diag(4), baseline.matrix)\r\ncolnames(baseline.matrix.tau) <- names(finance.ologit$coefficients)\r\n\r\n\r\ncolors <- c(\"#004D7380\", \"#1C82A380\", \"#17A1CC80\", \"#0ABA9E80\", \"#00DBA680\")\r\n\r\nage.range <- c(10:100)\r\n\r\n\r\nologit.probs1 <- matrix(NA, ndraws, length(age.range))\r\nologit.probs2 <- matrix(NA, ndraws, length(age.range))\r\nologit.probs3 <- matrix(NA, ndraws, length(age.range))\r\nologit.probs4 <- matrix(NA, ndraws, length(age.range))\r\nologit.probs5 <- matrix(NA, ndraws, length(age.range))\r\n\r\nologit.mean.probs <- matrix(NA, 5, length(age.range))\r\n\r\nfor (i in 1:length(age.range)) {\r\n\r\n\tbaseline.matrix.tau[,\"age\"] <- (age.range[i] * -1)\r\n\toprobs <- plogis(betadraw%*%t(baseline.matrix.tau))\r\n\tologit.probs1[,i] <- oprobs[,1]\r\n\tologit.probs2[,i] <- oprobs[,2] - oprobs[,1]\r\n\tologit.probs3[,i] <- oprobs[,3] - oprobs[,2]\r\n\tologit.probs4[,i] <- oprobs[,4] - oprobs[,3]\r\n\tologit.probs5[,i] <- 1 - oprobs[,4]\r\n\t\r\n\toprobs.mean <- plogis(beta%*%t(baseline.matrix.tau))\r\n\tologit.mean.probs[1,i] <- oprobs.mean[1]\r\n\tologit.mean.probs[2,i] <- oprobs.mean[2] - oprobs.mean[1]\r\n\tologit.mean.probs[3,i] <- oprobs.mean[3] - oprobs.mean[2]\r\n\tologit.mean.probs[4,i] <- oprobs.mean[4] - oprobs.mean[3]\r\n\tologit.mean.probs[5,i] <- 1 - oprobs.mean[4]\r\n}\r\n\r\npdf(\"fig41.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 5.6), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(ologit.mean.probs[1,]~age.range, xlim=c(18,90), ylim=c(0,0.6), type=\"n\", xlab=\"Age\", ylab=\"Probability\", xaxt=\"n\", las=1, lwd=2)\r\naxis(1, at=c(18, 30, 40, 50, 60, 70, 80, 90))\r\nfor (i in 1:length(age.range)){\r\n\tpoints(ologit.probs1[i,] ~ age.range, type=\"l\", col=colors[1], lwd=1)\r\n\tpoints(ologit.probs2[i,] ~ age.range, type=\"l\", col=colors[2], lwd=1)\r\n\tpoints(ologit.probs3[i,] ~ age.range, type=\"l\", col=colors[3], lwd=1)\r\n\tpoints(ologit.probs4[i,] ~ age.range, type=\"l\", col=colors[4], lwd=1)\r\n\tpoints(ologit.probs5[i,] ~ age.range, type=\"l\", col=colors[5], lwd=1)\r\n}\r\nlines(ologit.mean.probs[1,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(ologit.mean.probs[2,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(ologit.mean.probs[3,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(ologit.mean.probs[4,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(ologit.mean.probs[5,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nmtext(\"Much Worse\", side=4, at=ologit.mean.probs[1,82], cex=1.1, las=1, line=0.5)\r\nmtext(\"Somewhat\", side=4, at=ologit.mean.probs[2,82]-0.01, cex=1.1, las=1, line=0.5)\r\nmtext(\"Worse\", side=4, at=ologit.mean.probs[2,82]-0.03, cex=1.1, las=1, line=0.5)\r\nmtext(\"The Same\", side=4, at=ologit.mean.probs[3,82], cex=1.1, las=1, line=0.5)\r\nmtext(\"Somewhat\", side=4, at=ologit.mean.probs[4,82]+0.03, cex=1.1, las=1, line=0.5)\r\nmtext(\"Better\", side=4, at=ologit.mean.probs[4,82]+0.01, cex=1.1, las=1, line=0.5)\r\nmtext(\"Much Better\", side=4, at=ologit.mean.probs[5,82], cex=1.1, las=1, line=0.5)\r\ndev.off()\r\n\r\n\r\n###############\r\n## Table 4.3 ##\r\n###############\r\n\r\nbeta <- finance.ologit$coefficients\r\ncovmat.beta <- vcov(finance.ologit)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\n# AME\r\n\r\nologit.X <- cbind(0,0,0,0, finance.ologit$model[,-1]) * -1 # multiply by -1 because the formula is t - XB\r\nw <- financedata$sample_weight\r\n\r\n\r\nfor (i in 1:4) {\r\n\r\n\tologit.X.temp <- ologit.X\r\n\tologit.X.temp[,i] <- 1\r\n\tologit.p.temp <- plogis(betadraw %*% t(ologit.X.temp))\r\n\tassign(paste(\"ologit.p\", i, sep=\".\"), ologit.p.temp)\r\n\tassign(paste(\"ologit.d\", i, sep=\".\"), ologit.p.temp * (1 - ologit.p.temp))\r\n}\r\n\r\n# multiply each row by draws of health coefficients\r\name.1 <- diag(betadraw[,\"health\"]) %*% (0 - ologit.d.1) \r\name.2 <- diag(betadraw[,\"health\"]) %*% (ologit.d.1 - ologit.d.2) \r\name.3 <- diag(betadraw[,\"health\"]) %*% (ologit.d.2 - ologit.d.3) \r\name.4 <- diag(betadraw[,\"health\"]) %*% (ologit.d.3 - ologit.d.4) \r\name.5 <- diag(betadraw[,\"health\"]) %*% (ologit.d.4) \r\n\r\nologit.ame.1 <- apply(ame.1, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ame.2 <- apply(ame.2, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ame.3 <- apply(ame.3, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ame.4 <- apply(ame.4, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ame.5 <- apply(ame.5, 1, function(x){sum(x * w)/sum(w)})\r\n\r\nologit.ame <- cbind(ologit.ame.1, ologit.ame.2, ologit.ame.3, ologit.ame.4, ologit.ame.5)\r\n\r\nae.1 <- ame.1 * ((1/ologit.p.1) %*% diag(finance.ologit$model[,\"health\"]))\r\nae.2 <- ame.2 * ((1/(ologit.p.2 - ologit.p.1)) %*% diag(finance.ologit$model[,\"health\"]))\r\nae.3 <- ame.3 * ((1/(ologit.p.3 - ologit.p.2)) %*% diag(finance.ologit$model[,\"health\"]))\r\nae.4 <- ame.4 * ((1/(ologit.p.4 - ologit.p.3)) %*% diag(finance.ologit$model[,\"health\"]))\r\nae.5 <- ame.5 * ((1/(1 - ologit.p.4)) %*% diag(finance.ologit$model[,\"health\"]))\r\n\r\nologit.ae.1 <- apply(ae.1, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ae.2 <- apply(ae.2, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ae.3 <- apply(ae.3, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ae.4 <- apply(ae.4, 1, function(x){sum(x * w)/sum(w)})\r\nologit.ae.5 <- apply(ae.5, 1, function(x){sum(x * w)/sum(w)})\r\n\r\nologit.ae <- cbind(ologit.ae.1, ologit.ae.2, ologit.ae.3, ologit.ae.4, ologit.ae.5)\r\n\r\nquantiles.ame <- apply(ologit.ame, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsd.ame <- apply(ologit.ame, 2, sd)\r\nsummary.marginal.ame <- cbind(t(quantiles.ame), sd.ame)\r\n\r\nquantiles.ae <- apply(ologit.ae, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsd.ae <- apply(ologit.ae, 2, sd)\r\nsummary.elasticity.ame <- cbind(t(quantiles.ae), sd.ae)\r\n\r\n# MEM \r\n\r\nmean.x <- apply(finance.ologit$model[,-1], 2, mean)\r\nmean.x.matrix <- matrix(mean.x, 4, 5, byrow=TRUE) * -1\r\nmean.x.all <- cbind(diag(4), mean.x.matrix)\r\n\r\nmem.probs <- plogis(betadraw%*%t(mean.x.all))\r\n\r\nmem.1 <- -1 * (mem.probs[,1] * (1 - mem.probs[,1])) * betadraw[,\"health\"]\r\nmem.2 <- ((mem.probs[,1] * (1 - mem.probs[,1])) - (mem.probs[,2] * (1 - mem.probs[,2]))) * betadraw[,\"health\"]\r\nmem.3 <- ((mem.probs[,2] * (1 - mem.probs[,2])) - (mem.probs[,3] * (1 - mem.probs[,3]))) * betadraw[,\"health\"]\r\nmem.4 <- ((mem.probs[,3] * (1 - mem.probs[,3])) - (mem.probs[,4] * (1 - mem.probs[,4]))) * betadraw[,\"health\"]\r\nmem.5 <- (mem.probs[,4] * (1 - mem.probs[,4])) * betadraw[,\"health\"]\r\n\r\nologit.mem <- cbind(mem.1, mem.2, mem.3, mem.4, mem.5)\r\n\r\nme.1 <- mem.1 * (mean.x[\"health\"]/(mem.probs[,1]))\r\nme.2 <- mem.2 * (mean.x[\"health\"]/(mem.probs[,2] - mem.probs[,1]))\r\nme.3 <- mem.3 * (mean.x[\"health\"]/(mem.probs[,3] - mem.probs[,2]))\r\nme.4 <- mem.4 * (mean.x[\"health\"]/(mem.probs[,4] - mem.probs[,3]))\r\nme.5 <- mem.5 * (mean.x[\"health\"]/(1 - mem.probs[,4]))\r\n\r\nologit.me <- cbind(me.1, me.2, me.3, me.4, me.5)\r\n\r\nquantiles.mem <- apply(ologit.mem, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsd.mem <- apply(ologit.mem, 2, sd)\r\nsummary.marginal.mem <- cbind(t(quantiles.mem), sd.mem)\r\n\r\nquantiles.me <- apply(ologit.me, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsd.me <- apply(ologit.me, 2, sd)\r\nsummary.elasticity.mem <- cbind(t(quantiles.me), sd.me)\r\n\r\nmarginal.effects.elasticities <- rbind(summary.marginal.ame, summary.marginal.mem, summary.elasticity.ame, summary.elasticity.mem)\r\ncolnames(marginal.effects.elasticities) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\ncategory.names <- c(\"MW\", \"SW\", \"S\", \"SB\", \"MB\")\r\nrownames(marginal.effects.elasticities) <- c(paste(\"Marginal Effect (AME)\", category.names, sep=\".\"), paste(\"Marginal Effect (MEM)\", category.names, sep=\".\"), paste(\"Elasticity (AME)\", category.names, sep=\".\"), paste(\"Elasticity (MEM)\", category.names, sep=\".\"))\r\nprint(round(marginal.effects.elasticities, digits=3))\r\n\r\n\r\n## coefficient ratios\r\n\r\nmortgage.age.ratio <- betadraw[,\"mortgage\"]/betadraw[,\"age\"]\r\nratio.results <- quantile(mortgage.age.ratio, probs=c(0.5, 0.025, 0.975))\r\nprint(ratio.results)\r\n\r\n###############\r\n## Table 4.4 ##\r\n###############\r\n\r\nN <- length(finance.ologit$fitted.values)\r\n\r\nbeta <- finance.ologit$coefficients\r\ncovmat.beta <- vcov(finance.ologit)\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\nexp.betadraw <- exp(betadraw)\r\nquantiles <- apply(exp.betadraw, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(exp.betadraw, 2, sd)\r\nodds.ratios <- cbind(t(quantiles), sds)\r\ncolnames(odds.ratios) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(odds.ratios) <- names(beta) \r\nprint(round(odds.ratios, digits=3))\r\nprint(N)\r\n\r\n", "meta": {"hexsha": "43a34facbe4deba57815a7fb740512dbd8756b04", "size": 11769, "ext": "r", "lang": "R", "max_stars_repo_path": "R Code/Section4.r", "max_stars_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_stars_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "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 Code/Section4.r", "max_issues_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_issues_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "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 Code/Section4.r", "max_forks_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_forks_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-21T12:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T12:26:06.000Z", "avg_line_length": 41.1503496503, "max_line_length": 327, "alphanum_fraction": 0.6221429178, "num_tokens": 4536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6949921804507959}} {"text": " DGEEVX Example Program Results\n\n Eigenvalues\n\n Eigenvalue rcond error\n 1 7.9948E-01 0.9936 -\n 2 (-9.9412E-02, 4.0079E-01) 0.7027 -\n 3 (-9.9412E-02,-4.0079E-01) 0.7027 -\n 4 -1.0066E-01 0.5710 -\n\n Eigenvectors\n\n Eigenvector rcond error\n\n 1 6.5509E-01 0.8181 -\n 5.2363E-01\n -5.3622E-01\n 9.5607E-02\n\n 2 (-1.9330E-01, 2.5463E-01) 0.3996 -\n ( 2.5186E-01,-5.2240E-01)\n ( 9.7182E-02,-3.0838E-01)\n ( 6.7595E-01, 0.0000E+00)\n\n 3 (-1.9330E-01,-2.5463E-01) 0.3996 -\n ( 2.5186E-01, 5.2240E-01)\n ( 9.7182E-02, 3.0838E-01)\n ( 6.7595E-01,-0.0000E+00)\n\n 4 1.2533E-01 0.3125 -\n 3.3202E-01\n 5.9384E-01\n 7.2209E-01\n\n Errors below 10*machine precision are not displayed\n", "meta": {"hexsha": "89c30fb31c2c5f6fc82ddc0d84f48c36a29713f0", "size": 839, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dgeevx_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/dgeevx_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/dgeevx_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": 23.3055555556, "max_line_length": 52, "alphanum_fraction": 0.5041716329, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6949921764460306}} {"text": "#rows in the theatre and the scores given to the each movie corresponding to the rows\nfirst_row <- c(6,8,7,9, 9, 10)\nsecond_row <- c(6,8,7,5,9, 6)\nthird_row <- c(5,4,6,6,7, 8)\nfourth_row <- c(4,5,3,4,6,8)\n\n#Create a theatre matrix \nscores <- rbind(first_row, second_row, third_row, fourth_row)\nprint(scores)\n\n#Calculate the row wise scores \ntotal_sum <- rowSums(scores)\nprint(total_sum)\n\n#Merging the total sum to the existing theatre matrix\nscores <- cbind(scores, total_sum)\nprint(scores)\n\n#Adding Column and Row names\nrownames(scores) <- c(\"row1\",\"row2\",\"row3\",\"row4\")\ncolnames(scores) <- c(\"c1\",\"c2\",\"c3\",\"c4\",\"c5\",\"c6\",\"total\")\n\n#Final Theatre Matrix\nprint(scores)", "meta": {"hexsha": "7d7da9992fa3e601c80cb00174b11b9c02af8f6b", "size": 669, "ext": "r", "lang": "R", "max_stars_repo_path": "R/3.0/theatre.r", "max_stars_repo_name": "applecool/DataScience", "max_stars_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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/3.0/theatre.r", "max_issues_repo_name": "applecool/DataScience", "max_issues_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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/3.0/theatre.r", "max_forks_repo_name": "applecool/DataScience", "max_forks_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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.875, "max_line_length": 85, "alphanum_fraction": 0.7070254111, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6945396135123464}} {"text": "#' @title gini\n#' @description gini index of patchniness from a stratified survey (Myers and Cadigan 1995)\n#' @param \\code{x} : within strata mean per tow \n#' @param \\code{y} : strata areas in trawlable units\n#' @param \\code{plot} : makes the Lorenz plot if set to \\code{true}\n#' @return estimate of gini index as well as plot if plot=T\n#' @examples\n#' y=c(2454,\t656,\t2374,\t230,\t1221,\t619,\t172,\t2980,\t360,\t3245,\t1016,\t2569,\t424,\t390,\t454)\n#' x=c(0,\t0,\t0,\t0,\t0,\t0.25,\t1.81,\t2.52,\t2.6,\t3.68,\t7.58,\t10.07,\t13.33,\t13.33,\t24.99)\n#' gini(x,y,plot=T)\n#' #0.453 same as example in http://www.nefsc.noaa.gov/publications/crd/pdfs/crd9605f.pdf\n#' @author Adam Cook, \\email{Adam.Cook@@dfo-mpo.gc.ca}\n#' @export\n\n\ngini <- function(x,y,plot=F){\n\t\t\tXi <- data.frame(yh=x,Ah=y)\n\t\t Xi$P = Xi$yh * Xi$Ah\n\t\t Xi = Xi[order(Xi$P),]\n\t\t Xi$cP = cumsum(Xi$P) / sum(Xi$P)\n\t\t Xi$cA = cumsum(Xi$Ah) / sum(Xi$Ah)\n\t\t if(plot) {\n\t\t \twith(Xi,plot(cA,cP,type='l'))\n\t\t \tabline(a=0,b=1,col='blue')\n\t\t \t}\n\t\t gI=NA\n\n\t\t if(nrow(Xi)>1) gI = 1-(2*sum(rowMeans(embed(Xi$cP,2)) * diff(Xi$cA)))\n\t\t if(is.finite(gI)){\n\t\t \t\tif(gI<0){\n\t\t \t\t\tgI = NA\n\t\t \t\t}\n\t\t \t}\n\t\t return(gI)\n\t\t\t}\n", "meta": {"hexsha": "87b54adcd6ac5500ac2ddb030cd4338b0f13d09e", "size": 1175, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gini.r", "max_stars_repo_name": "AMCOOK/bio.survey", "max_stars_repo_head_hexsha": "cbca5a4c5c3bd68fd0885c1b84d9fd940ccf9d17", "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/gini.r", "max_issues_repo_name": "AMCOOK/bio.survey", "max_issues_repo_head_hexsha": "cbca5a4c5c3bd68fd0885c1b84d9fd940ccf9d17", "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/gini.r", "max_forks_repo_name": "AMCOOK/bio.survey", "max_forks_repo_head_hexsha": "cbca5a4c5c3bd68fd0885c1b84d9fd940ccf9d17", "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.6388888889, "max_line_length": 91, "alphanum_fraction": 0.5795744681, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.6945396135123463}} {"text": "#'@title Return the change points of the trend for the given time series\n#'\n#'@description Change points are transition points that optionally exceed a certain magnitude and/or\n#' continue in a certain direction for a specified length of time.\n#' \n#'\n#'@details Transition points are defined as indices at which the time series changes direction.\n#' We can think of the trend of a univariate time series as analogous to a smooth function\n#' \\eqn{f(t)} defined over a given interval of real numbers, \\eqn{[a,b]}. We know that \n#' for \\eqn{t in [a,b]}, \\eqn{f} is increasing on \\eqn{[a,b]} if \\eqn{f'(t) > 0},\n#' \\eqn{f} is decreasing on \\eqn{[a,b]} if \\eqn{f'(t) < 0} and\n#' \\eqn{f} is constant on \\eqn{[a,b]} if \\eqn{f'(t) = 0}. \n#' Similarly, we can examine the sign of the difference of a time series at two subsequent \n#' points in time, to determine if the time series is increasing, decreasing, or constant from one \n#' point in time to the next. \n#' Additionally, if we think of the time series as moving through space, a geometric interpretation\n#' would allow us to treat the time series as a vector with a direction (increasing, decreasing, or constant) \n#' and magnitude (the percent change of the time series from one period of time to the next). This perspective\n#' allows one to adapt what is considered a change point. Thus, a change point can merely be a transition point,\n#' or it can be a transition point whose percent change from the previous value exceeds some threshold,\n#' or it can be a transition point that causes the time series to continue in the new direction for a \n#' specified period of time.\n#' \n#'\n#'@usage tsData.cp <- getTrendChangePoints(tsData, minPctChange, nPeriods)\n#'\n#'@param tsData A time series object.\n#'@param minPctChange The optional lower bound a magnitude must exceed\n#'@param nPeriods An optional number of periods the transition must continue into the future\n#'\n#'@return A vector of integers corresponding to indices of change points in the given time series trend\n#'\n#'@export\n\ngetTrendChangePoints <- function(tsData, minPctChange = NULL, nPeriods = NULL)\n{\n\t# Search neighborhood for points that:\n\t# i) Transition\n\t# ii) Optionally greater than some threshold minPctChange\n\t# iii) Optionally continue in the new direction for nPeriods\n\n\tnHood <- getNeighborhoodDf(getTrend(tsData))\n\n\t# If neither magnitude of change nor the length of the new direction \n # are specified, the change points are merely the transition points\n\n\tnHood.cp <- which(nHood$IS_TP)\n\t\n\t# If a magnitude is specified, transition points must exceed a minimum percent change\n\t# to be considered a change point\n\t\n\tif (!is.null(minPctChange))\n\t\tnHood.cp <- which(nHood$IS_TP & nHood$PCT_CHANGE > minPctChange)\n\t\n\t# If nPeriods is given, each transition point must continue in the new\n\t# direction for nPeriods\n\t\n\tif (!is.null(nPeriods)) {\n\t\tcp <- integer()\n\t\tfor (k in nHood.cp) \n\t\t\tif (length(unique(nHood$DIFF_SIGN[k:(k+nPeriods)])) == 1)\n\t\t\t\tcp[length(cp)+1] <- k\n\t\tnHood.cp <- cp\n\t}\n\t\n\treturn (nHood.cp)\n}", "meta": {"hexsha": "0fdabd66b832c48da75243450b54866a10726d5a", "size": 3193, "ext": "r", "lang": "R", "max_stars_repo_path": "R/getTrendChangePoints.r", "max_stars_repo_name": "OHDSI/Castor", "max_stars_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-11T18:51:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T16:13:55.000Z", "max_issues_repo_path": "R/getTrendChangePoints.r", "max_issues_repo_name": "OHDSI/Castor", "max_issues_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-23T18:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T16:41:40.000Z", "max_forks_repo_path": "R/getTrendChangePoints.r", "max_forks_repo_name": "OHDSI/Castor", "max_forks_repo_head_hexsha": "a64faf53509b50bfedf9057f042355fe2e17974b", "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.6567164179, "max_line_length": 121, "alphanum_fraction": 0.6971500157, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.815232480373843, "lm_q1q2_score": 0.6945395959100712}} {"text": "# Large-Sample Approximation \r\nn=25\r\nB=13\r\n# test statstic\r\nBst=(B-(n/2))/(sqrt(n/4))\r\nprint(Bst)\r\n# critical value\r\nalpha=0.05\r\nz.alpha=qnorm(1-alpha/2)\r\nprint(z.alpha)\r\nprint(\"e BST is not greater than z.alpha, we fail to reject H0\")\r\npvalue=1-pnorm(Bst)\r\nprint(pvalue)\r\n", "meta": {"hexsha": "995714a6fac1f355e40dec067943b0e253a0e1a0", "size": 273, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.23/Ex5_23.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.23/Ex5_23.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.23/Ex5_23.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 19.5, "max_line_length": 65, "alphanum_fraction": 0.6776556777, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6944231800655473}} {"text": "=begin\n # sample-elementary-divisor01.rb\n\n require \"algebra\"\n \n M = SquareMatrix(Rational, 4)\n a = M[\n [2, 0, 0, 0],\n [0, 2, 0, 0],\n [0, 0, 2, 0],\n [5, 0, 0, 2]\n ]\n P = Polynomial(Rational, \"x\")\n MP = SquareMatrix(P, 4)\n \n ac = a._char_matrix(MP)\n ac.display; puts #=>\n #x - 2, 0, 0, 0\n # 0, x - 2, 0, 0\n # 0, 0, x - 2, 0\n # -5, 0, 0, x - 2\n \n p ac.elementary_divisor #=> [1, x - 2, x - 2, x^2 - 4x + 4]\n \n require \"algebra/matrix-algebra-triplet\"\n at = ac.to_triplet.e_diagonalize\n \n at.body.display; puts #=>\n # 1, 0, 0, 0\n # 0, x - 2, 0, 0\n # 0, 0, x - 2, 0\n # 0, 0, 0, x^2 - 4x + 4\n \n at.left.display; puts #=>\n # 0, 0, 0, -1/5\n # 0, 1, 0, 0\n # 0, 0, 1, 0\n # 5, 0, 0, x - 2\n \n at.right.display; puts #=>\n # 1, 0, 0, 1/5x - 2/5\n # 0, 1, 0, 0\n # 0, 0, 1, 0\n # 0, 0, 0, 1\n \n p at.left * ac * at.right == at.body #=> true\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "61d24f5dcf65b161c1cc2eb745da9465ee25d277", "size": 988, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-elementary-divisor01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-elementary-divisor01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-elementary-divisor01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.1632653061, "max_line_length": 61, "alphanum_fraction": 0.4190283401, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6944125908449799}} {"text": "trajanja <- faithful$eruptions\ncekanja <- faithful$waiting\n\nsredina.trajanja <- sum(trajanja)/length(trajanja)\nsredina.trajanja\nsredina.trajanja <- mean(trajanja)\nsredina.trajanja\n\nsredina.cekanja <- mean(cekanja)\nsredina.cekanja\n\nmediana.trajanja <- median(trajanja)\nmediana.trajanja\n\nmediana.cekanja <- median(cekanja)\nmediana.cekanja\n\nkvartili.trajanja <- quantile(trajanja)\nkvartili.trajanja\n\nkvartili.trajanja <- quantile(trajanja, c(0,0.25,0.5,0.75,1) )\nkvartili.trajanja\n\npercentili.trajanja <- quantile(trajanja, \n c(0,0.1,0.2,0.3,0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1) )\npercentili.trajanja\n\nopseg.trajanja <- range(trajanja)[2] - range(trajanja)[1]\nopseg.trajanja\nopseg.trajanja <- max(trajanja) - min(trajanja)\nopseg.trajanja\n\nopseg.medju.kvartilima.trajanja <- IQR(trajanja)\nopseg.medju.kvartilima.trajanja\n\nboxplot(trajanja)\n\ndisperzija.trajanja <- var(trajanja)\ndisperzija.trajanja\n\nstandardna.devijacija.trajanja <- sqrt(var(trajanja))\nstandardna.devijacija.trajanja\nstandardna.devijacija.trajanja <- sd(trajanja)\nstandardna.devijacija.trajanja\n\nkovarijansa.cekanja.i.trajanja = cov(cekanja, trajanja)\nkovarijansa.cekanja.i.trajanja\n\nkoeficiejnat.korelacije.cekanja.i.trajanja <- cor(cekanja, trajanja)\nkoeficiejnat.korelacije.cekanja.i.trajanja\n\nfilter.kratko <- faithful$eruptions < 3\nfilter.kratko\npodaci.kratko <- faithful[filter.kratko,]\npodaci.kratko\ncor(podaci.kratko$waiting, podaci.kratko$eruptions)\n\n\n\n", "meta": {"hexsha": "91a151e5e0980919f4f2e2f2d7a1cd7af80eab52", "size": 1425, "ext": "r", "lang": "R", "max_stars_repo_path": "predavanja/primeri-r/008-numericke-mere.r", "max_stars_repo_name": "PmfBlPRB/PRB", "max_stars_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "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": "predavanja/primeri-r/008-numericke-mere.r", "max_issues_repo_name": "PmfBlPRB/PRB", "max_issues_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-05T11:49:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T07:53:58.000Z", "max_forks_repo_path": "predavanja/primeri-r/008-numericke-mere.r", "max_forks_repo_name": "PmfBlPRB/PRB", "max_forks_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "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": 23.75, "max_line_length": 69, "alphanum_fraction": 0.7796491228, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6943817418178501}} {"text": "# SIMPLE IMPLEMENTATION OF HAMILTONIAN MONTE CARLO.\n#\n# Radford M. Neal, 2010.\n#\n# This program appears in Figure 2 of \"MCMC using Hamiltonian dynamics\",\n# to appear in the Handbook of Markov Chain Monte Carlo.\n#\n# The arguments to the HMC function are as follows:\n#\n# U A function to evaluate minus the log of the density of the\n# distribution to be sampled, plus any constant - ie, the\n# \"potential energy\".\n#\n# grad_U A function to evaluate the gradient of U.\n#\n# epsilon The stepsize to use for the leapfrog steps.\n#\n# L The number of leapfrog steps to do to propose a new state.\n#\n# current_q The current state (position variables only).\n#\n# Momentum variables are sampled from independent standard normal\n# distributions within this function. The value return is the vector\n# of new position variables (equal to current_q if the endpoint of the\n# trajectory was rejected).\n#\n# This function was written for illustrative purposes. More elaborate\n# implementations of this basic HMC method and various variants of HMC\n# are available from my web page, http://www.cs.utoronto.ca/~radford/\n\n\nHMC = function (U, grad_U, epsilon, L, current_q)\n{\n q = current_q\n p = rnorm(length(q),0,1) # independent standard normal variates\n current_p = p\n\n # Make a half step for momentum at the beginning\n\n p = p - epsilon * grad_U(q) / 2\n\n # Alternate full steps for position and momentum\n\n for (i in 1:L)\n {\n # Make a full step for the position\n\n q = q + epsilon * p\n\n # Make a full step for the momentum, except at end of trajectory\n\n if (i!=L) p = p - epsilon * grad_U(q)\n }\n\n # Make a half step for momentum at the end.\n\n p = p - epsilon * grad_U(q) / 2\n\n # Negate momentum at end of trajectory to make the proposal symmetric\n\n p = -p\n\n # Evaluate potential and kinetic energies at start and end of trajectory\n\n current_U = U(current_q)\n current_K = sum(current_p^2) / 2\n proposed_U = U(q)\n proposed_K = sum(p^2) / 2\n\n # Accept or reject the state at end of trajectory, returning either\n # the position at the end of the trajectory or the initial position\n\n if (runif(1) < exp(current_U-proposed_U+current_K-proposed_K))\n {\n return (q) # accept\n }\n else\n {\n return (current_q) # reject\n }\n}\n", "meta": {"hexsha": "96327787d874d527fe12729d1b849c6c5da00288", "size": 2294, "ext": "r", "lang": "R", "max_stars_repo_path": "R/hmc.r", "max_stars_repo_name": "MikeXL/bayes", "max_stars_repo_head_hexsha": "68912c47ae5df94973e960050cdef401676d5acb", "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/hmc.r", "max_issues_repo_name": "MikeXL/bayes", "max_issues_repo_head_hexsha": "68912c47ae5df94973e960050cdef401676d5acb", "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/hmc.r", "max_forks_repo_name": "MikeXL/bayes", "max_forks_repo_head_hexsha": "68912c47ae5df94973e960050cdef401676d5acb", "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.9756097561, "max_line_length": 74, "alphanum_fraction": 0.6891891892, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6943817374910218}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\n\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\nlibrary(seasonal)\r\nlibrary(seasonalview)\r\nlibrary(urca)\r\n\r\n#importar dados do hotel\r\ndados = read.csv(file.choose(),header = F)\r\nprint(dados)\r\n\r\n#treino/teste\r\nocupacaotreino = ts(dados, start = c(2003,1), end = c(2015,12), frequency=12)\r\nocupacaoteste = ts(dados, start = c(2016,1), end = c(2017,12), frequency=12)\r\n\r\n#ARIMA\r\nmodeloarima = auto.arima(ocupacaotreino, trace = F,stepwise = F, approximation = F )\r\npreverarima = forecast(modeloarima, h=24)\r\n\r\n#ets\r\nmodeloets = ets(ocupacaotreino)\r\npreverets = forecast(modeloets, h=24)\r\n\r\nplot(preverarima)\r\nlines(preverets$mean, col=\"red\")\r\n\r\naccuracy(preverarima,ocupacaoteste)\r\naccuracy(preverets,ocupacaoteste)\r\n\r\nplot(ocupacao)\r\nlines(preverarima$mean, col=\"blue\")\r\nlines(preverets$mean, col=\"green\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "836cef2f3123decc47ad03767e845de835169936", "size": 882, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.2.Comparando Modelos.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.2.Comparando Modelos.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.2.Comparando Modelos.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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": 18.7659574468, "max_line_length": 86, "alphanum_fraction": 0.7052154195, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6942511858115706}} {"text": "MSR=11128.14\r\nMSC=544.44\r\nt=5\r\nMSE=2887.29\r\n# relative efficiency of this Latin square design relative to a completely randomized design is\r\nre=(MSR+MSC+(t-1)*MSE)/((t+1)*MSE)\r\nre\r\n\r\n\r\n", "meta": {"hexsha": "9d227087f30fb42a35368f6ecbe835336971a2c1", "size": 185, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.7/Ex15_7.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.7/Ex15_7.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.7/Ex15_7.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 18.5, "max_line_length": 96, "alphanum_fraction": 0.6972972973, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6942436245565577}} {"text": "print (\"first task\")\n\na <- c( -1, 0, 2, 3, -5, 6, 0, 5, -1, 0, 5, -6, 0, 6, -8, 9)\nb <- c( 6, 1, -6, -3, -8, 7, 0, 10, -4, -6, 4, 1, -3, 0, -2, 4)\np <- c ( -4, 6, -7, 3, 0, -7, 5, 4, 3, -6, 7, 1, 0, 4, -2, 3)\nfir <- ((7)*a)+(2*b)\nprint (\"first answer\")\nfir\nsec <- ((-2)*as.numeric(a%*%b))*p+5*(norm(p, type=\"2\"))*a\nprint (\"second answer\")\nsec\nthr <- (-2)*(norm(p, type=\"2\"))*p-7*as.numeric(a%*%b)*p+9*as.numeric(b%*%p)*a\nprint (\"third answer\")\nthr\n\nЗадача 2\n\nprint (\"second task\")\nmat <- rbind(c(0,0,0,-1,8,0,6,-1),c(0,0,0,8,4,0,-5,4),c(0,0,0,11,3,0,0,6),c(7,0,0,0,0,8,0,-2),c(4,0,0,0,0,-4,-2,-6),c(-3,0,-4,0,-2,0,0,0),c(13,-7,0,8,1,0,0,0),c(-4,0,0,9,-5,0,0,0))\nrua <- c(5,-5,-14,10,-6,2,2,8)\nX <- solve(mat)%*%rua\nprint (\"Answer for the sec task\")\nX\nmat%*%X\nrua\n\nзадача 4\n\nprint (\"fourth task\")\nA <- rbind(c(19, 0 ,0 ,0 ,0 ,0 ,0 ,20),c(0 ,7 ,0 ,0, 0, 0, 0, 0),c(0, 0, 13, 0, 0, 0, 0, 0),c(0, 0, 0, 11, 0, 0, 0, 0),c(0, 9, 0, 0, 17, 0, 0, 0),c(0, 0, 0, 0, 0, 5, 0, 0),c(0, 0, 0, 0, 0, 0, 3, 0),c(0, 0, 0, 0, 0, 0, 0, 1))\nA\noptions(digits=3) # Задать количество значащих цифр для вывода\nprint (\"собственные числа \")\nd <- eigen(A)$values; d # Собственные значения матрицы A\nprint (\"собственные вектора\")\nP <- eigen(A)$vectors; P # Собственные векторы A, стоящие в столбцах матрицы\nP\nprint (\" Проверим ортогональность полученного собственного базиса \")\nsum(P[,1]^2) # Например, длина первого собственного вектора\nP[,1] %*% P[,2] # Например, скалярное произведение (f1, f2)\nsum(P[,2]^2); P[,2] %*% P[,3] # длина 2 собственного вектора и (f2, f3)\nsum(P[,3]^2); P[,3] %*% P[,4] # длина 3 собственного вектора и (f3, f4)\nsum(P[,4]^2); P[,4] %*% P[,5] # длина 4 собственного вектора и (f4, f5)\nsum(P[,5]^2); P[,5] %*% P[,6] # длина 5 собственного вектора и (f5, f6)\nsum(P[,6]^2); P[,6] %*% P[,7] # длина 6 собственного вектора и (f6, f7)\nsum(P[,7]^2); P[,7] %*% P[,8] # длина 7 собственного вектора и (f7, f8)\nsum(P[,8]^2); P[,8] %*% P[,1] # длина 8 собственного вектора и (f8, f1)\nprint (\"Таким образом, получили что полученный базис составляют нормированные и\nортогональные между собой вектора, т.е ортонормированный базис.\nТаким образом, получили что полученный базис составляют нормированные и\nортогональные между собой вектора, т.е ортонормированный базис.\")\n\nзадача 6\n\nprint (\"sixth task\")\ninstall.packages(\"lpSolveAPI\") # Загружаем библиотеку\nlibrary(lpSolveAPI) # Активируем библиотеку линейного программирования\nM <- make.lp(ncol= 2) # Объявляем количество неотрицательных переменных в M\nname.lp(M, \"Example\") # Объявляем название \"Example\"для задачи(модели) М\ncolnames(M) <- c(\"X1\", \"X2\") # Объявляем названия переменных в модели М\nlp.control(M, sense = \"max\")$sense# Объявляем задачу на минимум модели М\nset.objfn(M, c(10, 15)) # Задаем целевую функцию: f = 5*X1 +3*X2 для модели М\nadd.constraint(M, c(1,4), \">=\", 4) # Задаем ограничение:\nadd.constraint(M, c(-3, 1), \">=\", -10) # Аналогично\nadd.constraint(M, c(-8, 5), \"<=\", 29) # Аналогично\nadd.constraint(M, c(5, 2), \"<=\", 54) # Аналогично\nrownames(M) <- c(\"A\", \"B\", \"C\", \"D\") # Называем ограничения в модели М\nM\nsolve.lpExtPtr(M)\nget.variables(M) # Оптимальный план\nget.objective(M)\nX1.opt<- get.variables(M)[1]; X1.opt # Оптимальное значение для X1\nX2.opt<- get.variables(M)[2]; X2.opt # Оптимальное значение для X2\nf.max<- get.objective(M); f.max \n", "meta": {"hexsha": "49cdf750df900f4961e3eb9df53a6b54421b0e82", "size": 3306, "ext": "r", "lang": "R", "max_stars_repo_path": "Tasks/Task 8/solution.r", "max_stars_repo_name": "Master-sniffer/Doing-some-tasks-with-R", "max_stars_repo_head_hexsha": "629e7add02437ea22c079ecd7a4279e46028b69c", "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": "Tasks/Task 8/solution.r", "max_issues_repo_name": "Master-sniffer/Doing-some-tasks-with-R", "max_issues_repo_head_hexsha": "629e7add02437ea22c079ecd7a4279e46028b69c", "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": "Tasks/Task 8/solution.r", "max_forks_repo_name": "Master-sniffer/Doing-some-tasks-with-R", "max_forks_repo_head_hexsha": "629e7add02437ea22c079ecd7a4279e46028b69c", "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.08, "max_line_length": 224, "alphanum_fraction": 0.6200846945, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6942285963429833}} {"text": "deg <- function(radians) 180*radians/pi\nrad <- function(degrees) degrees*pi/180\nsind <- function(ang) sin(rad(ang))\ncosd <- function(ang) cos(rad(ang))\ntand <- function(ang) tan(rad(ang))\nasind <- function(v) deg(asin(v))\nacosd <- function(v) deg(acos(v))\natand <- function(v) deg(atan(v))\n\nr <- pi/3\nrd <- deg(r)\n\nprint( c( sin(r), sind(rd)) )\nprint( c( cos(r), cosd(rd)) )\nprint( c( tan(r), tand(rd)) )\n\nS <- sin(pi/4)\nC <- cos(pi/3)\nT <- tan(pi/4)\n\nprint( c( asin(S), asind(S) ) )\nprint( c( acos(C), acosd(C) ) )\nprint( c( atan(T), atand(T) ) )\n", "meta": {"hexsha": "4e5ffed723cea69768a9ad28037bf19a91e8c89f", "size": 548, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Trigonometric-functions/R/trigonometric-functions.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/Trigonometric-functions/R/trigonometric-functions.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/Trigonometric-functions/R/trigonometric-functions.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": 22.8333333333, "max_line_length": 39, "alphanum_fraction": 0.598540146, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6941480566108318}} {"text": "# Get data\ndigits.train <- read.table(url(\"http://www.amlbook.com/data/zip/features.train\"))\ndigits.test <- read.table(url(\"http://www.amlbook.com/data/zip/features.test\"))\n\ncolnames(digits.train) <- c(\"digit\", \"symmetry\", \"intensity\")\ncolnames(digits.test) <- c(\"digit\", \"symmetry\", \"intensity\")\n\ndigits.train$digit <- factor(digits.train$digit)\ndigits.test$digit <- factor(digits.test$digit)\n\n\n# Visualize\nggplot(digits.train, aes(x = symmetry, y = intensity, color = digit)) + \n geom_point()\n\nsummary(digits.train)\nsummary(digits.train$digit)\n\nq2_4 <- t(sapply(0:9, function(myDigit) {\n fit <- svm(digit == myDigit ~ ., data = digits.train, \n scale = FALSE, \n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 0.01,\n type = \"C-classification\")\n \n # fit\n pred <- predict(fit, digits.train[-1])\n \n Ein = sum(pred != (digits.train$digit == myDigit))/nrow(digits.train)\n table(pred, (digits.train$digit == myDigit))\n cbind(myDigit, Ein, fit$tot.nSV)\n}))\n\n\ndigits.train.sub <- subset(digits.train, digit == 1 | digit == 5)\ndigits.test.sub <- subset(digits.test, digit == 1 | digit == 5)\n\nq5 <- t(sapply(c(0.0001, 0.001, 0.01, 0.1, 1), function(cst) {\n myDigit = 5\n fit <- svm(digit == myDigit ~ ., data = digits.train.sub, \n scale = FALSE, \n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = cst,\n type = \"C-classification\")\n pred <- predict(fit, digits.train.sub[-1])\n \n Ein = sum(pred != (digits.train.sub$digit == myDigit))/nrow(digits.train.sub)\n \n pred <- predict(fit, digits.test.sub[-1])\n Eout = sum(pred != (digits.test.sub$digit == myDigit))/nrow(digits.test.sub)\n \n cbind(cst, Ein, Eout, fit$tot.nSV)\n}))\n\n# q6, run q5 with degree = 5\n\nmyDigit = 5\nq7 <- tune(svm,digit == myDigit ~ ., data = digits.train.sub, \n scale = FALSE, type = \"C-classification\",\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, \n ranges = list(cost = c(.0001, .001, .01, .1, 1)),\n tunecontrol = tune.control(sampling = \"cross\", cross = 10, nrepeat = 100))\n\nq7\n\n# Another way\nrslts <- lapply(1:100, function(x) {\n ordIdx <- sample(nrow(digits.train.sub))\n fit.0001 <- svm(digit == myDigit ~ ., data = digits.train.sub[ordIdx, ], \n scale = FALSE, seed = x,\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 0.0001,\n type = \"C-classification\", cross = 10)\n \n fit.001 <- svm(digit == myDigit ~ ., data = digits.train.sub[ordIdx, ], \n scale = FALSE, seed = x,\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 0.001,\n type = \"C-classification\", cross = 10)\n \n fit.01 <- svm(digit == myDigit ~ ., data = digits.train.sub[ordIdx, ], \n scale = FALSE, seed = x,\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 0.01,\n type = \"C-classification\", cross = 10)\n \n fit.1 <- svm(digit == myDigit ~ ., data = digits.train.sub[ordIdx, ], \n scale = FALSE, seed = x,\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 0.1,\n type = \"C-classification\", cross = 10)\n \n fit1 <- svm(digit == myDigit ~ ., data = digits.train.sub[ordIdx, ], \n scale = FALSE, seed = x,\n kernel = \"polynomial\", degree = 2, gamma = 1, coef0 = 1, cost = 1,\n type = \"C-classification\", cross = 10)\n\n 1 - cbind(fit.0001$tot.accuracy, fit.001$tot.accuracy, fit.01$tot.accuracy, fit.1$tot.accuracy, fit1$tot.accuracy)/100\n})\n\nsummary(sapply(rslts, function(x) which(x == min(x))[1]))\nsummary(sapply(rslts, function(x) x[2]))\n\nmyDigit = 5\nq9_10 <- t(sapply(c(1e-2, 1, 1e2, 1e4, 1e6), function(cst) {\n fit <- svm(digit == myDigit ~ ., data = digits.train.sub, \n scale = FALSE, \n kernel = \"radial\", gamma = 1, cost = cst,\n type = \"C-classification\")\n pred <- predict(fit, digits.train.sub[-1])\n \n Ein = sum(pred != (digits.train.sub$digit == myDigit))/nrow(digits.train.sub)\n \n pred <- predict(fit, digits.test.sub[-1])\n Eout = sum(pred != (digits.test.sub$digit == myDigit))/nrow(digits.test.sub)\n \n cbind(cst, Ein, Eout, fit$tot.nSV)\n}))\n\n\nq9_10\n", "meta": {"hexsha": "16a4aca726fd030bd4329af4e6bae545626b2d07", "size": 4292, "ext": "r", "lang": "R", "max_stars_repo_path": "Homework_8/Rcode/by_sanealytics/hw8_svm_kernel.r", "max_stars_repo_name": "freeernest/edX-Learning-From-Data-Solutions", "max_stars_repo_head_hexsha": "5cbcf0885b5fdb00c3658d230fc7bb7e20b5cf44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2015-01-27T11:09:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T12:01:35.000Z", "max_issues_repo_path": "Homework_8/Rcode/by_sanealytics/hw8_svm_kernel.r", "max_issues_repo_name": "freeernest/edX-Learning-From-Data-Solutions", "max_issues_repo_head_hexsha": "5cbcf0885b5fdb00c3658d230fc7bb7e20b5cf44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-25T05:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-04T14:44:32.000Z", "max_forks_repo_path": "Homework_8/Rcode/by_sanealytics/hw8_svm_kernel.r", "max_forks_repo_name": "freeernest/edX-Learning-From-Data-Solutions", "max_forks_repo_head_hexsha": "5cbcf0885b5fdb00c3658d230fc7bb7e20b5cf44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-04-06T18:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T18:08:40.000Z", "avg_line_length": 37.0, "max_line_length": 120, "alphanum_fraction": 0.5761882572, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6940829123984844}} {"text": "\ndf = NULL\n\n# Fixed parameters\ns <- .2\ngl <- .01\ndelta <- .05\nalpha <- .3\nlambda <- .9\nphi <- -.2\ntheta <- .01\ngR <- .01\n\n# Initialize dynamic process\nkycurr <- s/(gl+delta+.02) # start near a BGP\nkyalt <- s/(gl+delta+.02) # start near a BGP\nRcurr <- 10 # start everyone with same R stock\nAcurr <- 2\nAalt <- 20\n\n\ndf = NULL # initialize a dataframe\ndfalt = NULL # initialize a dataframe\nname = \"A\"\nnamealt = \"B\"\n\nfor (t in 1:250) # do for this many periods\n{\n gA <- theta*(Rcurr^lambda)/(Acurr^(1-phi)) # calculate growth in k/y given current k/y\n gky <- (1-alpha)*(s/kycurr - delta - gA - gl) \n df = rbind(df, data.frame(t,Acurr,gA,gky,kycurr,name)) # add to dataframe\n kycurr <- (1+gky)*(kycurr)\n Acurr <- (1+gA)*(Acurr) # update current k/y for next period\n gA <- theta*(Rcurr^lambda)/(Aalt^(1-phi))\n gky <- (1-alpha)*(s/kyalt - delta - gA - gl)\n dfalt = rbind(dfalt, data.frame(t,Aalt,gA,gky,kyalt,namealt)) # add to dataframe\n kyalt <- (1+gky)*(kyalt)\n Aalt <- (1+gA)*(Aalt)\n Rcurr <- (1+gR)*Rcurr\n}\n\ncolnames(dfalt) <- c(\"t\",\"Acurr\",\"gA\",\"gky\",\"kycurr\",\"name\")\ndfgraph = rbind(df,dfalt)\n\ndfgraph$lny <- (alpha/(1-alpha))*log(dfgraph$ky) + 4 + log(dfgraph$Acurr)\ndfgraph$gy <- (alpha/(1-alpha))*dfgraph$gky + dfgraph$gA\n\ndf <-dfgraph[order(dfgraph$name, dfgraph$t),]\n\nfig <- plot_ly(df,\n x = ~t, \n y = ~lny, \n color = ~name,\n hoverinfo = \"text\",\n type = 'scatter',\n mode = 'lines'\n)\n\n\n\nfig <- fig %>% animation_slider(\n hide = T\n)\nfig <- fig %>% animation_button(\n x = 1, xanchor = \"right\", y = 0.4, yanchor = \"bottom\"\n)\nfig <- layout(fig, title = list(text = 'Level of GDP per capita over time', x=0),\n xaxis = list(title = 'Time', range=c(0,30),dtick=5),\n yaxis = list (title = 'Log GDP per capita'\n )\n)\n\n#api_create(fig, filename = \"me-lny-prodanimated\")\n", "meta": {"hexsha": "7d8c114cf8576982c93a52bf27c2e2044e003b66", "size": 1899, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_ME_Prod.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_ME_Prod.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "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/Guide_ME_Prod.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 25.6621621622, "max_line_length": 88, "alphanum_fraction": 0.5781990521, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6940451547140334}} {"text": "\nminCanopyTemperature = minTair + cropHeatFlux / ((rhoDensityAir * specificHeatCapacityAir * conductance / lambdaV) * 1000)\nmaxCanopyTemperature = maxTair + cropHeatFlux / ((rhoDensityAir * specificHeatCapacityAir * conductance / lambdaV) * 1000)\n\n", "meta": {"hexsha": "7418b0c52836ad166ba2b7e43073a36e1f405a9d", "size": 248, "ext": "r", "lang": "R", "max_stars_repo_path": "test/data/energyBalance/crop2ml/Algo/R/canopytemperature.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": "test/data/energyBalance/crop2ml/Algo/R/canopytemperature.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": "test/data/energyBalance/crop2ml/Algo/R/canopytemperature.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": 49.6, "max_line_length": 122, "alphanum_fraction": 0.7822580645, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6939608290740814}} {"text": "# Euler1 in R\r\n\r\nmySum <- function (n, size) {\r\n n * (ceiling(size/n)**2 + ceiling(size/n)) / 2\r\n}\r\n\r\neuler1 <- function (size) {\r\n return (mySum(3,size) + mySum(5,size) - mySum(15,size))\r\n}\r\n\r\neuler1(999)", "meta": {"hexsha": "2a1eda334d4357513bbd9475a6c6924998dc7dba", "size": 211, "ext": "r", "lang": "R", "max_stars_repo_path": "r/euler1_4.r", "max_stars_repo_name": "gregorymorrison/euler1", "max_stars_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-13T11:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-13T11:11:50.000Z", "max_issues_repo_path": "r/euler1_4.r", "max_issues_repo_name": "gdm9000/euler1", "max_issues_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "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/euler1_4.r", "max_forks_repo_name": "gdm9000/euler1", "max_forks_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-10T00:27:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-10T00:27:17.000Z", "avg_line_length": 19.1818181818, "max_line_length": 60, "alphanum_fraction": 0.5592417062, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6936994077697634}} {"text": "\n# Algorithms_potts\n# Extend algorithms to work on pott sampler.\n\n# library(extraDistr) # CHECK -- do we need this?\nsource(\"tools.r\")\n\n# Simulate states from the Potts model, using auxiliary Gaussian variables.\n#\n# A: adjacency matrix\n# beta: inverse-temperatures\n# init: intial state for the chain\n# n_states: number of states each particle can adopt.\n# n_iter: number of sampling iteration.\n# B (not implemented): external magnetic field.\n# alpha_modif: modification along diagonal of A to make it semi-positive def.\n# retain_alpha: whether to use alpha_modif or instead use min eigenvalue.\n# pertub (not implemented): if TRUE, adds flip transition.\n#\n# return: matrix with samples.\nag_potts_simple <- function (A, beta, init, n_states = 2, n_iter = 1000, B = 0,\n alpha_modif = 1e-7, retain_alpha = FALSE,\n perturb = FALSE) {\n if (B != 0) print(\"WARNING: non-zero magnetic field is not supported.\")\n if (perturb) print(\"WARNING: pertub = TRUE is not supported.\")\n \n if (retain_alpha) {\n alpha = alpha_modif\n } else {\n alpha = abs(min(eigen(A, symmetric = TRUE, only.values = TRUE)$values))\n alpha = alpha + alpha_modif\n }\n\n n_particles = nrow(A)\n C = 2 * beta * (A + alpha * diag(n_particles))\n L = t(chol(solve(C)))\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n # Auxiliary Gaussians\n Q = matrix(NA, nrow = n_particles, ncol = n_states)\n\n for (i in 2:n_iter) {\n for (l in 1:n_states) {\n mu_q = rep(0, n_particles)\n mu_q[X[i - 1, ] == l] = 1\n Q[, l] = mvrnorm_cholesky(n = 1, mu = mu_q, L = L)\n }\n\n P = C %*% Q\n\n u = runif(n_particles, 0, 1)\n\n for (j in 1:n_particles) {\n p = rep(NA, n_states)\n for (l in 1:n_states) {\n p[l] = exp(P[j, l])\n }\n norm_const = sum(p)\n\n state = 1\n p_current = p[state] / norm_const\n while (u[j] > p_current) {\n state = state + 1\n p_current = p_current + p[state] / norm_const\n }\n \n X[i, j] = state\n }\n }\n X\n}\n\n\n\n###############################################################################\n\n# Simulate states from the Potts model, using auxiliary Gaussian variables,\n# and a low rank approximation. Takes in the modified adjacency matrix,\n# C_tilde. See the wrapper below, which takes in A and beta.\n# \n#\n# C_tilde: modified adjacency matrix, which is low rank, semi+ def,\n# and scaled by the inverse-temperature beta.\n# init: intial state for the chain\n# n_states: number of states each particle can adopt.\n# n_iter: number of sampling iteration.\n# epsilon: value below which an eigenvalue is considered to be 0.\n# eigenvalue_rounding: determines how different two eigen values need to\n# be in order to be considered non-identical.\n# Required to handle numerical precision of LAPACK. \n#\n# return: matrix with samples.\nag_potts_lowrank__ <- function (C, init, n_states = 2, n_iter = 1000,\n epsilon = 1e-12, eigenvalue_rounding = 1e12) {\n n_particles = nrow(C)\n spectral_decomposition = eigen(C, symmetric = TRUE)\n\n n_rank = length(\n spectral_decomposition$values[spectral_decomposition$values > epsilon])\n eigen_values_sqrt = sqrt(spectral_decomposition$values[1:n_rank])\n\n scaled_eigenvectors <- matrix(NA, nrow = n_particles, ncol = n_rank)\n for (i in 1:n_rank) {\n scaled_eigenvectors[, i] = spectral_decomposition$values[i] *\n spectral_decomposition$vectors[, i]\n }\n \n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n # Auxiliary Gaussians\n Q = matrix(NA, nrow = n_rank, ncol = n_states)\n\n for (i in 2:n_iter) {\n for (l in 1:n_states) {\n Y = rep(0, n_particles)\n Y[X[i - 1, ] == l] = 1\n mu_q = t(spectral_decomposition$vector[, 1:n_rank]) %*% Y\n\n # set.seed(1954)\n standard_normal = rnorm(n_rank)\n Q[, l] = standard_normal / eigen_values_sqrt + mu_q\n }\n\n P = scaled_eigenvectors %*% Q\n\n u = runif(n_particles, 0, 1)\n\n for (j in 1:n_particles) {\n p = exp(P[j, ])\n norm_const = sum(p)\n\n state = 1\n p_current = p[state] / norm_const\n while (u[j] > p_current) {\n state = state + 1\n p_current = p_current + p[state] / norm_const\n }\n\n X[i, j] = state\n }\n }\n X\n}\n\n# Wrapper around the above function, which takes A and beta.\nag_potts_lowrank <- function(A, beta, init, n_states = 2, n_iter = 1000,\n alpha_modif = 1e-7, epsilon = 1e-12) {\n n_particles = nrow(A)\n # spectral_decomposition = eigen(2 * beta * A, symmetric = TRUE)\n # n_rank = length(\n # spectral_decomposition$values[abs(spectral_decomposition$values) > epsilon])\n # \n # A_tilde = matrix(0, nrow = n_particles, ncol = n_particles)\n # for (i in 1:n_rank) {\n # A_tilde = A_tilde +\n # spectral_decomposition$values[i] * spectral_decomposition$vectors[, i] %*% \n # t(spectral_decomposition$vectors[, i])\n # }\n # \n # alpha <- abs(min(eigen(A_tilde, symmetric = TRUE, only.values = TRUE)$values))\n # C_tilde <- A_tilde + alpha * diag(n_particles)\n\n alpha = abs(min(eigen(A, symmetric = TRUE, only.values = TRUE)$values))\n alpha = alpha + alpha_modif\n C = 2 * beta * (A + alpha * diag(n_particles))\n\n ag_potts_lowrank__(C, init, n_states, n_iter, epsilon)\n}\n\n\n## Test code\n\n# x <- init_potts\n# H = 0\n# for (i in 1:n_part) {\n# for (j in 1:n_part) {\n# H = H + (x[i] == x[j]) * C[i, j]\n# }\n# }\n\n\n# 1) Reduce rank\n# n_particles <- 16\n# A <- adjacency_graph(n_particles, \"complete\")\n# eigen_output <- eigen(A, symmetric = TRUE)\n# epsilon <- 1e-12\n# eigenvalue_rounding <- 1e12\n# n_rank = length(round(\n# eigen_output$values[abs(eigen_output$values) > epsilon] *\n# eigenvalue_rounding) / eigenvalue_rounding)\n# \n# # Nake sure we have eigenvalues and eigenvectors\n# # index <- 4\n# # t(A %*% eigen_output$vectors[, index])\n# # t(eigen_output$values[index] * eigen_output$vectors[, index])\n# \n# A_tilde = matrix(0, nrow = n_particles, ncol = n_particles)\n# for (i in 1:n_rank) {\n# A_tilde = A_tilde +\n# eigen_output$values[i] * eigen_output$vectors[, i] %*% t(eigen_output$vectors[, i])\n# }\n# # QUESTION: why does A_tilde not recover A??\n# \n# alpha <- abs(min(eigen(A_tilde, symmetric = TRUE, only.values = TRUE)$values))\n# C_tilde <- A_tilde + alpha * diag(n_particles)\n# init <- sample(1:n_states, n_particles, replace = T)\n# n_states = 4\n\n# B_tilde <- eigen_output$values + eigen_output$vectors[, 1] %*% t(eigen_output$vectors[, 1])\n# eigen_output$values[3] * eigen_output$vectors[, 3]\n# A %*% eigen_output$vectors[, 3]\n\n\n # # NOTE: The Auxiliary variable I introduce is an overcomplication.\n # # The ag_potts_simple for a simpler version.\n # # DEPRECATE.\n # ag_potts <- function (A, beta, init, n_states = 2, n_iter = 1000, B = 0,\n # alpha_modif = 1e-7, retain_alpha = FALSE,\n # perturb = FALSE) {\n # print(\"WARNING: We recommend using ag_potts_simple.\")\n # if (retain_alpha) {\n # alpha = alpha_modif\n # } else {\n # # CHECK ME!\n # alpha = abs(min(eigen(A, symmetric = TRUE, only.values = TRUE)$values))\n # alpha = alpha + alpha_modif\n # }\n # \n # n_particles = nrow(A)\n # C = beta * (A + alpha * diag(n_particles))\n # L = 2 * t(chol(solve(C)))\n # X = matrix(NA, nrow = n_iter, ncol = n_particles)\n # x = init\n # X[1, ] = x\n # \n # # Auxiliary Gaussians\n # Q = matrix(NA, nrow = n_particles, ncol = n_states)\n # \n # for (i in 2:n_iter) {\n # for (l in 1:n_states) {\n # mu_q = rep(-1, n_particles)\n # mu_q[X[i - 1, ] == l] = 1\n # Q[, l] = mvrnorm_cholesky(n = 1, mu = mu_q, L = L)\n # }\n # \n # P = C %*% Q\n # P_row_sum_term = 0.25 * rowSums(P)\n # P_half = 0.5 * P\n # \n # u = runif(n_particles, 0, 1)\n # \n # for (j in 1:n_particles) {\n # p = rep(NA, n_states)\n # for (l in 1:n_states) {\n # p[l] = exp(P_half[j, l] - P_row_sum_term[j])\n # }\n # norm_const = sum(p)\n # \n # state = 1\n # p_current = p[state] / norm_const\n # while (u[j] > p_current) {\n # state = state + 1\n # p_current = p_current + p[state] / norm_const\n # }\n # \n # X[i, j] = state\n # }\n # }\n # X\n # } \n", "meta": {"hexsha": "7af10d69e194870a1d1bc55a81a1eb9f9d39aeb0", "size": 8372, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/algorithms_potts.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/algorithms_potts.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/algorithms_potts.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": 30.4436363636, "max_line_length": 93, "alphanum_fraction": 0.5934065934, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6936720087636364}} {"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\n############## FUNCTION DEFINITIONS #################################\n\n#function to calculate the log-likelihood for nonstationary GEV model with trend in location parameter\nGEV.likelihood = function(mu,muslope,sigma,epsilon,data,time_index){\n t = (1+epsilon*((data-mu-(muslope*time_index))/sigma))^(-1/epsilon)\n pdf = (t^(epsilon+1))*exp(-t)/sigma\n log.likelihood = sum(log(pdf))\n return(log.likelihood)\n}\n\n#function to create time index for any baseyear\ntime.index = function(Year,ReferenceYear){\n t = Year - ReferenceYear\n return(t)\n}\n#function to calculate nonstationary return period for event z\ncalc.nstat.ret.period = function(mu_0,mu_1,scale,shape,z,baseyear,analysisyear){\n i = 0\n accept_prob = 1\n prod_accept_prob = 1\n t = 1\n while (accept_prob > 0){\n accept_prob = exp(-((1 + (shape*((z-(mu_0+mu_1*(analysisyear-baseyear)+(mu_1*i)))/scale)))^(-1/shape)))\n prod_accept_prob = prod_accept_prob*accept_prob\n t = t + prod_accept_prob\n i = i+1\n }\n return(t)\n}\n\n#function to calculate nonstationary \"n\" year return event (n>=2)\ncalc.nstat.ret.event = function(mu_0,mu_1,scale,shape,n,baseyear,analysisyear,epsilon){\n stat_params.default = 1\n if (mu_1<=0){\n z = mu_0 - scale*(1-(-log(1 - (1/n)))^(-shape))/shape\n return(z)\n } else {\n #calculate lower bound of n year event\n lb = mu_0 - scale*(1-(-log(1 - (1/n)))^(-shape))/shape\n t_lb = n\n while (t_lb > n-epsilon){\n t_lb = calc.nstat.ret.period(mu_0,mu_1,scale,shape,lb,baseyear,analysisyear)\n if(t_lb>n-epsilon){lb = 0.9*lb}\n }\n #calculate upper bound of n year event\n ub = mu_0 + mu_1*(analysisyear-baseyear) +mu_1*n - scale*(1-(-log(1 - (1/(n))))^(-shape))/shape \n t_ub = n\n while (t_ub < n+epsilon){\n t_ub = calc.nstat.ret.period(mu_0,mu_1,scale,shape,ub,baseyear,analysisyear)\n if(t_ub epsilon) { \n z = (lb+ub)/2\n t = calc.nstat.ret.period(mu_0,mu_1,scale,shape,z,baseyear,analysisyear)\n if (t < n) {\n lb = z\n } else {ub = z}\n }\n return(z)\n }\n \n}\n\n#function to plot return event with respect to return period\nret.event.plot.data = function(baseyear_par_data, min_ret_index, max_ret_index,mle_year_index, avg_year_index, analysisyear){\n t = seq(5,100,5)\n epsilon_seq = 0.01*t\n min = NULL\n max = NULL\n mle = NULL\n avg = NULL\n for (i in 1:length(t)){\n min[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[min_ret_index],baseyear_par_data$location_slope[min_ret_index],baseyear_par_data$scale[min_ret_index],baseyear_par_data$shape[min_ret_index],t[i],baseyear_par_data$year[min_ret_index],analysisyear,epsilon_seq[i])\n max[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[max_ret_index],baseyear_par_data$location_slope[max_ret_index],baseyear_par_data$scale[max_ret_index],baseyear_par_data$shape[max_ret_index],t[i],baseyear_par_data$year[max_ret_index],analysisyear,epsilon_seq[i])\n mle[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[mle_year_index],baseyear_par_data$location_slope[mle_year_index],baseyear_par_data$scale[mle_year_index],baseyear_par_data$shape[mle_year_index],t[i],baseyear_par_data$year[mle_year_index],analysisyear,epsilon_seq[i])\n avg[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[avg_year_index],baseyear_par_data$location_slope[avg_year_index],baseyear_par_data$scale[avg_year_index],baseyear_par_data$shape[avg_year_index],t[i],baseyear_par_data$year[avg_year_index],analysisyear,epsilon_seq[i]) \n }\n y_data = data.frame(t,min,max,mle,avg)\n write.table(y_data, file = paste0(output_file,\"_reteventplot_data.csv\"), row.names=FALSE, na=\"\", col.names=c(\"year\",\"min\",\"max\",\"mle\",\"avg\"), sep=\",\")\n return(y_data)\n}\n#function to plot return event trend with respect to analysis year for a given return period\nret.event.trend = function(baseyear_par_data,min_ret_index, max_ret_index,mle_year_index, avg_year_index, return_period,first_analysis_year,last_analysis_year,interval){\n epsilon = 0.01*return_period\n analysisyear = seq(first_analysis_year,last_analysis_year,interval)\n min = NULL\n max = NULL\n mle = NULL\n avg = NULL\n for (i in 1:length(analysisyear)){\n min[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[min_ret_index],baseyear_par_data$location_slope[min_ret_index],baseyear_par_data$scale[min_ret_index],baseyear_par_data$shape[min_ret_index],return_period,baseyear_par_data$year[min_ret_index],analysisyear[i],epsilon)\n max[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[max_ret_index],baseyear_par_data$location_slope[max_ret_index],baseyear_par_data$scale[max_ret_index],baseyear_par_data$shape[max_ret_index],return_period,baseyear_par_data$year[max_ret_index],analysisyear[i],epsilon)\n mle[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[mle_year_index],baseyear_par_data$location_slope[mle_year_index],baseyear_par_data$scale[mle_year_index],baseyear_par_data$shape[mle_year_index],return_period,baseyear_par_data$year[mle_year_index],analysisyear[i],epsilon)\n avg[i] = calc.nstat.ret.event(baseyear_par_data$location_intercept[avg_year_index],baseyear_par_data$location_slope[avg_year_index],baseyear_par_data$scale[avg_year_index],baseyear_par_data$shape[avg_year_index],return_period,baseyear_par_data$year[avg_year_index],analysisyear[i],epsilon)\n }\n ret_trend_data = data.frame(analysisyear,min,max,mle,avg)\n write.table(ret_trend_data, file = paste0(output_file,\"_retevent_trend_data.csv\"), row.names=FALSE, na=\"\", col.names=c(\"analysisyear\",\"min\",\"max\",\"mle\",\"avg\"), sep=\",\")\n return(ret_trend_data)\n}\n\n#function to calculate likelihood value\nlikelihood.val = function(data,time_index,mu0,mu1,scale,shape){\n k =(1 + (shape*(data-(mu0+(mu1*time_index)))/scale))^(-1/shape)\n pdf = (1/scale)*((k)^(shape+1))*exp(-k)\n llf = -sum(log(pdf))\n return(llf)\n}\n\n#function to calculate stationary return event\ncalc.stat.ret.event = function(mu, scale, shape, n){\n z = mu - scale*(1-(-log(1 - (1/n)))^(-shape))/shape\n return(z)\n}\n\n#function to do MCMC sampling\ndraw.MCMC.samples = function(Data,time_index,InitialValues,LocationInterceptPrior,LocationSlopePrior,ScalePrior,ShapePrior,ProposalWidth,n_samples){\n mu_lb = LocationInterceptPrior[1]\n mu_ub = LocationInterceptPrior[2]\n muslope_lb = LocationSlopePrior[1]\n muslope_ub = LocationSlopePrior[2]\n scale_lb = ScalePrior[1]\n scale_ub = ScalePrior[2]\n shape_lb = ShapePrior[1]\n shape_ub = ShapePrior[2]\n mu = InitialValues[1]\n muslope = InitialValues[2]\n scale = InitialValues[3]\n shape = InitialValues[4]\n mu_proposal_width = ProposalWidth[1]\n muslope_proposal_width = ProposalWidth[2]\n scale_proposal_width = ProposalWidth[3]\n shape_proposal_width = ProposalWidth[4]\n mu_post=NULL\n muslope_post=NULL\n scale_post=NULL\n shape_post=NULL\n rng_seed = 1\n sample = 0\n rng = 0\n set.seed(rng_seed)\n \n #start the algorithm; (NOTE: if likelihood not finite for initial values of parameters, select different values).\n \n if(is.finite(GEV.likelihood(mu,muslope,scale,shape,Data,time_index))==FALSE){\n while (is.finite(GEV.likelihood(mu,muslope,scale,shape,Data,time_index))==FALSE){\n mu = runif(1,mu_lb,mu_ub)\n muslope = runif(1,muslope_lb,muslope_ub)\n scale = runif(1,scale_lb,scale_ub)\n shape = runif(1,shape_lb,shape_ub)\n rng = rng+1\n }\n }\n \n while (sample < n_samples){\n \n #start sampling proposals from jump distribution\n mu_proposed = rnorm(1,mu,mu_proposal_width)\n muslope_proposed = rnorm(1,muslope,muslope_proposal_width)\n scale_proposed = rnorm(1,scale,scale_proposal_width)\n shape_proposed = rnorm(1,shape,shape_proposal_width)\n #counter for random number generated\n rng = rng+1\n \n #check if all the values are finite for acceptance ratio calculation\n \n suppressWarnings(if (is.finite(GEV.likelihood(mu_proposed,muslope_proposed,scale_proposed,shape_proposed,Data,time_index))==TRUE & is.finite(dunif(mu_proposed,mu_lb,mu_ub,log = TRUE)) == TRUE & is.finite(dunif(scale_proposed,scale_lb,scale_ub,log = TRUE)) == TRUE & is.finite(dunif(shape_proposed,shape_lb,shape_ub,log = TRUE)) == TRUE & is.finite(dunif(muslope_proposed,muslope_lb,muslope_ub,log = TRUE))==TRUE) {\n \n log.r = GEV.likelihood(mu_proposed,muslope_proposed,scale_proposed,shape_proposed,Data,time_index) + dunif(mu_proposed,mu_lb,mu_ub,log = TRUE) + dunif(muslope_proposed,muslope_lb,muslope_ub,log = TRUE) + dunif(scale_proposed,scale_lb,scale_ub,log = TRUE) + dunif(shape_proposed,shape_lb,shape_ub,log = TRUE) - GEV.likelihood(mu,muslope,scale,shape,Data,time_index) - dunif(mu,mu_lb,mu_ub,log = TRUE) - dunif(scale,scale_lb,scale_ub,log = TRUE) - dunif(shape,shape_lb,shape_ub,log = TRUE) - dunif(muslope,muslope_lb,muslope_ub,log = TRUE)\n \n \n #collect new sample if criteria satisfied\n if (log.r > log(runif(1,0,1))){\n mu = mu_proposed\n muslope = muslope_proposed\n scale = scale_proposed\n shape = shape_proposed\n \n }\n })\n mu_post = c(mu_post,mu)\n scale_post = c(scale_post,scale)\n shape_post = c(shape_post,shape)\n muslope_post = c(muslope_post,muslope)\n sample = sample + 1\n }\n parameters = data.frame(mu_post,muslope_post,scale_post,shape_post)\n return(parameters)\n}", "meta": {"hexsha": "db6f121614e22d8c16b6d37096d28a3ad7b55e4e", "size": 10540, "ext": "r", "lang": "R", "max_stars_repo_path": "function.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": "function.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": "function.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": 49.9526066351, "max_line_length": 543, "alphanum_fraction": 0.7411764706, "num_tokens": 3019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6934535207379232}} {"text": "# Imitating the amount of expenses in following:\n# A person, older than 65 y.o., buys some medicine during 1 year.\n# The number of purchases ~ Po(25), purchase's amount of money ~ U(5,95)\n\n# calculating total costs for each year by the number of purchases\nCostCalculate <- function(num)\n{\n return(sum(runif(num, 5, 95)))\n}\n\nDrawPlot <- function(title, x = Timeline, y)\n{\n ggplot(data = NULL, aes(x, y)) + geom_path() + ggtitle(title) + xlab(substitute(x)) + ylab(substitute(y))\n}\n\nlibrary(ggplot2)\n \n# number of years to imitate independently\nY <- 1000\nTimeline <- seq(from = 1, to = Y, by = 1)\n\n# imitating Y years for one person:\n# number of purchases\nPurchaseNum <- rpois(Y,25)\nExpenses <- sapply(PurchaseNum, CostCalculate)\n\nDrawPlot(y = PurchaseNum, title = \"Purchase Number\")\nDrawPlot(y = Expenses, title = \"Expenses\")\n\nAvgCost <- mean(Expenses)\nprint(\"Average expenses cost is:\")\nprint(AvgCost)\n\n# P{costs per year >= 2000} - ?\np <- length(Expenses[Expenses >= 2000])/length(Expenses)\nprint(\"P{costs per year >= 2000} is:\")\nprint(p)", "meta": {"hexsha": "db9c4181aa60e5d0afff982f963e496846e89d85", "size": 1042, "ext": "r", "lang": "R", "max_stars_repo_path": "lab4.r", "max_stars_repo_name": "alexgulyi/randimitation", "max_stars_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": "lab4.r", "max_issues_repo_name": "alexgulyi/randimitation", "max_issues_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": "lab4.r", "max_forks_repo_name": "alexgulyi/randimitation", "max_forks_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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.1621621622, "max_line_length": 107, "alphanum_fraction": 0.6967370441, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6931565076146209}} {"text": "#' Quantile Sheets with pya's constraint\n#'\n#' Estimate conditional quantile sheet Schlossmacher's\n#' Alternating b/w weighted regression and recomputing weights\n#' @param x vector or matrix whose rows contains predictors\n#' of each observations.\n#' @param y vector of the variable we want to estimate its condtional cdf\n#' @param arg_bs argument for b-spline\n#' @param dims knots number\n#' @param ords order of splien\n#' @param opt optimization methods\n#' @param maxit maximum iteration for Schlossmacherl's method\n#' @param ntaus number of taus to be considered\n#' @param analysis indicator whther plot analysis\n#' @param trace\n#' @param sp smoothing coefficients\n#' @param tol tolerance for Schlossmacher's\n#' @param ... additional arguement pass into scam (eg. gamma, weights)\n#'\n#' @import scam\n#'\n#' @return a scam object\n#'\n\nqs_scam <- function(x, y, maxit = 10, ntaus = 10,\n arg_bs = c(\"tesmi1\", \"ps\"),\n opt = \"bfgs\", dims = c(5, 15), ords = NA,\n analysis = F, trace = F, sp = NULL, tol = 5e-2,\n bnd = 1e-5, ...) {\n if (is.vector(x)) {\n s_k <- 1\n } else if (is.matrix(x)) {\n s_k <- ncol(x)\n } else {\n stop(\"input x type not support\")\n }\n\n # initialization\n fit <- cq.reg(x, y, arg_bs, opt, dims, ords, sp = sp, ...)\n v_coef <- coef(fit)\n # fit <- f_descent(y, x, dims - ords, ords, maxit = 0)\n # v_coef <- fit$beta\n\n # repeat Y ntaus times\n ystar <- rep(y, ntaus)\n\n # data\n v_taus <- seq(bnd, 1 - bnd, length.out = ntaus)\n v_wog <- v_taus[cut(seq_along(ystar), breaks = ntaus, labels = FALSE)]\n xnam <- c(\"tau\", paste0(\"x\", seq_len(s_k)))\n newx <- cbind(v_wog, rep(x, ntaus))\n dat <- data.frame(ystar, newx)\n colnames(dat) <- c(\"y\", xnam)\n\n # get info\n v_pred <- predict(fit, dat)\n # v_pred <- c(cq_prediction(v_taus, fit))\n v_resid <- ystar - v_pred\n\n # Schlossmacher's method\n for (iter in seq(maxit)) {\n # weights\n v_idx <- ystar <= v_pred\n v_weight <- v_wog\n v_weight[v_idx] <- 1 - v_weight[v_idx]\n v_weight <- v_weight / sqrt(v_resid^2 + 1e-8 * max(abs(v_resid))^2)\n v_weight <- v_weight / mean(v_weight)\n # fit the model\n fit <- scam(y ~ s(tau, x1, k = dims, m = ords, bs = arg_bs),\n data = dat, optimizer = opt, sp = c(sp), weights = c(v_weight),\n start = v_coef, ...\n )\n\n # get info\n v_pred <- fit$fitted.values\n v_resid <- fit$residual\n s_diff <- norm_2(v_coef - c(coef(fit))) / norm_2(v_coef)\n v_coef <- c(coef(fit))\n # plot the trace\n if (trace) {\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n sub <- paste(\"Iter:\", iter, \"diff:\", round(s_diff, 3))\n main <- paste(\"Smoothing:\", fit$sp, \"dim:\", dims)\n cq_regplot(fit, sub = sub, main = main)\n }\n # terminate\n if (s_diff <= tol) break\n }\n\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n if (analysis) {\n dev.new()\n par(mfrow = c(2, 2), mar = c(4, 4, 2, 2))\n plot(fit, se = TRUE)\n plot(fit, pers = TRUE, theta = 30, phi = 40)\n plot(ystar, fit$fitted.values,\n xlab = \"Real Data\",\n ylab = \"Fitted data\", pch = \".\", cex = 3\n )\n cq_regplot(fit, sub = sub, main = main)\n }\n fit$ntaus <- ntaus\n fit$bnd <- bnd\n fit$dat <- dat\n fit$wog <- v_wog\n fit$idx <- v_idx\n return(fit)\n}\n\n\n\n\n#' Quantile Sheets(original)\n#'\n#' Estimate conditional quantile sheet Schlossmacher's\n#' Alternating b/w weighted regression and recomputing weights\n#' @param x vector or matrix whose rows contains predictors\n#' of each observations.\n#' @param y vector of the variable we want to estimate its condtional cdf\n#' @param ords order of splien\n#' @param opt optimization methods\n#' @param maxit maximum iteration for Schlossmacherl's method\n#' @param ntaus number of taus to be considered\n#' @param analysis indicator whther plot analysis\n#' @param trace\n#' @param sp smoothing coefficients\n#' @param tol tolerance for Schlossmacher's\n#' @param ... additional arguement pass into scam (eg. gamma, weights)\n#'\n#' @import mgcv\n#'\n#' @return a gam object\n#'\n\nqs_gam <- function(x, y, maxit = 10, ntaus = 10,\n dims = c(10, 10), ords = NA,\n analysis = F, trace = F, sp = NULL, tol = 1e-3, ...) {\n if (is.vector(x)) {\n s_k <- 1\n } else if (is.matrix(x)) {\n s_k <- ncol(x)\n } else {\n stop(\"input x type not support\")\n }\n # repeat Y ntaus times\n ystar <- rep(y, ntaus)\n\n # data\n v_taus <- seq(0, 1, length.out = ntaus)\n v_wog <- v_taus[cut(seq_along(ystar), breaks = ntaus, labels = FALSE)]\n xnam <- c(\"tau\", paste0(\"x\", seq_len(s_k)))\n newx <- cbind(v_wog, rep(x, ntaus))\n dat <- data.frame(ystar, newx)\n colnames(dat) <- c(\"y\", xnam)\n\n # initialization\n fit <- mgcv::gam(y ~ te(tau, x1, k = dims, m = ords),\n data = dat, sp = c(sp), ...\n )\n v_coef <- coef(fit)\n\n # get info\n v_pred <- predict(fit, dat)\n v_resid <- ystar - v_pred\n\n # Schlossmacher's method\n for (iter in seq(maxit)) {\n # weights\n v_idx <- ystar <= v_pred\n v_weight <- v_wog\n v_weight[v_idx] <- 1 - v_weight[v_idx]\n v_weight <- v_weight / sqrt(v_resid^2 + 1e-8 * max(abs(v_resid))^2)\n v_weight <- v_weight / mean(v_weight)\n # fit the model\n fit <- mgcv::gam(y ~ te(tau, x1, k = dims, m = ords),\n data = dat, sp = c(sp), weights = c(v_weight),\n start = v_coef, ...\n )\n\n # terminate\n s_diff <- norm_2(v_coef - coef(fit)) / norm_2(v_coef)\n v_coef <- coef(fit)\n # plot the trace\n if (trace) {\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n sub <- paste(\"Iter:\", iter, \"diff:\", round(s_diff, 3))\n main <- paste(\"Smoothing:\", fit$sp, \"dim:\", dims)\n cq_regplot(fit, sub = sub, main = main)\n }\n if (s_diff <= tol) break\n # get info\n v_pred <- fit$fitted.values\n v_resid <- ystar - v_pred\n }\n\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n if (analysis) {\n dev.new()\n par(mfrow = c(2, 2), mar = c(4, 4, 2, 2))\n plot(fit, se = TRUE)\n plot(fit, pers = TRUE, theta = 30, phi = 40)\n plot(ystar, fit$fitted.values,\n xlab = \"Real Data\",\n ylab = \"Fitted data\", pch = \".\", cex = 3\n )\n cq_regplot(fit, sub = sub, main = main)\n }\n fit$ntaus <- ntaus\n fit$dat <- dat\n fit$wog <- v_wog\n fit$idx <- v_idx\n return(fit)\n}\n\n\n#' Expectile Sheets with pya's constraint\n#'\n#' Estimate conditional quantile sheet iterative evalution\n#' @param x vector or matrix whose rows contains predictors\n#' of each observations.\n#' @param y vector of the variable we want to estimate its condtional cdf\n#' @param arg_bs argument for b-spline\n#' @param dims knots number\n#' @param ords order of splien\n#' @param opt optimization methods\n#' @param maxit maximum iteration for Schlossmacherl's method\n#' @param ntaus number of taus to be considered\n#' @param analysis indicator whther plot analysis\n#' @param trace\n#' @param sp smoothing coefficients\n#' @param tol tolerance for Schlossmacher's\n#' @param ... additional arguement pass into scam (eg. gamma, weights)\n#'\n#' @import scam\n#'\n#' @return a scam object\n#'\nes_scam <- function(x, y, maxit = 10, ntaus = 10,\n arg_bs = c(\"tesmi1\", \"ps\"),\n opt = \"nlm.fd\", dims = c(5, 10), ords = NA,\n analysis = F, trace = F, sp = NULL, tol = 1e-2, ...) {\n if (is.vector(x)) {\n s_k <- 1\n } else if (is.matrix(x)) {\n s_k <- ncol(x)\n } else {\n stop(\"input x type not support\")\n }\n\n # initialization\n fit <- cq.reg(x, y, arg_bs, opt, dims, ords, sp = sp, ...)\n v_coef <- coef(fit)\n\n # repeat Y ntaus times\n ystar <- rep(y, ntaus)\n\n # data\n v_taus <- seq(0, 1, length.out = ntaus)\n v_wog <- v_taus[cut(seq_along(ystar), breaks = ntaus, labels = FALSE)]\n xnam <- c(\"tau\", paste0(\"x\", seq_len(s_k)))\n newx <- cbind(v_wog, rep(x, ntaus))\n dat <- data.frame(ystar, newx)\n colnames(dat) <- c(\"y\", xnam)\n\n # get info\n v_pred <- predict(fit, dat)\n\n # Schlossmacher's method\n for (iter in seq(maxit)) {\n # weights\n v_idx <- ystar <= v_pred\n v_weight <- v_wog\n v_weight[v_idx] <- 1 - v_weight[v_idx]\n v_weight <- v_weight / mean(v_weight)\n # fit the model\n fit <- scam(y ~ s(tau, x1, k = dims, m = ords, bs = arg_bs),\n data = dat, optimizer = opt, sp = c(sp), weights = c(v_weight),\n start = v_coef, ...\n )\n\n # terminate\n s_diff <- norm_2(v_coef - coef(fit)) / norm_2(v_coef)\n v_coef <- coef(fit)\n # plot the trace\n if (trace) {\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n sub <- paste(\"Iter:\", iter, \"diff:\", round(s_diff, 3))\n main <- paste(\"Smoothing:\", fit$sp, \"dim:\", dims)\n cq_regplot(fit, sub = sub, main = main)\n }\n if (s_diff <= tol) break\n # get info\n v_pred <- fit$fitted.values\n }\n\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n if (analysis) {\n dev.new()\n par(mfrow = c(2, 2), mar = c(4, 4, 2, 2))\n plot(fit, se = TRUE)\n plot(fit, pers = TRUE, theta = 30, phi = 40)\n plot(ystar, fit$fitted.values,\n xlab = \"Real Data\",\n ylab = \"Fitted data\", pch = \".\", cex = 3\n )\n cq_regplot(fit, sub = sub, main = main)\n }\n fit$ntaus <- ntaus\n fit$dat <- dat\n fit$wog <- v_wog\n fit$idx <- v_idx\n return(fit)\n}\n\n\n\n#' Expectile Sheets(original)\n#'\n#' Expectile sheet\n#'\n#' @param x vector or matrix whose rows contains predictors\n#' of each observations.\n#' @param y vector of the variable we want to estimate its condtional cdf\n#' @param ords order of splien\n#' @param opt optimization methods\n#' @param maxit maximum iteration for Schlossmacherl's method\n#' @param ntaus number of taus to be considered\n#' @param analysis indicator whther plot analysis\n#' @param trace\n#' @param sp smoothing coefficients\n#' @param tol tolerance for Schlossmacher's\n#' @param ... additional arguement pass into scam (eg. gamma, weights)\n#'\n#' @import mgcv\n#'\n#' @return a gam object\n#'\n\nes_gam <- function(x, y, maxit = 10, ntaus = 10,\n dims = c(10, 10), ords = NA,\n analysis = F, trace = F, sp = NULL, tol = 1e-3, ...) {\n if (is.vector(x)) {\n s_k <- 1\n } else if (is.matrix(x)) {\n s_k <- ncol(x)\n } else {\n stop(\"input x type not support\")\n }\n # repeat Y ntaus times\n ystar <- rep(y, ntaus)\n\n # data\n v_taus <- seq(0, 1, length.out = ntaus)\n v_wog <- v_taus[cut(seq_along(ystar), breaks = ntaus, labels = FALSE)]\n xnam <- c(\"tau\", paste0(\"x\", seq_len(s_k)))\n newx <- cbind(v_wog, rep(x, ntaus))\n dat <- data.frame(ystar, newx)\n colnames(dat) <- c(\"y\", xnam)\n\n # initialization\n fit <- mgcv::gam(y ~ te(tau, x1, k = dims, m = ords),\n data = dat, sp = c(sp), ...\n )\n v_coef <- coef(fit)\n\n # get info\n v_pred <- predict(fit, dat)\n\n # Schlossmacher's method\n for (iter in seq(maxit)) {\n # weights\n v_idx <- ystar <= v_pred\n v_weight <- v_wog\n v_weight[v_idx] <- 1 - v_weight[v_idx]\n v_weight <- v_weight / mean(v_weight)\n # fit the model\n fit <- mgcv::gam(y ~ te(tau, x1, k = dims, m = ords),\n data = dat, sp = c(sp), weights = c(v_weight),\n start = v_coef, ...\n )\n\n # terminate\n s_diff <- norm_2(v_coef - coef(fit)) / norm_2(v_coef)\n v_coef <- coef(fit)\n # plot the trace\n if (trace) {\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n sub <- paste(\"Iter:\", iter, \"diff:\", round(s_diff, 3))\n main <- paste(\"Smoothing:\", fit$sp, \"dim:\", dims)\n cq_regplot(fit, sub = sub, main = main)\n }\n if (s_diff <= tol) break\n # get info\n v_pred <- fit$fitted.values\n }\n\n fit$x <- x\n fit$y <- y\n fit$xnam <- xnam\n if (analysis) {\n dev.new()\n par(mfrow = c(2, 2), mar = c(4, 4, 2, 2))\n plot(fit, se = TRUE)\n plot(fit, pers = TRUE, theta = 30, phi = 40)\n plot(ystar, fit$fitted.values,\n xlab = \"Real Data\",\n ylab = \"Fitted data\", pch = \".\", cex = 3\n )\n cq_regplot(fit, sub = sub, main = main)\n }\n fit$ntaus <- ntaus\n fit$dat <- dat\n fit$wog <- v_wog\n fit$idx <- v_idx\n return(fit)\n}", "meta": {"hexsha": "a12e1291334df34d4095863ddd5f425a3ada58d6", "size": 12921, "ext": "r", "lang": "R", "max_stars_repo_path": "R/qs.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/qs.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/qs.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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.0488372093, "max_line_length": 75, "alphanum_fraction": 0.5385806052, "num_tokens": 4009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894343482288}} {"text": "# Imitating shot noise process according to:\n# x(t) = sum(k=1:inf; g(t - sum(i=1:k; xi_i))) + sum(k=1:inf; g(t + sum(i=1:k; eta_i))),\n# where g() - measured & absolutely integrated function,\n# xi_i, eta_i - i.i.d.r.v. with Exp(1) distribution\n\ng <- function(t)\n{\n # g() - measured & absolutely integrated function to make x(t)\n g_scalar <- function(t)\n {\n if(t >= 0 && t <= 0.5)\n return(1)\n else\n return(0)\n }\n return(sapply(X = t, FUN = g_scalar))\n}\n\nShotNoise <- function(t, num, inLambda = 1)\n{\n # returns value of x(t)\n \n # auxiliary random variable to build process: xi or eta\n # 2 different calls of aux_rvar provides independency\n aux_rvar <- function(n = num, lambda = inLambda)\n {\n return(rexp(n, rate = lambda))\n }\n \n # X = X1 + X2\n X1 <- sum(g(t - cumsum(aux_rvar())))\n X2 <- sum(g(t + cumsum(aux_rvar())))\n X <- X1 + X2\n return(X)\n}\n\nEvaluateTail <- function(s, imitNum, over)\n{\n # calculating P{max[X(t)]>=s} with imitation\n p <- 0\n for(i in 1:imitNum)\n {\n Sample <- sapply(over, ShotNoise, num = 100)\n M <- max(Sample)\n if(M >= s)\n p <- p + 1/imitNum\n }\n return(p)\n}\n\nlibrary(ggplot2)\nN <- 1000\n\nTimeline = seq(from = 0, to = 10, by = 0.1)\nShotNoiseValues <- sapply(Timeline, ShotNoise, num = N)\nqplot(x = Timeline,\n y = ShotNoiseValues,\n geom = \"path\",\n main = \"Shot Noise Process\",\n xlab = \"t\",\n ylab = \"x(t)\")\nprint(\"Calculated value for P{max[X(t)]>=3}:\")\nprint(EvaluateTail(3, imitNum = N, over = Timeline))", "meta": {"hexsha": "9ee3cd01a78fc9c3d657c28b63961c51fe6499cd", "size": 1508, "ext": "r", "lang": "R", "max_stars_repo_path": "lab3.r", "max_stars_repo_name": "alexgulyi/randimitation", "max_stars_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": "lab3.r", "max_issues_repo_name": "alexgulyi/randimitation", "max_issues_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": "lab3.r", "max_forks_repo_name": "alexgulyi/randimitation", "max_forks_repo_head_hexsha": "f2840fe8fec1ba7439b936c81851558864d1cba1", "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": 23.9365079365, "max_line_length": 88, "alphanum_fraction": 0.5895225464, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6930890462492518}} {"text": "# /**\n# * Calculate p-value of hypergeometric test\n# * $k : overlop number\n# * $m : set 1 size\n# * $n : set 2 size\n# * $N : background size\n# * C(m,k) * C(N-m, n-k)\n# * log(P) = log[----------------------]\n# * C(N, n)\n# * m!/(k!(m-k)!) * (N-m)!/(n-k)!(N-m-n+k)!)\n# * = log[------------------------------------------]\n# * N!/(n!(N-n)!)\n# * = logfact(m) + logfact(N-m) + logfact(n) + logfact(N-n)\n# * - logfact(k) - logfact(m-k) - logfact(n-k) - logfact(N-m-n+k) - logfact(N)\n# */\n{{rimport}}('__init__.r')\nlibrary(methods)\n\ninfile = {{i.infile | R}}\noutfile = {{o.outfile | R}}\nintype = {{args.intype | R}}\nN = {{args.N | R}}\ninopts = update.list(list(rnames=T, cnames=T), {{args.inopts | R}})\n\n\nret = matrix(nrow = 0, ncol = 5)\ncolnames(ret) = c('k', 'm', 'n', 'N', 'pval')\n\nif (intype == 'raw') {\n\trn = if (inopts$rnames) 1 else NULL\n\tdata = read.table(infile, row.names = rn, header = inopts$cnames, sep = \"\\t\", check.names = F)\n\tcnames = colnames(data)\n\tncols = ncol(data)\n\tif (is.null(N))\n\t\tN = nrow(data)\n\tif (ncols < 2)\n\t\tstop ('Need at least 2 columns.')\n\tif (!inopts$cnames) {\n\t\tcnames = paste0(\"COL\", 1:ncols)\n\t\tcolnames(data) = cnames\n\t}\n\tfor (i in 1:(ncols-1)) {\n\t\tfor (j in (i+1):ncols) {\n\t\t\trow = list(k = NA, m = NA, n = NA, N = N, pval = NA)\n\t\t\trow$m = sum(data[, i], na.rm = T)\n\t\t\trow$n = sum(data[, j], na.rm = T)\n\t\t\trow$k = nrow(data[which(data[, i] + data[, j] == 2), ])\n\t\t\trow$pval = phyper(row$k, row$m, row$N-row$m, row$n, lower.tail = F)\n\t\t\trow.names = paste(cnames[i], 'vs', cnames[j], sep = '.')\n\t\t\trow = as.data.frame(row)\n\n\t\t\trownames(row) = row.names\n\n\t\t\tret = rbind(ret, row)\n\t\t}\n\t}\n} else {\n\trn = if (inopts$rnames) 1 else NULL\n\tdata = read.table(infile, row.names = rn, header = inopts$cnames, sep = \"\\t\", check.names = F)\n\tcnames = colnames(data)\n\tncols = ncol(data)\n\tif (!inopts$cnames) {\n\t\tcnames = c('k', 'm', 'n', 'N')[1:ncols]\n\t\tcolnames(data) = cnames\n\t}\n\tif (!'N' %in% cnames && is.null(N)) {\n\t\tstop('N is not specified neither in infile nor args.N.')\n\t}\n\tif (!'k' %in% cnames || !'m' %in% cnames || !'n' %in% cnames) {\n\t\tstop('Column k, m or n is missing.')\n\t}\n\trnames = rownames(data)\n\tif (!inopts$rnames) {\n\t\trnames = paste0('ROW', 1:nrow(data))\n\t\trownames(data) = rnames\n\t}\n\tfor (rname in rnames) {\n\t\tif ('N' %in% cnames) N = data[rname, 'N']\n\t\trow = list(k = NA, m = NA, n = NA, N = N, pval = NA)\n\t\trow$m = data[rname, 'm']\n\t\trow$n = data[rname, 'n']\n\t\trow$k = data[rname, 'k']\n\t\trow$pval = phyper(row$k, row$m, row$N-row$m, row$n, lower.tail = F)\n\t\trow = as.data.frame(row)\n\n\t\trownames(row) = rname\n\t\tret = rbind(ret, row)\n\t}\n}\n\nwrite.table(\n\tpretty.numbers(ret, formats = list(pval = '%.2E')),\n\toutfile, quote = F, row.names = T, col.names = T, sep = \"\\t\"\n)\n", "meta": {"hexsha": "8d1d2a48e2d7ba6f0a430b499ec141259d336d04", "size": 2870, "ext": "r", "lang": "R", "max_stars_repo_path": "bioprocs/scripts/stats/pHypergeom.r", "max_stars_repo_name": "pwwang/biopipen", "max_stars_repo_head_hexsha": "d53b78aa192fd56a5da457463b099b2aa833b284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-10T00:17:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T09:53:09.000Z", "max_issues_repo_path": "bioprocs/scripts/stats/pHypergeom.r", "max_issues_repo_name": "pwwang/biopipen", "max_issues_repo_head_hexsha": "d53b78aa192fd56a5da457463b099b2aa833b284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-02T07:54:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-02T07:54:09.000Z", "max_forks_repo_path": "bioprocs/scripts/stats/pHypergeom.r", "max_forks_repo_name": "pwwang/biopipen", "max_forks_repo_head_hexsha": "d53b78aa192fd56a5da457463b099b2aa833b284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-10T00:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T09:56:40.000Z", "avg_line_length": 30.2105263158, "max_line_length": 97, "alphanum_fraction": 0.5101045296, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.693089037246735}} {"text": "population<-c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)\r\n# There are 45 possible samples of 2 items selected from the 10 items. \r\ncombn(population, 2)\r\nsamps<-combn(population, 2)\r\nxbars <- colMeans(samps)\r\ntable(xbars)\r\nprop.table(table(xbars))\r\n \r\n\r\n", "meta": {"hexsha": "738421adfdbcf8fc72a34beaf5925d73eb6e0b36", "size": 243, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.22/Ex4_22.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.22/Ex4_22.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.22/Ex4_22.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.3, "max_line_length": 73, "alphanum_fraction": 0.6666666667, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6929781799750728}} {"text": "labMarketOD <- function(N,sal_res,OD){\n if(OD == \"o\"){\n func = 0.5*N\n func[func% add_trace(y = labMarketOD(emp_level,input$sal_res,\"o\"), type = \"scatter\", mode = \"lines\", name = \"$$N^s(N)$$\", line = list(color = \"blue\"),\n hovertemplate = paste(\"Ns=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_trace(y = labMarketOD(emp_level,input$sal_res,\"d\"), type = \"scatter\", mode = \"lines\", name = \"$$N^d(N)$$\", line = list(color = \"red\"),\n hovertemplate = paste(\"Nd=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(0,input$W/values$p,values$eq$subN,input$W/values$p, line = list(color = 'blue', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$subN,input$W/values$p,values$eq$N,input$W/values$p, line = list(color = 'green', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$N,input$W/values$p,eqNo,input$W/values$p, line = list(color = 'grey', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$subN,0,values$eq$subN,input$W/values$p, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_trace(x = values$eq$subN, y = input$W/values$p, mode = \"markers\", marker = list(color = \"blue\"), showlegend = F,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
W/p=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$Nstar,0,values$eq$Nstar,eqNstar, line = list(color = 'rgb(200,0,0)', width = 1, dash = 'dash'), showlegend = F,\n hovertemplate = paste(\"N*=%{x:.0f}\",\"
(W/p)*=%{y:.0f}\",\"\"))\n\n if(abs(values$eq$Nstar - values$eq$N) >= 5 & abs(values$eq$subN - values$eq$N) >= 5){\n x_label = c(values$eq$Nstar,values$eq$N,values$eq$subN)\n y_label = c(eqNstar,input$W/values$p,input$W/values$p)\n text_label = c(paste0(\"N*=\",round(values$eq$Nstar),\",(W/p)*=\",round(eqNstar,1)),paste0(\"N=\",round(values$eq$N)),paste0(\"N=\",round(values$eq$subN)))\n } else if(abs(values$eq$Nstar - values$eq$N) >= 5 & abs(values$eq$subN - values$eq$N) <= 5){\n x_label = c(values$eq$Nstar,values$eq$N)\n y_label = c(eqNstar,input$W/values$p)\n text_label = c(paste0(\"N*=\",round(values$eq$Nstar),\",(W/p)*=\",round(eqNstar,1)),paste0(\"N=\",round(values$eq$N)))\n } else if(abs(values$eq$Nstar - values$eq$N) <= 5 & abs(values$eq$subN - values$eq$N) >= 5){\n x_label = c(values$eq$Nstar,values$eq$subN)\n y_label = c(eqNstar,input$W/values$p)\n text_label = c(paste0(\"N*=\",round(values$eq$Nstar),\",(W/p)*=\",round(eqNstar,1)),paste0(\"N=\",round(values$eq$subN)))\n } else{\n x_label = c(values$eq$Nstar)\n y_label = c(eqNstar)\n text_label = paste0(\"N*=\",round(values$eq$Nstar),\",(W/p)*=\",round(eqNstar,1))\n }\n eq_label = list(\n x = x_label,\n y = y_label,\n text = text_label\n )\n fig = fig %>% layout(annotations = eq_label)\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n empLevel <- list(\n title = \"Niveau d'emploi, N\",\n titlefont = f\n )\n salReels <- list(\n title = \"Salaires réels, W/p\",\n titlefont = f\n )\n fig = fig %>% layout(xaxis = empLevel, yaxis = salReels)\n}\n\nmargCost = function(N,w){\n return(w/(-N^0.6+13)+5)\n}\n\nfirmEqPlot <- function(input,output,values){\n N = seq(0,70,length.out = 1000)\n to_plot = data.frame(emp_level = N)\n\n eqRev = margCost(values$eq$N,input$W/values$p)#*values$p\n subEqRev = margCost(values$eq$subN,input$W/values$p)\n fig = plot_ly(to_plot, x = ~emp_level)\n fig = fig %>% add_trace(y = margCost(N,input$W/values$p), type = \"scatter\", mode = \"lines\", name = \"$$N^s(N)$$\", line = list(color = \"red\"),\n hovertemplate = paste(\"N=%{x:.0f}\",\"
R=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(0,eqRev,98,eqRev, line = list(color = 'blue', width = 1), showlegend = FALSE,\n hovertemplate = paste(\"N=%{x:.0f}\",\"
R=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$subN,0,values$eq$subN,subEqRev, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Nd=%{x:.0f}\",\"\")) \n fig = fig %>% add_segments(values$eq$subN, subEqRev, values$eq$subN, eqRev, line = list(color = \"green\", width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Nd=%{x:.0f}\",\"
R=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$subN, subEqRev, values$eq$N, subEqRev, line = list(color = \"green\", width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Nd=%{x:.0f}\",\"
R=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(values$eq$N, 0, values$eq$N, eqRev, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Nd=%{x:.0f}\",\"
R=%{y:.0f}\",\"\"))\n \n if(abs(values$eq$subN - values$eq$N) > 5){\n x_label = c(values$eq$N,values$eq$subN)\n y_label = c(eqRev,subEqRev)\n text_label = c(paste0(\"N=\",round(values$eq$N)),paste0(\"N=\",round(values$eq$subN)))\n } else{\n x_label = c(values$eq$N)\n y_label = c(eqRev)\n text_label = paste0(\"N=\",round(values$eq$N))\n }\n eq_label = list(\n x = x_label,\n y = y_label,\n text = text_label\n )\n fig = fig %>% layout(annotations = eq_label)\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n empLevel <- list(\n title = \"Niveau d'emploi, N\",\n titlefont = f,\n range = c(0,70)\n )\n revCosts <- list(\n title = \"Revenus et Couts\",\n titlefont = f,\n range = c(0,40)\n )\n fig = fig %>% layout(xaxis = empLevel, yaxis = revCosts)\n \n}\n", "meta": {"hexsha": "043f3ea0a2ee4eecdfc1fe4ef3654d31f4a527bc", "size": 6640, "ext": "r", "lang": "R", "max_stars_repo_path": "src/LaborMarket_functions.r", "max_stars_repo_name": "placardo/macro_monetaire", "max_stars_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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/LaborMarket_functions.r", "max_issues_repo_name": "placardo/macro_monetaire", "max_issues_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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/LaborMarket_functions.r", "max_forks_repo_name": "placardo/macro_monetaire", "max_forks_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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.552238806, "max_line_length": 166, "alphanum_fraction": 0.5686746988, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6929781682567625}} {"text": "#volume of a donut\n\nr <- 3 #minor radius of the donut\n\nR <- 6 #major radius of the donut\n\n#circumference of the donut\n\ncircum_inner <- 2*pi*R\n\n#cylindrical area of the donut\narea <- pi*(r^2)\n\n#volume = area * circumference\n\nvolume <- area * circum_inner\n\nprint(volume)\n", "meta": {"hexsha": "f66f5ad498b9209296d751f10b31196e043023fa", "size": 269, "ext": "r", "lang": "R", "max_stars_repo_path": "R/1.1/volume.r", "max_stars_repo_name": "applecool/DataScience", "max_stars_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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/1.1/volume.r", "max_issues_repo_name": "applecool/DataScience", "max_issues_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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/1.1/volume.r", "max_forks_repo_name": "applecool/DataScience", "max_forks_repo_head_hexsha": "2d166cc18ced32d9bf01620d83555d70c688a627", "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.1578947368, "max_line_length": 33, "alphanum_fraction": 0.6988847584, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6929694795539242}} {"text": "qroots <- function(a, b, c) {\n r <- sqrt(b * b - 4 * a * c + 0i)\n if (abs(b - r) > abs(b + r)) {\n z <- (-b + r) / (2 * a)\n } else {\n z <- (-b - r) / (2 * a)\n }\n c(z, c / (z * a))\n}\n\nqroots(1, 0, 2i)\n[1] -1+1i 1-1i\n\nqroots(1, -1e9, 1)\n[1] 1e+09+0i 1e-09+0i\n", "meta": {"hexsha": "56c3181305ef95be71496e3db727b5fc9383ee3b", "size": 268, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function-1.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function-1.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/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.75, "max_line_length": 35, "alphanum_fraction": 0.3768656716, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.692529874066096}} {"text": "#!/usr/bin/Rscript\n# Copyright © 2016 Martin Ueding \n# Licensed under the MIT license.\n\nbin_count = 50\nsamples_count = 100000\n\npdf = function(x) {\n sqrt(1/x - log(1 - x))\n}\n\ngm = function(x) {\n 4 / (pi * sqrt(x * (1 - x)))\n}\n\n# Plot the original function.\nx_orig = seq(0.01, 0.99, length.out=200)\ny_orig = pdf(x_orig)\nplot(x_orig, y_orig, type='l', main='Original PDF', xlab='x', ylab='y',\n col='red')\n\n# Also plot the majorizing function.\ny = gm(x_orig)\nlines(x_orig, y)\n\ninverse_cdf = function(u) {\n sin(pi * u / 2)^2\n}\n\nu = runif(samples_count)\nx = inverse_cdf(u)\n\nu2 = runif(samples_count)\nidx = u2 < pdf(x) / gm(x)\naccepted = x[idx]\n\nhist(accepted, breaks=bin_count, freq=FALSE)\n\n# The pdf above needs to be normalized, on the problem/solution set the\n# normalization is given as this particular magic number.\nlines(x_orig, y_orig / 2.32812, col='red')\n", "meta": {"hexsha": "c80022bac951ef404c6ff60bafa56717d5b0cc2a", "size": 893, "ext": "r", "lang": "R", "max_stars_repo_path": "03/R/3-accept-reject.r", "max_stars_repo_name": "martin-ueding/exercides-2016", "max_stars_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": "03/R/3-accept-reject.r", "max_issues_repo_name": "martin-ueding/exercides-2016", "max_issues_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": "03/R/3-accept-reject.r", "max_forks_repo_name": "martin-ueding/exercides-2016", "max_forks_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": 21.2619047619, "max_line_length": 71, "alphanum_fraction": 0.6651735722, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6924454140582221}} {"text": "sieve <- function(n)\n{\n n <- as.integer(n)\n if(n > 1e6) stop(\"n too large\") # restricting for larger values of n\n primes <- rep(TRUE, n) # initially all false\n primes[1] <- FALSE # trivial case\n last.prime <- 2L\n for(i in last.prime:floor(sqrt(n))) # looping through the array\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 sieve(1000000) # calling the function\n", "meta": {"hexsha": "11ab2f707263c6e521a3fad26dafb3b3061246d5", "size": 491, "ext": "r", "lang": "R", "max_stars_repo_path": "math/prime_sieve/R/Keshav_PrimeSieve.r", "max_stars_repo_name": "CarbonDDR/al-go-rithms", "max_stars_repo_head_hexsha": "8e65affbe812931b7dde0e2933eb06c0f44b4130", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1253, "max_stars_repo_stars_event_min_datetime": "2017-06-06T07:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:07:58.000Z", "max_issues_repo_path": "math/prime_sieve/R/Keshav_PrimeSieve.r", "max_issues_repo_name": "rishabh99-rc/al-go-rithms", "max_issues_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 554, "max_issues_repo_issues_event_min_datetime": "2017-09-29T18:56:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:48:13.000Z", "max_forks_repo_path": "math/prime_sieve/R/Keshav_PrimeSieve.r", "max_forks_repo_name": "rishabh99-rc/al-go-rithms", "max_forks_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2226, "max_forks_repo_forks_event_min_datetime": "2017-09-29T19:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:59:55.000Z", "avg_line_length": 28.8823529412, "max_line_length": 72, "alphanum_fraction": 0.6252545825, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6924454126373201}} {"text": ".logit <- function(x) { log(x / (1 - x)) }\n.dlogit <- function(x) { 1 / (x - x * x) }\n.logistic <- function(x) { 1 / (1 + exp(-x)) }\n.logit_scale <- function(x, a, b) { log((a - x) / (x - b)) }\n.dlogit_scale <- function(x, a, b) {(b - a) / ((a - x) * (x - b)) }\n.logistic_scale <- function(x, a, b) { ex <- exp(x); (a + b * ex) / (ex + 1) }\n\n#' Transform to an unbounded domain\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @export\nmvd.transform_to_unbounded <- function(x, bounds) {\n transformed <- matrix(NA, nrow = nrow(x), ncol = ncol(x))\n for (i in 1:ncol(x)) {\n if (bounds[i, 1] >= bounds[i, 2]) {\n stop(\"Upper bound must be strictly higher than lower bound\")\n }\n\n if (bounds[i, 1] == 0 && bounds[i, 2] == 1) {\n # [0,1] -> logit\n transformed[, i] <- .logit(x[, i])\n } else if (bounds[i, 1] == 0 && bounds[i, 2] == Inf) {\n # [0,inf] -> log\n transformed[, i] <- log(x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == 0) {\n # [0,inf] -> log\n transformed[, i] <- log(-x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == Inf) {\n # [-inf,inf] -> no transform\n transformed[, i] <- x[, i]\n } else {\n # [a,b] -> scaled logit\n transformed[, i] <- .logit_scale(x[, i], bounds[i, 1], bounds[i, 2])\n }\n }\n return(transformed)\n}\n\n#' Reverse transform from an unbounded domain\n#'\n#' description\n#' @param transformed_x Matrix or vector of transformed samples. For matrices, rows are samples and columns are variables.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @export\nmvd.transform_from_unbounded <- function(transformed_x, bounds) {\n x <- matrix(NA, nrow = nrow(x), ncol = ncol(x))\n for (i in 1:ncol(x)) {\n if (bounds[i, 1] == 0 && bounds[i, 2] == 1) {\n # [0,1] -> logit -> inverse = logistic\n x[, i] <- .logistic(transformed_x[, i])\n } else if (bounds[i, 1] == 0 && bounds[i, 2] == Inf) {\n # [0,inf] -> log -> inverse = exp\n x[, i] <- exp(transformed_x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == 0) {\n # [0,inf] -> log -> inverse = exp\n x[, i] <- -exp(transformed_x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == Inf) {\n # [-inf,inf] -> no transform\n x[, i] <- transformed_x[, i]\n } else {\n # [a,b] -> scaled logit -> inverse = scaled logistic\n x[, i] <- .logistic_scale(transformed_x[, i], bounds[i, 1], bounds[i, 2])\n }\n }\n return(x)\n}\n\n#' Probability density correction for variable transformation\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param p Probability densities to correct\n#' @param log Specifies whether p is in log scale\n#' @export\nmvd.correct_p_for_transformation <- function(x, bounds, p, log = T) {\n if (log) {\n for (i in 1:ncol(x)) {\n if (bounds[i, 1] == 0 && bounds[i, 2] == 1) {\n # [0,1] -> logit -> derivative = dlogit\n p <- p + log(.dlogit(x[, i]))\n } else if (bounds[i, 1] == 0 && bounds[i, 2] == Inf) {\n # [0,inf] -> log -> derivative = 1/log\n p <- p - log(x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == 0) {\n # [0,inf] -> log -> derivative = 1/log\n p <- p - log(x[, i])\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == Inf) {\n # [-inf,inf] -> no transform\n } else {\n # [a,b] -> scaled logit -> derivative = dlogit_scale\n p <- p + log(.dlogit_scale(x[, i], bounds[i, 1], bounds[i, 2]))\n }\n }\n } else {\n for (i in 1:ncol(x)) {\n if (bounds[i, 1] == 0 && bounds[i, 2] == 1) {\n # [0,1] -> logit -> derivative = dlogit\n p <- p * .dlogit(x[, i])\n } else if (bounds[i, 1] == 0 && bounds[i, 2] == Inf) {\n # [0,inf] ->log(x) -> 1/x\n p <- p / x[, i]\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == 0) {\n # [0,inf] ->log(x) -> 1/x\n p <- p / x[, i]\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == Inf) {\n # [-inf,inf] -> no transform\n } else {\n # [a,b] -> scaled logit -> derivative = dlogit_scale\n p <- p * .dlogit_scale(x[, i], bounds[i, 1], bounds[i, 2])\n }\n }\n }\n return(p)\n}\n\n.mvd.transform_name <- function(bounds, i) {\n if (bounds[i, 1] == 0 && bounds[i, 2] == 1) {\n return(\"logit\")\n } else if (bounds[i, 1] == 0 && bounds[i, 2] == Inf) {\n return(\"log\")\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == 0) {\n return(\"negative log\")\n } else if (bounds[i, 1] == -Inf && bounds[i, 2] == Inf) {\n return(\"no transform\")\n } else {\n return(\"scaled logit\")\n }\n}\n", "meta": {"hexsha": "a7d8ca05a826c9868bcce998134c51c3192f57e2", "size": 5331, "ext": "r", "lang": "R", "max_stars_repo_path": "R/transform.r", "max_stars_repo_name": "bramthijssen/mvdens", "max_stars_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "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/transform.r", "max_issues_repo_name": "bramthijssen/mvdens", "max_issues_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T12:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T12:45:03.000Z", "max_forks_repo_path": "R/transform.r", "max_forks_repo_name": "NKI-CCB/mvdens", "max_forks_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "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.0076923077, "max_line_length": 122, "alphanum_fraction": 0.4758957044, "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6923789216109147}} {"text": "#' MLE for the trunckated normal distribution\n#'\n#' Creating a Function that Returns the Log Likelihood, Gradient and Hessian Functions\n#'\n#' @param data numeric vector\n#' @param t truncation limits\n#' @param ... additional options\n#'\n#' @export\n#'\n\nmklhood <- function(data, t, ...) {\n\n data <- na.omit(data)\n n <- length(data)\n t <- sort(t)\n\n psi<-function(y, mu, sigma){\n exp(-(y-mu)^2/(2*sigma^2))/(sigma*sqrt(2*pi))\n }\n\n psi.mu<-function(y,mu,sigma){\n exp(-(y-mu)^2/(2*sigma^2)) * ((y-mu)/(sigma^3*sqrt(2*pi)))\n }\n\n psi.sigma<-function(y,mu,sigma){\n exp(-(y-mu)^2/(2*sigma^2)) *\n (((y-mu)^2)/(sigma^4*sqrt(2*pi)) - 1/(sigma^2*sqrt(2*pi)))\n }\n\n psi2.mu<-function(y,mu,sigma){\n exp(-(y - mu)^2/(2*sigma^2)) *\n (((y - mu)^2)/(sigma^5*sqrt(2*pi))-1/(sigma^3*sqrt(2*pi)))\n }\n\n psi2.sigma<-function(y,mu,sigma){\n exp(-(y-mu)^2/(2*sigma^2)) *\n ((2)/(sigma^3*sqrt(2*pi)) - (5*(y-mu))/(sigma^5*sqrt(2*pi)) +\n ((y-mu)^4)/(sigma^7*sqrt(2*pi)))\n }\n\n psi12.musig<-function(y,mu,sigma){\n exp(-(y-mu)^2/(2*sigma^2)) *\n (((y-mu)^3)/(sigma^6*sqrt(2*pi)) - (3*(y-mu))/(sigma^4*sqrt(2*pi)))\n }\n\n ll.tnorm2<-function(p){\n out <- (-n*log(pnorm(t[2],p[1],p[2])-pnorm(t[1],p[1],p[2]))) -\n (n*log(sqrt(2*pi*p[2]^2))) - (sum((data-p[1])^2)/(2*p[2]^2))\n -1*out\n }\n\n grad.tnorm<-function(p){\n g1 <- (-n*(integrate(psi.mu,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value) /\n (pnorm(max(t),p[1],p[2])-pnorm(min(t),p[1],p[2]))) - ((n*p[1]-sum(data))/p[2]^2)\n g2 <- (-n*(integrate(psi.sigma,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value) /\n (pnorm(max(t),p[1],p[2])-pnorm(min(t),p[1],p[2]))) - ((n)/(p[2])) + ((sum((data-p[1])^2))/(p[2]^3))\n out <- c(g1,g2)\n return(out)\n }\n\n hessian.tnorm<-function(p){\n\n h1<- -n*(integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value *\n integrate(psi2.mu,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value -\n integrate(psi.mu,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value^2) /\n (integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value^2) -\n n/(p[2]^2)\n\n h3<- -n*(integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value *\n integrate(psi12.musig,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value -\n integrate(psi.mu,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value *\n integrate(psi.sigma,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value) /\n (integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value^2) +\n (2*(n*p[1]-sum(data)))/(p[2]^3)\n\n h2<- -n*(integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value *\n integrate(psi2.sigma,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value -\n integrate(psi.sigma,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value^2) /\n (integrate(psi,t[1],t[2],mu=p[1],sigma=p[2], stop.on.error = FALSE)$value^2) +\n (n)/(p[2]^2)-(3*sum((data-p[1])^2))/(p[2]^4)\n\n H<-matrix(0,nrow=2,ncol=2)\n H[1,1]<-h1\n H[2,2]<-h2\n H[1,2]<-H[2,1]<-h3\n return(H)\n }\n\n\n return(list(ll.tnorm2 = ll.tnorm2, grad.tnorm = grad.tnorm, hessian.tnorm = hessian.tnorm))\n}\n\n#' Newton Raphson Function\n#'\n#' This takes in the Objects Returned from mklhood Function above\n#'\n#' @param lhood lhood\n#' @param p p\n#' @param tol tolerance\n#' @param maxit max iterations\n#'\n#' @export\n#'\nNewtonRaphsonLike <- function(lhood, p, tol = 1e-07, maxit = 100) {\n\n cscore <- lhood$grad.tnorm(p)\n if(sum(abs(cscore)) < tol)\n return(list(estimate = p, value = lhood$ll.tnorm2(p), iter = 0))\n cur <- p\n for(i in 1:maxit) {\n inverseHess <- solve(lhood$hessian.tnorm(cur))\n cscore <- lhood$grad.tnorm(cur)\n new <- cur - cscore %*% inverseHess\n if (new[2] <= 0) stop(\"Sigma < 0\")\n cscore <- lhood$grad.tnorm(new)\n\n if(((abs(lhood$ll.tnorm2(cur)- lhood$ll.tnorm2(new))/(lhood$ll.tnorm2(cur))) < tol))\n return(list(estimate = new, value= lhood$ll.tnorm2(new), iter = i))\n cur <- new\n }\n\n return(list(estimate = new, value= lhood$ll.tnorm2(new), iter = i))\n}\n\n#' Based on the MLE Functions (mklhood) and NewtonRaphson Function\n#'\n#' (NewtonRaphsonLike), This function estimates the MEAN and SD from the Truncated using Newton Raphson.\n#'\n#' @param missingdata matrix\n#' @param perc perc\n#' @param iter iterations in NR algorithm\n#'\n#' @export\n#'\n\nEstimatesComputation <- function(missingdata, perc, iter=50) {\n\n ## 2 column matrix where column 1 = means, column 2 = SD\n ParamEstim <- matrix(NA, nrow = nrow(missingdata), ncol = 2)\n nsamp <- ncol(missingdata)\n\n ## sample means / SDs\n ParamEstim[,1] <- rowMeans(missingdata, na.rm = TRUE)\n ParamEstim[,2] <- apply(missingdata, 1, function(x) sd(x, na.rm = TRUE))\n\n ## Case 1: missing % > perc => use sample mean / SD\n na.sum <- apply(missingdata, 1, function(x) sum(is.na(x)))\n idx1 <- which(na.sum/nsamp >= perc)\n\n ## Case 2: sample mean > 3 SD away from LOD => use sample mean / SD\n lod <- min(missingdata, na.rm=TRUE) ## why use the min of whole data set??????\n idx2 <- which(ParamEstim[,1] > 3*ParamEstim[,2] + lod)\n\n ## Case 3: for all others, use NR method to obtain truncated mean / SD estimate\n idx.nr <- setdiff(1:nrow(missingdata), c(idx1, idx2))\n ## t = limits of integration (LOD and upper)\n upplim <- max(missingdata, na.rm=TRUE) + 2*max(ParamEstim[,2])\n for (i in idx.nr) {\n Likelihood <- mklhood(missingdata[i,], t=c(lod, upplim))\n res <- tryCatch(NewtonRaphsonLike(Likelihood, p = ParamEstim[i,]),\n error = function(e) 1000)\n\n if (length(res) == 1) {\n next\n } else if (res$iter >= iter) {\n next\n } else {\n ParamEstim[i,] <- as.numeric(res$estimate)\n }\n }\n return(ParamEstim)\n}\n\n\n\n#' This Function imputes the data BASED on KNN-EUCLIDEAN\n#'\n#' @param data data set to be imputed\n#' @param k number of neighbors for imputing values\n#' @param rm.na remove NA\n#' @param rm.nan remove NaN\n#' @param rm.inf remove Inf\n#'\n#' @export\n#'\nKNNEuc <- function (data, k, rm.na = TRUE, rm.nan = TRUE, rm.inf = TRUE) {\n\n nr <- dim(data)[1]\n\n imp.knn <- data\n imp.knn[is.finite(data) == FALSE] <- NA\n t.data<-t(data)\n\n mv.ind <- which(is.na(imp.knn), arr.ind = TRUE)\n arrays <- unique(mv.ind[, 2])\n array.ind <- match(arrays, mv.ind[, 2])\n nfeatures <- 1:nr\n\n for (i in 1:length(arrays)) {\n set <- array.ind[i]:min((array.ind[(i + 1)] - 1), dim(mv.ind)[1], na.rm = TRUE)\n cand.features <- nfeatures[-unique(mv.ind[set, 1])]\n cand.vectors <- t.data[,cand.features]\n exp.num <- arrays[i]\n\n for (j in set) {\n feature.num <- mv.ind[j, 1]\n tar.vector <- data[feature.num,]\n\n dist <- sqrt(colMeans((tar.vector-cand.vectors)^2, na.rm = TRUE))\n dist[is.nan(dist) | is.na(dist)] <- Inf\n dist[dist==0] <- ifelse(is.finite(min(dist[dist>0])), min(dist[dist>0])/2, 1)\n\n if (sum(is.finite(dist)) < k) {\n stop(message = \"Fewer than K finite distances found\")\n }\n k.features.ind <- order(dist)[1:k]\n k.features <- cand.features[k.features.ind]\n wghts <- 1/dist[k.features.ind]/sum(1/dist[k.features.ind])\n imp.knn[feature.num, exp.num] <- wghts %*% data[k.features, exp.num]\n }\n }\n\n if (!rm.na) {\n imp.knn[is.na(data) == TRUE & is.nan(data) == FALSE] <- NA\n }\n if (!rm.inf) {\n index <- is.finite(data) == FALSE & is.na(data) == FALSE &\n is.nan(data) == FALSE\n imp.knn[index] <- data[index]\n }\n if (!rm.nan) {\n imp.knn[is.nan(data) == TRUE] <- NaN\n }\n return(imp.knn)\n}\n\n#' imputeKNN\n#'\n#' This Function imputes the data based on KNN-CORRELATION or\n#' KNN-TRUNCATION. The Parameter Estimates based on the Truncated\n#' Normal from EstimateComputation function is run on this function\n#'\n#' @param data data\n#' @param k k\n#' @param distance distance\n#' @param rm.na remove NA\n#' @param rm.nan remove NaN\n#' @param rm.inf remove Inf\n#' @param perc percentage\n#' @param ... additional options\n#'\n#' @export\n#'\n\nimputeKNN <- function (data, k , distance = \"correlation\",\n rm.na = TRUE, rm.nan = TRUE, rm.inf = TRUE, perc=1,...) {\n\n if (!(is.matrix(data))) {\n stop(message = paste(deparse(substitute(data)),\n \" is not a matrix.\", sep = \"\"))\n }\n\n distance <- match.arg(distance, c(\"correlation\",\"truncation\"))\n\n nr <- dim(data)[1]\n if (k < 1 | k > nr) {\n stop(message = \"k should be between 1 and the number of rows\")\n }\n\n if (distance==\"correlation\"){\n genemeans<-rowMeans(data,na.rm=TRUE)\n genesd<-apply(data, 1, function(x) sd(x, na.rm = TRUE))\n data<-(data-genemeans)/genesd\n }\n\n if (distance==\"truncation\"){\n\n\tParamMat <- EstimatesComputation(data, perc = perc)\n\n \tgenemeans<-ParamMat[,1]\n genesd<-ParamMat[,2]\n data<-(data-genemeans)/genesd\n }\n\n imp.knn <- data\n imp.knn[is.finite(data) == FALSE] <- NA\n t.data<-t(data)\n\n mv.ind <- which(is.na(imp.knn), arr.ind = TRUE)\n arrays <- unique(mv.ind[, 2])\n array.ind <- match(arrays, mv.ind[, 2])\n ngenes <- 1:nr\n\n for (i in 1:length(arrays)) {\n set <- array.ind[i]:min((array.ind[(i + 1)] - 1), dim(mv.ind)[1],\n na.rm = TRUE)\n cand.genes <- ngenes[-unique(mv.ind[set, 1])]\n cand.vectors <- t.data[,cand.genes]\n exp.num<- arrays[i]\n for (j in set) {\n\n gene.num <- mv.ind[j, 1]\n tar.vector <- data[gene.num,]\n\n r <- (cor(cand.vectors,tar.vector, use = \"pairwise.complete.obs\"))\n dist <- switch(distance,\n correlation = (1 - abs(r)),\n truncation = (1 - abs(r)))\n dist[is.nan(dist) | is.na(dist)] <- Inf\n dist[dist==0]<-ifelse(is.finite(min(dist[dist>0])), min(dist[dist>0])/2, 1)\n dist[abs(r) == 1] <- Inf\n\n if (sum(is.finite(dist)) < k) {\n stop(message = \"Fewer than K finite distances found\")\n }\n k.genes.ind <- order(dist)[1:k]\n k.genes <- cand.genes[k.genes.ind]\n\n wghts <- (1/dist[k.genes.ind]/sum(1/dist[k.genes.ind])) * sign(r[k.genes.ind])\n imp.knn[gene.num, exp.num] <- wghts %*% data[k.genes, exp.num]\n }\n }\n\n if (distance==\"correlation\") {\n imp.knn <- (imp.knn * genesd) + genemeans\n }\n\n if(distance==\"truncation\") {\n imp.knn <- (imp.knn * genesd) + genemeans\n }\n\n if (!rm.na) {\n imp.knn[is.na(data) == TRUE & is.nan(data) == FALSE] <- NA\n }\n if (!rm.inf) {\n index <- is.finite(data) == FALSE & is.na(data) == FALSE &\n is.nan(data) == FALSE\n imp.knn[index] <- data[index]\n }\n if (!rm.nan) {\n imp.knn[is.nan(data) == TRUE] <- NaN\n }\n return(imp.knn)\n}\n\n#' Root Mean Squared Error Function\n#'\n#' @param imp imputation\n#' @param mis missing\n#' @param true true data\n#' @param norm normal\n#'\n#' @export\n#'\nRmse <- function(imp, mis, true, norm = FALSE) {\n imp <- as.matrix(imp)\n mis <- as.matrix(mis)\n true <- as.matrix(true)\n missIndex <- which(is.na(mis))\n errvec <- imp[missIndex] - true[missIndex]\n rmse <- sqrt(mean(errvec^2))\n if (norm) {\n rmse <- rmse/sd(true[missIndex])\n }\n return(rmse)\n}\n\n#' Compute the Errors for the Different Imputation Methods\n#'\n#' @param trunc truncation\n#' @param corr corr\n#' @param euc euc\n#' @param miss missing\n#' @param complete complete\n#'\n#' @export\n#'\n\nErrorsComputation <- function(trunc, corr, euc, miss, complete) {\n\n ImputeErrors <- NULL\n missing <- t(miss)\n original <- t(complete)\n KnnTrunc <- Rmse(trunc, missing, original)\n KnnCorr <- Rmse(corr, missing, original)\n KnnEuc <- Rmse(euc, missing, original)\n ImputeErrors <- c(KnnTrunc, KnnCorr, KnnEuc)\n return(ImputeErrors)\n\n}\n\n\n\n", "meta": {"hexsha": "5da57618a0d6f7c48105726b0fb0f4b2739bedf1", "size": 13260, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Imput_funcs.r", "max_stars_repo_name": "fabregithub/NDim4jecs", "max_stars_repo_head_hexsha": "a66b1570d542aa6507004fdbe0567f8dc34ca211", "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": "R/Imput_funcs.r", "max_issues_repo_name": "fabregithub/NDim4jecs", "max_issues_repo_head_hexsha": "a66b1570d542aa6507004fdbe0567f8dc34ca211", "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": "R/Imput_funcs.r", "max_forks_repo_name": "fabregithub/NDim4jecs", "max_forks_repo_head_hexsha": "a66b1570d542aa6507004fdbe0567f8dc34ca211", "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": 33.5696202532, "max_line_length": 307, "alphanum_fraction": 0.5107088989, "num_tokens": 4009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.6922630940739596}} {"text": "nxt <- function(d, mu=0., sigma=1.) {\n n <- length(d$x)\n d$x <- d$x + rnorm(n,mu,sigma)\n d$y <- d$y + rnorm(n,mu,sigma)\n return(d)\n}\n\nnxt.unif <- function(d, mu=0., sigma=1.) {\n n <- length(d$x)\n limit <- sqrt(3)*sigma\n d$x <- d$x + runif(n,mu-limit,mu+limit)\n d$y <- d$y + runif(n,mu-limit,mu+limit)\n return(d)\n}\n\nplot.snap <- function(d, i, prefix, edge=10.0) {\n png(sprintf(\"%s_%5.5d.png\", prefix, i), width=760, height=760)\n plot(d$x, d$y, xlim=c(-edge/2.,edge/2.), ylim=c(-edge/2.,edge/2.), main=\"\", xlab=\"\", ylab=\"\", cex=0.2, col=\"grey\")\n dev.off()\n}\n\nplot.snap <- function(d, i, prefix, edge=10.0) {\n png(sprintf(\"%s_%5.5d.png\", prefix, i), width=760, height=760)\n plot(d$x, d$y, xlim=c(-edge/2.,edge/2.), ylim=c(-edge/2.,edge/2.), main=\"\", xlab=\"\", ylab=\"\", cex=0.2, col=\"grey\")\n dev.off()\n}\n\nsnaps <- function(n, n.iter, prefix, mu=0.0, sigma=1.0, edge=10.0) {\n std.x <- numeric(n.iter)\n std.y <- numeric(n.iter)\n d <- data.frame(x=numeric(n), y=numeric(n))\n for(i in 1:n.iter) {\n plot.snap(d, i, prefix, edge)\n d <- nxt(d, mu, sigma)\n std.x[i] <- sd(d$x)\n std.y[i] <- sd(d$y)\n print(sprintf(\"Iteration %d made\", i))\n }\n return(list(data=d,std.x=std.x,std.y=std.y))\n}\n\nsnaps.unif <- function(n, n.iter, prefix, mu=0.0, sigma=1.0, edge=10.0) {\n std.x <- numeric(n.iter)\n std.y <- numeric(n.iter)\n d <- data.frame(x=numeric(n), y=numeric(n))\n for(i in 1:n.iter) {\n plot.snap(d, i, prefix, edge)\n d <- nxt.unif(d, mu, sigma)\n std.x[i] <- sd(d$x)\n std.y[i] <- sd(d$y)\n print(sprintf(\"Iteration %d made\", i))\n }\n return(list(data=d,std.x=std.x,std.y=std.y))\n}\n\nprocess.normal <- function(n.part=3000, n.snaps=900) {\n par(mfrow=c(1,1))\n l<-snaps(n.part, n.snaps, \"normal/snap\", 0.0, 0.03, 10)\n d <- l$data\n png(file=\"normal/marginal.png\", width=760*2, height=760)\n par(mfrow=c(1,2))\n hist(d$x, main=\"\", xlab=\"x\", ylab=\"Densità\", prob=TRUE, col=\"pink\")\n lines(density(d$x),lw=2,col=\"red\")\n mu <- mean(d$x)\n s <- sd(d$x)\n x.min <- -10.0/2\n x.max <- 10.0/2\n x <- seq(from=x.min,to=x.max,by=10/100)\n lines(x, dnorm(x,mu,s), col=\"black\", lw=2)\n rug(jitter(d$x))\n hist(d$y, main=\"\", xlab=\"y\", ylab=\"Densità\", prob=TRUE, col=\"pink\")\n lines(density(d$y),lw=2,col=\"red\")\n mu <- mean(d$y)\n s <- sd(d$y)\n y.min <- -10.0/2\n y.max <- 10.0/2\n y <- seq(from=y.min,to=y.max,by=10/100)\n lines(y, dnorm(y,mu,s), col=\"black\", lw=2)\n rug(jitter(d$y))\n par(mfrow=c(1,1))\n dev.off()\n png(file=\"normal/devstd.png\", height=720, width=720)\n par(mfrow=c(2,1))\n plot((1:n.snaps)/30, l$std.x, type=\"l\", xlab=\"Tempo (s)\", ylab=\"Dev.std. asse X (m)\", col=\"red\")\n plot((1:n.snaps)/30, l$std.y, type=\"l\", xlab=\"Tempo (s)\", ylab=\"Dev.std. asse Y (m)\", col=\"red\")\n par(mfrow=c(1,1))\n dev.off()\n}\n\nprocess.unif <- function(n.part=3000, n.snaps=900) {\n par(mfrow=c(1,1))\n l<-snaps.unif(n.part, n.snaps, \"uniform/snap\", 0.0, 0.03, 10)\n d <- l$data\n png(file=\"uniform/marginal.png\", width=760*2, height=760)\n par(mfrow=c(1,2))\n hist(d$x, main=\"\", xlab=\"x\", ylab=\"Densità\", prob=TRUE, col=\"pink\")\n lines(density(d$x),lw=2,col=\"red\")\n mu <- mean(d$x)\n s <- sd(d$x)\n x.min <- -10.0/2\n x.max <- 10.0/2\n x <- seq(from=x.min,to=x.max,by=10/100)\n lines(x, dnorm(x,mu,s), col=\"black\", lw=2)\n rug(jitter(d$x))\n hist(d$y, main=\"\", xlab=\"y\", ylab=\"Densità\", prob=TRUE, col=\"pink\")\n lines(density(d$y),lw=2,col=\"red\")\n mu <- mean(d$y)\n s <- sd(d$y)\n y.min <- -10.0/2\n y.max <- 10.0/2\n y <- seq(from=y.min,to=y.max,by=10/100)\n lines(y, dnorm(y,mu,s), col=\"black\", lw=2)\n rug(jitter(d$y))\n par(mfrow=c(1,1))\n dev.off()\n png(file=\"uniform/devstd.png\", height=720, width=720)\n par(mfrow=c(2,1))\n plot((1:n.snaps)/30, l$std.x, type=\"l\", xlab=\"Tempo (s)\", ylab=\"Dev.std. asse X (m)\", col=\"red\")\n plot((1:n.snaps)/30, l$std.y, type=\"l\", xlab=\"Tempo (s)\", ylab=\"Dev.std. asse Y (m)\", col=\"red\")\n par(mfrow=c(1,1))\n dev.off()\n}\n", "meta": {"hexsha": "ccb23cf1f2ec13916452705dcbdf82f8c63d049c", "size": 3899, "ext": "r", "lang": "R", "max_stars_repo_path": "Diffusione/Normale/process.r", "max_stars_repo_name": "mafavaron/Bit-e-Natura", "max_stars_repo_head_hexsha": "dddfb64b9e4525ce1ad924bde3e8d54e25d55598", "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": "Diffusione/Normale/process.r", "max_issues_repo_name": "mafavaron/Bit-e-Natura", "max_issues_repo_head_hexsha": "dddfb64b9e4525ce1ad924bde3e8d54e25d55598", "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": "Diffusione/Normale/process.r", "max_forks_repo_name": "mafavaron/Bit-e-Natura", "max_forks_repo_head_hexsha": "dddfb64b9e4525ce1ad924bde3e8d54e25d55598", "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.6991869919, "max_line_length": 116, "alphanum_fraction": 0.5668120031, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6920132796348335}} {"text": "# take input from the user\nnum = as.integer(readline(prompt=\"Enter a number: \"))\n# initialize sum\nsum = 0\n# find the sum of the cube of each digit\ntemp = num\nwhile(temp > 0) {\ndigit = temp %% 10\nsum = sum + (digit ^ 3)\ntemp = floor(temp / 10)\n}\n# display the result\nif(num == sum) {\nprint(paste(num, \"is an Armstrong number\"))\n} else {\nprint(paste(num, \"is not an Armstrong number\"))\n}", "meta": {"hexsha": "dff5b77640a518a4e265d8de6e4320a16a0626b7", "size": 385, "ext": "r", "lang": "R", "max_stars_repo_path": "check_armstrong_number.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "check_armstrong_number.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "check_armstrong_number.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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.6470588235, "max_line_length": 53, "alphanum_fraction": 0.6623376623, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.6919039633668163}} {"text": "fisheryatesknuthshuffle <- function(n)\n{\n a <- seq_len(n)\n while(n >=2)\n {\n k <- sample.int(n, 1)\n if(k != n)\n {\n temp <- a[k]\n a[k] <- a[n]\n a[n] <- temp\n }\n n <- n - 1\n }\n a\n}\n\n#Example usage:\nfisheryatesshuffle(6) # e.g. 1 3 6 2 4 5\nx <- c(\"foo\", \"bar\", \"baz\", \"quux\")\nx[fisheryatesknuthshuffle(4)] # e.g. \"bar\" \"baz\" \"quux\" \"foo\"\n", "meta": {"hexsha": "dafbc5b68bd496cbc03ad02a4c3ac4b20a28fbf5", "size": 417, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Knuth-shuffle/R/knuth-shuffle-2.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/Knuth-shuffle/R/knuth-shuffle-2.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/Knuth-shuffle/R/knuth-shuffle-2.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": 18.9545454545, "max_line_length": 70, "alphanum_fraction": 0.4268585132, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.7931059560743421, "lm_q1q2_score": 0.6918638986231036}} {"text": "# percentile of normal distribution using r\r\n# we will use qnorm function \r\n# 75th percentile of Normal distribution Mean = 530 and SD=205\r\nmu=530\r\nsigma=205\r\nz_75percentile=0.67\r\ny=mu+sigma*z_75percentile\r\nprint(y)\r\n print(\" Thus , 25% of the tax returns in this classification exceed $667.35 in the amount owed the government.\")\r\n\r\n ", "meta": {"hexsha": "7d8c76211b9c81326041720785de27a680e10f11", "size": 342, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.19/Ex4_19.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.19/Ex4_19.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.19/Ex4_19.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 31.0909090909, "max_line_length": 115, "alphanum_fraction": 0.730994152, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6917658037640639}} {"text": "# For details of this cuts this file is demonstrating see http://arxiv.org/abs/1512.04644 \n\n# assumes theta bounds are +/- around 0, w.o.l.g.\n# this allows us to easily take the projection through reference angle of theta = 0\n\nanimation_steps = 60\n\n#theta_ub = 0.261799 # 15 degrees in radians\ntheta_ub = 0.5236 # 30 degrees in radians\nvi_ub = 1.2\nvi_lb = 0.8\n\nvj_ub = 1.2\nvj_lb = 0.8\n\nvi_sigma = vi_ub+vi_lb\nvj_sigma = vj_ub+vj_lb\n\nwi_ub = vi_ub^2\nwi_lb = vi_lb^2\n\nwj_ub = vj_ub^2\nwj_lb = vj_lb^2\n\n\nvj_val = vj_lb\nwj_val = vj_val^2\n\n\nline_width = 3\nreceding_color = rgb(0.5,0.5,0.5)\nlnc1_color = \"darkorange1\"\nlnc2_color = \"dodgerblue1\"\n\nfile_name_prefix = \"lnc\"\n\nvj_steps = seq(vj_lb, vj_ub, length.out=animation_steps)\n#vj_steps = c((vj_lb+vj_ub)/2)\nfor (i in 1:length(vj_steps)) {\n\n vj_val = vj_steps[i]\n wj_val = vj_val^2\n\n pdf(paste(\"./pdfs/\",file_name_prefix,\"_\",sprintf(\"%03d\",i),\".pdf\",sep=\"\"), pointsize=14, width=7, height=7, bg=\"white\")\n x_lims = c(vi_lb*vj_lb*cos(theta_ub), vi_ub*vj_ub)\n y_lims = c(wi_lb, wi_ub)\n #print(x_lims)\n #print(y_lims)\n\n wi_steps = seq(wi_lb, wi_ub, length.out=30)\n\n plot(x_lims, y_lims, \n main=\"Lifted Nonlinear Cuts for AC Power Flow\", \n sub=substitute(paste(w[i] %in% {}, \"(\", wil, \",\", wiu,\") \", w[j] %in% {}, \"(\", wjl, \",\", wju,\") \", theta %in% {}, \"(\", -tu, \",\", tu, \")\", sep=\"\"), list(wil = wi_lb, wiu = wi_ub, wjl = wj_lb, wju = wj_ub, tu = theta_ub) ), \n xlab=expression({w^r}[ij]), ylab=expression(w[i]), type=\"n\")\n\n # cut through theta=0\n points(sqrt(wi_steps*wj_val), wi_steps, type=\"l\", lwd=line_width)\n \n # cut through the extreme value of theta, theta_ub\n points(sqrt(wi_steps*wj_val)*cos(theta_ub), wi_steps, type=\"l\", lty=1, lwd=line_width, col=receding_color)\n\n # UB connecting line\n points(c(sqrt(wi_ub*wj_val)*cos(theta_ub), sqrt(wi_ub*wj_val)), c(wi_ub, wi_ub), type=\"l\", lty=1, lwd=line_width, col=receding_color)\n\n # LB connecting line\n points(c(sqrt(wi_lb*wj_val)*cos(theta_ub), sqrt(wi_lb*wj_val)), c(wi_lb, wi_lb), type=\"l\", lty=1, lwd=line_width, col=receding_color)\n\n # lnc 1\n # vj_ub*cos(theta_ub)*vj_sigma*w_i == vi_sigma*vj_sigma*wr_ij - vi_ub*cos(theta_ub)*vi_sigma*w_j - vi_ub*vj_ub*cos(theta_ub)*(vi_lb*vj_lb - vi_ub*vj_ub) \n lnc1_m = vi_sigma*vj_sigma/(vj_ub*cos(theta_ub)*vj_sigma)\n lnc1_b = (-vi_ub*vi_sigma*wj_val - vi_ub*vj_ub*(vi_lb*vj_lb - vi_ub*vj_ub))/(vj_ub*vj_sigma)\n abline(lnc1_b, lnc1_m, col=lnc1_color, lwd=line_width)\n \n # lnc 2\n # vj_lb*cos(theta_ub)*vj_sigma*w_i == vi_sigma*vj_sigma*wr_ij - vi_lb*cos(theta_ub)*vi_sigma*w_j - vi_lb*vj_lb*cos(theta_ub)*(vi_ub*vj_ub - vi_lb*vj_lb)\n lnc2_m = vi_sigma*vj_sigma/(vj_lb*cos(theta_ub)*vj_sigma)\n lnc2_b = (-vi_lb*vi_sigma*wj_val - vi_lb*vj_lb*(vi_ub*vj_ub - vi_lb*vj_lb))/(vj_lb*vj_sigma)\n abline(lnc2_b, lnc2_m, col=lnc2_color, lwd=line_width)\n\n # documentation\n text( x_lims[1], y_lims[2]*0.97, pos=4, substitute(paste(w[j], \" = \", wjv), list(wjv = sprintf(\"%.4f\",wj_val))) ) #, adj = c( 0, 1 ), col = \"blue\" )\n\n legend(\"bottomright\", c(\"Surface\", \"Receding\", \"LNC 1\", \"LNC 2\"), col = c(\"black\", receding_color, lnc1_color, lnc2_color),\n lwd = c(line_width, line_width, line_width),\n merge = TRUE, bg=\"white\")\n\n dev.off()\n}", "meta": {"hexsha": "a8dc44a41f42b08ec83aad4a6883b66bc950fd9c", "size": 3290, "ext": "r", "lang": "R", "max_stars_repo_path": "make.r", "max_stars_repo_name": "ccoffrin/lnc-animation", "max_stars_repo_head_hexsha": "36ccbdfbff9bd474060913afe19696f88b858a26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-10T05:16:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T05:16:21.000Z", "max_issues_repo_path": "make.r", "max_issues_repo_name": "ccoffrin/lnc-animation", "max_issues_repo_head_hexsha": "36ccbdfbff9bd474060913afe19696f88b858a26", "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": "make.r", "max_forks_repo_name": "ccoffrin/lnc-animation", "max_forks_repo_head_hexsha": "36ccbdfbff9bd474060913afe19696f88b858a26", "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.9662921348, "max_line_length": 230, "alphanum_fraction": 0.6598784195, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6917657994862535}} {"text": "############################################################\n# For macaque paper, 09.20\n# Just does some of the Chi-squared tests for gene counts.\n# Gregg Thomas\n############################################################\n\nthis.dir <- dirname(parent.frame(2)$ofile)\nsetwd(this.dir)\n\ncat(\"----------\\n\\n\")\n\n############################################################\n\ncat(\"HUMAN AND MACAQUE GENE RATIOS BY CNV TYPE\\n\\n\")\ngene_ratios = matrix(c(1212,5483,226,1132), nrow=2, dimnames=list(c(\"macaque\", \"human\"), c(\"del\",\"dup\")))\ngene_ratio_chi = chisq.test(gene_ratios)\nprint(gene_ratio_chi)\ncat(\"----------\\n\\n\")\n# \ncat(\"HUMAN AND MACAQUE 10KB UPSTREAM RATIOS BY CNV TYPE\\n\\n\")\nup_ratios = matrix(c(469,3132,147,647), nrow=2, dimnames=list(c(\"macaque\", \"human\"), c(\"del\",\"dup\")))\nup_ratio_chi = chisq.test(up_ratios)\nprint(up_ratio_chi)\ncat(\"----------\\n\\n\")\n# \ncat(\"HUMAN AND MACAQUE 10KB DOWNSTREAM RATIOS BY CNV TYPE\\n\\n\")\ndown_ratios = matrix(c(537,3174,149,693), nrow=2, dimnames=list(c(\"macaque\", \"human\"), c(\"del\",\"dup\")))\ndown_ratio_chi = chisq.test(down_ratios)\nprint(down_ratio_chi)\ncat(\"----------\\n\\n\")\n# \ncat(\"HUMAN AND MACAQUE TRANSCRIPT RATIOS BY CNV TYPE\\n\\n\")\ntranscript_ratios = matrix(c(2665,22246,476,4176), nrow=2, dimnames=list(c(\"macaque\", \"human\"), c(\"del\",\"dup\")))\ntranscript_ratio_chi = chisq.test(transcript_ratios)\nprint(transcript_ratio_chi)\ncat(\"----------\\n\\n\")\n\ncat(\"HUMAN AND MACAQUE EXON RATIOS BY CNV TYPE\\n\\n\")\nexon_ratios = matrix(c(936,7597,425,2587), nrow=2, dimnames=list(c(\"macaque\", \"human\"), c(\"del\",\"dup\")))\nexon_ratio_chi = chisq.test(exon_ratios)\nprint(exon_ratio_chi)\ncat(\"----------\\n\\n\")\n# Numbers for these test come from adding full and partial events in TABLE 1\ncat(\"----------\\n\\n\")\n\n\ncat(\"MACAQUE TOTAL CNVS BY TYPE TO CNVS OVERLAPPING EXONS BY TYPE\\n\\n\")\nmq_exon_ratio = matrix(c(432,90,3214,291), nrow=2, dimnames=list(c(\"total\", \"exon\"), c(\"dup\",\"del\")))\nmq_exon_chi = chisq.test(mq_exon_ratio)\nprint(mq_exon_chi)\ncat(\"----------\\n\\n\")\n# \ncat(\"HUMAN TOTAL CNVS BY TYPE TO CNVS OVERLAPPING EXONS BY TYPE\\n\\n\")\nhu_exon_ratio = matrix(c(1784,443,13745,2267), nrow=2, dimnames=list(c(\"total\", \"exon\"), c(\"dup\",\"del\")))\nhu_exon_chi = chisq.test(hu_exon_ratio)\nprint(hu_exon_chi)\ncat(\"----------\\n\\n\")\n# Numbers for these test come from adding full and partial events in TABLE 2 and from cnv_counts.r", "meta": {"hexsha": "2a1cee4692fff060d29500f090f95779ce8db339", "size": 2351, "ext": "r", "lang": "R", "max_stars_repo_path": "gene-counts/chi_tests.r", "max_stars_repo_name": "gwct/macaque-cnv-figs", "max_stars_repo_head_hexsha": "1767306693e27834650dede03ace4122c4ed5a45", "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": "gene-counts/chi_tests.r", "max_issues_repo_name": "gwct/macaque-cnv-figs", "max_issues_repo_head_hexsha": "1767306693e27834650dede03ace4122c4ed5a45", "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": "gene-counts/chi_tests.r", "max_forks_repo_name": "gwct/macaque-cnv-figs", "max_forks_repo_head_hexsha": "1767306693e27834650dede03ace4122c4ed5a45", "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.5344827586, "max_line_length": 112, "alphanum_fraction": 0.6341982135, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6916153500337657}} {"text": "# Intro to Computational Finance with R\r\n\r\n# Section 1 - Return Calculations\r\n\r\n# Assign the URL to the CSV file\r\ndata_url <- \"http://assets.datacamp.com/course/compfin/sbuxPrices.csv\"\r\n\r\n# Load the data frame using read.csv\r\nsbux_df <- read.csv(data_url, header=TRUE, stringsAsFactors=FALSE)\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\n\r\n# Check the structure of 'sbux_df'\r\nstr(sbux_df)\r\n\r\n# Check the first and last part of 'sbux_df'\r\nhead(sbux_df)\r\ntail(sbux_df)\r\n\r\n# Get the class of the Date column of 'sbux_df'\r\nclass(sbux_df$Date)\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\nclosing_prices <- sbux_df['Adj.Close',drop=FALSE]\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\n\r\n# Find indices associated with the dates 3/1/1994 and 3/1/1995\r\nindex_1 <- which(sbux_df$Date == '3/1/1994')\r\nindex_2 <- which(sbux_df$Date == '3/1/1995')\r\n\r\n# Extract prices between 3/1/1994 and 3/1/1995\r\nsome_prices <- sbux_df[index_1:index_2, 'Adj.Close']\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\n\r\n# Create a new data frame that contains the price data with the dates as the row names\r\nsbux_prices_df <- sbux_df[, \"Adj.Close\", drop=FALSE]\r\nrownames(sbux_prices_df) <- sbux_df$Date\r\nhead(sbux_prices_df)\r\n \r\n# With Dates as rownames, you can subset directly on the dates.\r\n# Find indices associated with the dates 3/1/1994 and 3/1/1995.\r\nprice_1 <- sbux_prices_df['3/1/1994', ];\r\nprice_2 <- sbux_prices_df['3/1/1995', ];\r\n\r\n\r\n# Now add all relevant arguments to the plot function below to get a nicer plot\r\nplot(sbux_df$Adj.Close, type='l', col='blue', lwd=2, ylab='Adjusted close', main='Monthly closing price of SBUX')\r\nlegend(x='topleft', legend='SBUX', lty=1, lwd=2, col='blue')\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\nsbux_prices_df <- sbux_df[, \"Adj.Close\", drop=FALSE]\r\n\r\n# Denote n the number of time periods\r\nn <- nrow(sbux_prices_df)\r\nsbux_ret <- (sbux_prices_df[2:n,1] - sbux_prices_df[1:(n-1),1]) / sbux_prices_df[1:(n-1),1]\r\n\r\n# Notice that sbux_ret is not a data frame object\r\nclass(sbux_ret)# The sbux_df data frame is already loaded in your work space\r\nsbux_prices_df <- sbux_df[, \"Adj.Close\", drop=FALSE]\r\n\r\n# Denote n the number of time periods:\r\nn <- nrow(sbux_prices_df)\r\nsbux_ret <- ((sbux_prices_df[2:n, 1] - sbux_prices_df[1:(n-1), 1])/sbux_prices_df[1:(n-1), 1])\r\n\r\n# Notice that sbux_ret is not a data frame object\r\nclass(sbux_ret)\r\n\r\n# Now add dates as names to the vector and print the first elements of sbux_ret to the console to check\r\nnames(sbux_ret) <- sbux_df[2:n, 1]\r\nhead(sbux_ret)\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\nsbux_prices_df <- sbux_df[, \"Adj.Close\", drop=FALSE]\r\n\r\n# Denote n the number of time periods:\r\nn <- nrow(sbux_prices_df)\r\nsbux_ret <- ((sbux_prices_df[2:n, 1] - sbux_prices_df[1:(n-1), 1])/sbux_prices_df[1:(n-1), 1])\r\n\r\n# Compute continuously compounded 1-month returns\r\nsbux_ccret <- log(sbux_prices_df[2:n, 1]) - log(sbux_prices_df[1:(n-1), 1])\r\n\r\n# Assign names to the continuously compounded 1-month returns\r\nnames(sbux_ccret) <- sbux_df[2:n,1]\r\n\r\n# Show sbux_ccret\r\nhead(sbux_ccret)\r\n\r\n\r\n# The sbux_df data frame is already loaded in your work space\r\nsbux_prices_df <- sbux_df[, \"Adj.Close\", drop=FALSE]\r\n\r\n# Denote n the number of time periods:\r\nn <- nrow(sbux_prices_df)\r\nsbux_ret <- ((sbux_prices_df[2:n, 1] - sbux_prices_df[1:(n-1), 1])/sbux_prices_df[1:(n-1), 1])\r\n\r\n# Compute continuously compounded 1-month returns\r\nsbux_ccret <- log(sbux_prices_df[2:n,1]) - log(sbux_prices_df[1:(n-1),1])\r\nnames(sbux_ccret) <- sbux_df[2:n,1]\r\nhead(sbux_ccret)\r\n\r\n# Compare the simple and cc returns\r\nhead(cbind(sbux_ret, sbux_ccret))\r\n\r\n\r\n# The simple returns (sbux_ret) and the continuously compounded returns (sbux_ccret) have been preloaded in your workspace\r\n\r\n# Plot the returns on the same graph\r\nplot(sbux_ret, type=\"l\", col=\"blue\", lwd=2, ylab=\"Return\",\r\n main=\"Monthly Returns on SBUX\")\r\n\r\n# Add horizontal line at zero\r\nabline(h=0)\r\n\r\n# Add a legend\r\nlegend(x=\"bottomright\", legend=c(\"Simple\", \"CC\"), \r\n lty=1, lwd=2, col=c(\"blue\",\"red\"))\r\n\r\n# Add the continuously compounded returns\r\nlines(sbux_ccret, col='red', lwd=2)\r\n\r\n\r\n# The simple returns (sbux_ret) and the continuously compounded returns (sbux_ccret) have been preloaded in your workspace\r\n\r\n# Compute gross returns\r\nsbux_gret <- sbux_ret + 1\r\n\r\n# Compute future values\r\nsbux_fv <- cumprod(sbux_gret)\r\n\r\n# Plot the evolution of the $1 invested in SBUX as a function of time\r\nplot(sbux_fv, type=\"l\", col=\"blue\", lwd=2, ylab=\"Dollars\", \r\n main=\"FV of $1 invested in SBUX\")\r\n\r\n\r\n\r\n# Section 2 Random Variables and Probabilities\r\n\r\n# X ~ N(0.05, (0.10)^2)\r\nmu_x <- 0.05\r\nsigma_x <- 0.10\r\n\r\n# Pr(X > 0.10)\r\n1 - pnorm(0.10, mean = mu_x, sd = sigma_x)\r\n\r\n# Pr(X < -0.10)\r\npnorm(-0.10, mean = mu_x, sd = sigma_x)\r\n\r\n# Pr(-0.05 < X < 0.15)\r\n1 - pnorm(-0.05, mean = mu_x, sd = sigma_x) - pnorm(0.15, mean = mu_x, sd = sigma_x, lower.tail=FALSE)\r\n\r\n\r\n# The mean (mu_x) and the standard deviation (sigma_x) are still in your workspace\r\n\r\n# 1%, 5%, 95% and 99% quantile\r\nqnorm(c(0.01, 0.05, 0.95, 0.99), mean = mu_x, sd = sigma_x)\r\n\r\n\r\n# Normally distributed monthly returns\r\nx_vals <- seq(-0.25, 0.35, length.out = 100)\r\nMSFT <- dnorm(x_vals, mean = 0.05, sd = 0.1)\r\nSBUX <- dnorm(x_vals, mean=0.025, sd=0.05)\r\n\r\n\r\n# MSFT and x_vals are still in your workspace\r\n\r\n# Normal curve for MSFT\r\nplot(x_vals, MSFT, type='l', col='blue', ylab='Normal curves', ylim=c(0,8))\r\n\r\n\r\n# MSFT, SBUX and x_vals are still in your workspace\r\n\r\n# Normal curve for MSFT\r\nplot(x_vals, MSFT, type = \"l\", col = \"blue\", ylab = \"Normal curves\", \r\n ylim = c(0, 8))\r\n\r\n# Add a normal curve for SBUX\r\nlines(x_vals, SBUX, col='red')\r\n\r\n# Add a plot legend\r\nlegend(\"topleft\", legend = c(\"Microsoft\", \"Starbucks\"), \r\n col = c(\"blue\", \"red\"), lty = 1)\r\n\r\n\r\n# R ~ N(0.04, (0.09)^2) \r\nmu_R <- 0.04\r\nsigma_R <- 0.09\r\n\r\n# Initial wealth W0 equals $100,000\r\nW0 <- 100000\r\n\r\n# The 1% value-at-risk\r\n(1 + qnorm(0.01, mean = mu_R, sd = sigma_R)) * W0 - W0\r\n\r\n# The 5% value-at-risk\r\n(1 + qnorm(0.05, mean = mu_R, sd = sigma_R)) * W0 - W0\r\n\r\n\r\n# r ~ N(0.04, (0.09)^2) \r\nmu_r <- 0.04\r\nsigma_r <- 0.09\r\n\r\n# Initial wealth W0 equals $100,000\r\nW0 <- 100000\r\n\r\n# The 1% value-at-risk\r\n(1 + (exp(qnorm(0.01, mean = mu_r, sd = sigma_r)) - 1)) * W0 - W0\r\n\r\n# The 5% value-at-risk\r\n(1 + (exp(qnorm(0.05, mean = mu_r, sd = sigma_r)) - 1)) * W0 - W0\r\n\r\n\r\n# Vectors of prices\r\nPA <- c(38.23, 41.29)\r\nPC <- c(41.11, 41.74)\r\n\r\n# Simple monthly returns\r\nRA <- (PA[2] - PA[1]) / PA[1]\r\nRC <- (PC[2] - PC[1]) / PC[1]\r\n\r\n\r\n# The simple returns on Amazon (RA) and Costco (RC) are still in your workspace\r\n\r\n# Continuously compounded returns\r\nrA <- log(PA[2]) - log(PA[1])\r\nrC <- log(PC[2]) - log(PC[1])\r\n\r\n\r\n# The prices for Amazon (PA) are still in your workspace\r\n\r\n# Cash dividend per share\r\nDA <- 0.1\r\n\r\n# Simple total return\r\nRA_total <- ((PA[2] + DA) - PA[1])/PA[1]\r\n\r\n# Dividend yield\r\nDY <- DA / PA[1]\r\n\r\n\r\n# The simple monthly return on Amazon (RA) is still in your workspace\r\n\r\n# Simple annual return\r\nRA_annual <- ((1 + RA)^12) - 1\r\n\r\n# Continuously compounded annual return\r\nrA_annual <- log(1 + RA_annual)\r\n\r\n\r\n# The simple returns on Amazon (RA) and Costco (RC) are still in your workspace\r\n\r\n# Portfolio shares\r\nxA <- 8000/10000\r\nxC <- 2000/10000\r\n\r\n# Simple monthly return\r\nxA * RA + xC * RC\r\n\r\n\r\n# Section 3 Bivariate Distributions\r\n\r\n\r\n# Standard deviations and correlation\r\nsig_x <- 0.10\r\nsig_y <- 0.05\r\nrho_xy <- 0.9\r\n\r\n# Covariance between X and Y\r\nsig_xy <- rho_xy * sig_x * sig_y\r\n\r\n# Covariance matrix\r\nSigma_xy <- matrix(c(sig_x^2, sig_xy, sig_xy, sig_y^2), nrow=2, ncol=2, byrow=TRUE)\r\n\r\n\r\n# Load the mvtnorm package\r\nlibrary(\"mvtnorm\")\r\n\r\n# The covariance matrix (Sigma_xy) is still in your workspace\r\n\r\n# Means\r\nmu_x <- 0.05\r\nmu_y <- 0.025\r\n\r\n# Simulate 100 observations\r\nset.seed(123) # for reproducibility\r\nxy_vals <- rmvnorm(100, mean = c(mu_x, mu_y), sigma=Sigma_xy)\r\n \r\n# Have a look at the first observations\r\nhead(xy_vals)\r\n\r\n\r\n# The simulated values (xy_vals) are still in your workspace\r\n\r\n# Create scatterplot\r\nplot(xy_vals, pch=16, cex=2, col='blue', main='Bivariate normal: rho=0.9', xlab='x', ylab='y')\r\n\r\n\r\n# Simulated values (xy_vals) and means (mu_x, mu_y) are still in your workspace\r\n\r\n# create scatterplot\r\nplot(xy_vals[, 1], xy_vals[, 2], pch = 16, cex = 2, col = \"blue\", \r\n main = \"Bivariate normal: rho=0.9\", xlab = \"x\", ylab = \"y\")\r\n\r\n# Add lines\r\nabline(v=mu_x, h=mu_y)\r\n\r\n\r\n# Means (mu_x, mu_y) and covariance matrix (Sigma_xy) are still in your workspace\r\n\r\n# create scatterplot\r\nplot(xy_vals[, 1], xy_vals[, 2], pch = 16, cex = 2, col = \"blue\", \r\n main = \"Bivariate normal: rho=0.9\", xlab = \"x\", ylab = \"y\")\r\n\r\n# Add lines\r\nabline(h = mu_y, v = mu_x)\r\n\r\n# Add line segments\r\nsegments(x0 = 0, y0 = -1e10, x1 = 0, y1 = 0, col=\"red\")\r\nsegments(x0 = -1e10, y0 = 0, x1 = 0, y1 = 0, col=\"red\")\r\n\r\n# Compute joint probability\r\npmvnorm(lower = c(-Inf, -Inf), upper = c(0, 0), mean = c(mu_x, mu_y), sigma = Sigma_xy)\r\n\r\n\r\n# Standard deviations and correlation\r\nsig_x <- 0.10\r\nsig_y <- 0.05\r\nrho_xy <- -0.9\r\n# Covariance between X and Y\r\nsig_xy <- rho_xy * sig_x * sig_y\r\n# Covariance matrix\r\nSigma_xy <- matrix(c(sig_x^2, sig_xy, sig_xy, sig_y^2), nrow = 2, ncol = 2)\r\n\r\n# Means\r\nmu_x <- 0.05\r\nmu_y <- 0.025\r\n# Simulate 100 observations\r\nset.seed(123) # for reproducibility\r\nxy_vals <- rmvnorm(100, mean=c(mu_x, mu_y), sigma = Sigma_xy)\r\nhead(xy_vals)\r\n\r\n# Create scatterplot\r\nplot(xy_vals[, 1], xy_vals[, 2], pch = 16, cex = 2, col = \"blue\", \r\n main = \"Bivariate normal: rho=-0.9\", xlab = \"x\", ylab = \"y\")\r\n# Add lines\r\nabline(h = mu_y, v = mu_x)\r\n# Add line segments\r\nsegments(x0 = 0, y0 = -1e10, x1 = 0, y1 = 0, col=\"red\")\r\nsegments(x0 = -1e10, y0 = 0, x1 = 0, y1 = 0, col=\"red\")\r\n\r\n# Compute joint probability\r\npmvnorm(lower = c(-Inf, -Inf), upper = c(0, 0), \r\n mean = c(mu_x, mu_y), sigma = Sigma_xy)\r\n\r\n\r\n# Standard deviations and correlation\r\nsig_x <- 0.10\r\nsig_y <- 0.05\r\nrho_xy <- 0\r\n# Covariance between X and Y\r\nsig_xy <- rho_xy * sig_x * sig_y\r\n# Covariance matrix\r\nSigma_xy <- matrix(c(sig_x^2, sig_xy, sig_xy, sig_y^2), nrow = 2, ncol = 2)\r\n\r\n# Means\r\nmu_x <- 0.05\r\nmu_y <- 0.025\r\n# Simulate 100 observations\r\nset.seed(123) # for reproducibility\r\nxy_vals <- rmvnorm(100, mean=c(mu_x, mu_y), sigma = Sigma_xy)\r\nhead(xy_vals)\r\n\r\n# Create scatterplot\r\nplot(xy_vals[, 1], xy_vals[, 2], pch = 16, cex = 2, col = \"blue\", \r\n main = \"Bivariate normal: rho=0\", xlab = \"x\", ylab = \"y\")\r\n# Add lines\r\nabline(h = mu_y, v = mu_x)\r\n# Add line segments\r\nsegments(x0 = 0, y0 = -1e10, x1 = 0, y1 = 0, col=\"red\")\r\nsegments(x0 = -1e10, y0 = 0, x1 = 0, y1 = 0, col=\"red\")\r\n\r\n# Compute joint probability\r\npmvnorm(lower = c(-Inf, -Inf), upper = c(0, 0), \r\n mean = c(mu_x, mu_y), sigma = Sigma_xy)\r\n\r\n\r\n# Section 4 Simulating Time Series Data\r\n\r\nset.seed(123);\r\n# Simulate 250 observations from the described MA(1) model\r\nma1_sim <- 0.05 + arima.sim(model=list(ma=0.5), n=250, mean=0, sd=0.1)\r\n\r\n\r\nset.seed(123);\r\n# Simulate 250 observations from the described MA(1) model\r\nma1_sim <- arima.sim(model=list(ma=0.5), n=250, mean=0, sd=0.1) + 0.05;\r\n\r\n# A line plot of the simulated observations\r\nplot(ma1_sim, type='l', xlab='time', ylab='y(t)', main='MA(1) Process: mu=0.05, theta=0.5')\r\nabline(h=0)\r\n\r\n\r\nset.seed(123);\r\n# Simulate 250 observations from the described MA(1) model\r\nma1_sim <- arima.sim(model=list(ma=0.5), n=250, mean=0, sd=0.1) + 0.05;\r\n# Generate the theoretical ACF with upto lag 10\r\nacf_ma1_model <- ARMAacf(ma=0.5, lag.max=10)\r\n\r\n# Split plotting window in three rows\r\npar(mfrow=c(3,1))\r\n\r\n# First plot: The simulated observations\r\nplot(ma1_sim, type=\"l\",main=\"MA(1) Process: mu=0.05, theta=0.5\",xlab=\"time\",ylab=\"y(t)\")\r\nabline(h=0)\r\n\r\n# Second plot: Theoretical ACF\r\nplot(1:10, acf_ma1_model[2:11], type=\"h\", col=\"blue\", ylab=\"ACF\", main=\"theoretical ACF\")\r\n\r\n# Third plot: Sample ACF\r\n# Assign to tmp the Sample ACF\r\ntmp <- acf(ma1_sim, lag.max=10, main='Sample ACF')\r\n\r\n# Reset graphical window to only one graph\r\npar(mfrow=c(1,1))\r\n\r\nset.seed(123);\r\n# Simulate 250 observations from the described MA(1) model\r\nma1_sim <- arima.sim(model=list(ma=0.9), n=250, mean=0, sd=0.1) + 0.05;\r\n# Generate the theoretical ACF with upto lag 10\r\nacf_ma1_model <- ARMAacf(ma=0.9, lag.max=10)\r\n\r\n# Split plotting window in three rows\r\npar(mfrow=c(3,1))\r\n\r\n# First plot: The simulated observations\r\nplot(ma1_sim, type=\"l\",main=\"MA(1) Process: mu=0.05, theta=0.9\",xlab=\"time\",ylab=\"y(t)\")\r\nabline(h=0)\r\n\r\n# Second plot: Theoretical ACF\r\nplot(1:10, acf_ma1_model[2:11], type=\"h\", col=\"blue\", main=\"theoretical ACF\")\r\n\r\n# Third plot: Sample ACF\r\ntmp=acf(ma1_sim, lag.max=10, main=\"Sample ACF\")\r\n\r\n# Reset graphical window to only one graph\r\npar(mfrow=c(1,1))\r\n\r\n\r\nset.seed(123);\r\n# Simulate 250 observations from the described AR(1) model\r\nar1_sim <- arima.sim(model=list(ar=0.5), n=250, mean=0, sd=0.1) + 0.05\r\n# Generate the theoretical ACF with ten lags\r\nacf_ar1_model <- ARMAacf(ar=0.5, lag.max=10)\r\n\r\n# Split plotting window in three rows\r\npar(mfrow=c(3,1))\r\n\r\n# Generate the same three graphs as in the previous exercise \r\npar(mfrow=c(3,1))\r\n\r\n# First plot: The simulated observations\r\nplot(ar1_sim, type=\"l\", main=\"AR(1) Process: mu=0.05, phi=0.5\",xlab=\"time\",ylab=\"y(t)\")\r\nabline(h=0)\r\n\r\n# Second plot: Theoretical AFC\r\nplot(1:10, acf_ar1_model[2:11], type=\"h\", col=\"blue\", main=\"theoretical ACF\")\r\n\r\n# Third plot: Sample AFC\r\ntmp <- acf(ar1_sim, lag.max=10., main='Sample ACF')\r\n\r\n# Reset plotting window to default\r\npar(mfrow=c(1,1));\r\n\r\n\r\n# Section 5 - Analyzing Stock Returns\r\n\r\n# Load relevant packages\r\nlibrary(PerformanceAnalytics);library(zoo);library(tseries);\r\n\r\n# Get the monthly adjusted closing price data on VBLTX, FMAGX and SBUX from Yahoo! using the tseries function get.hist.quote(). Set the sample to Jan 1998 through Dec 2009.\r\n\r\n# Get the adjusted closing prices from Yahoo!\r\nVBLTX_prices <- get.hist.quote(instrument=\"vbltx\", start=\"1998-01-01\",end=\"2009-12-31\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet=TRUE)\r\n \r\nFMAGX_prices <- get.hist.quote(instrument=\"fmagx\", start=\"1998-01-01\",end=\"2009-12-31\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet=TRUE)\r\n\r\nSBUX_prices <- get.hist.quote(instrument=\"sbux\", start=\"1998-01-01\",end=\"2009-12-31\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet=TRUE)\r\n\r\n# Change the class of the time index to yearmon which is appropriate for monthly data\r\n# index() and as.yearmon() are functions in the zoo package \r\n\r\nindex(VBLTX_prices) <- as.yearmon(index(VBLTX_prices))\r\nindex(FMAGX_prices) <- as.yearmon(index(FMAGX_prices))\r\nindex(SBUX_prices) <- as.yearmon(index(SBUX_prices))\r\n\r\n# Inspect your data\r\nstart(VBLTX_prices)\r\nend(VBLTX_prices)\r\n\r\n\r\n# The variables VBLTX_prices, FMAGX_prices and SBUX_prices are preloaded in your workspace\r\n\r\n# Create merged price data\r\nall_prices = merge(VBLTX_prices, FMAGX_prices, SBUX_prices)\r\n# Rename columns\r\ncolnames(all_prices) <- c(\"VBLTX\", \"FMAGX\", \"SBUX\")\r\n\r\n# Calculate cc returns as difference in log prices\r\nall_returns = diff(log(all_prices))\r\n\r\n# Look at the return data\r\nstart(all_returns)\r\nend(all_returns)\r\ncolnames(all_returns) \r\nhead(all_returns)\r\n\r\n\r\n# 'all_returns' is preloaded in your workspace.\r\n\r\n# Plot returns after using the PerformanceAnalytics function chart.TimeSeries().\r\n# This function creates a slightly nicer looking plot than plot.zoo()\r\nchart.TimeSeries(all_returns, legend.loc=\"bottom\", main=\" \") \r\n\r\n# The previous charts are a bit hard to read. The PerformanceAnalytics function\r\n# chart.Bar makes it easier to compare the returns of different assets on the \r\n# same plot\r\nchart.Bar(all_returns, legend.loc=\"bottom\", main=\" \")\r\n\r\n\r\n# Cumulative return plot - must use simple returns (!) and not cc returns for this\r\n# Use PerformanceAnalytics function chart.CumReturns()\r\nsimple_returns <- diff(all_prices)/lag(all_prices, k=-1);\r\nchart.CumReturns(simple_returns, wealth.index=TRUE, legend.loc='topleft', main='Future Value of $1 invested')\r\n\r\n\r\n# Create matrix with returns\r\nreturn_matrix <- coredata(all_returns);\r\n\r\n# Generate four panel plots\r\npar(mfrow=c(2,2))\r\nhist(return_matrix[,\"VBLTX\"],main=\"VBLTX monthly returns\",\r\n xlab=\"VBLTX\", probability=T, col=\"slateblue1\")\r\nboxplot(return_matrix[,\"VBLTX\"],outchar=T, main=\"Boxplot\", col=\"slateblue1\")\r\nplot(density(return_matrix[,\"VBLTX\"]),type=\"l\", main=\"Smoothed density\",\r\n xlab=\"monthly return\", ylab=\"density estimate\", col=\"slateblue1\")\r\nqqnorm(return_matrix[,\"VBLTX\"], col=\"slateblue1\")\r\nqqline(return_matrix[,\"VBLTX\"])\r\npar(mfrow=c(1,1))\r\n\r\n\r\n# Create matrix with returns\r\nreturn_matrix <- coredata(all_returns);\r\n\r\n# Show boxplot of three series on one plot\r\nboxplot(return_matrix[,\"VBLTX\"], return_matrix[,\"FMAGX\"], return_matrix[,\"SBUX\"],\r\n names=colnames(return_matrix), col=\"slateblue1\")\r\n\r\n# Do the same thing using the PerformanceAnalytics function chart.Boxplot\r\nchart.Boxplot(all_returns)\r\n\r\n\r\n# Note: all_returns is preloaded in your workspace\r\n\r\n# Create matrix with returns\r\nreturn_matrix <- coredata(all_returns);\r\n\r\nsummary(return_matrix)\r\n\r\n# Compute descriptive statistics by column using the base R function apply()\r\nargs(apply)\r\napply(return_matrix, 2, mean)\r\napply(return_matrix, 2, var)\r\napply(return_matrix, 2, sd)\r\n\r\napply(return_matrix, 2, skewness)\r\napply(return_matrix, 2, kurtosis)\r\n# A nice PerformanceAnalytics function that computes all of the relevant descriptive statistics is table.Stats\r\ntable.Stats(all_returns)\r\n\r\n\r\n# Note: return_matrix is preloaded in your workspace\r\n\r\n# Annualized continuously compounded mean \r\n12 * apply(return_matrix, 2, mean)\r\n# Annualized simple mean\r\nexp(12*apply(return_matrix, 2, mean)) - 1;\r\n\r\n# Annualized standard deviation values\r\n12^0.5 * apply(return_matrix, 2, sd)\r\n\r\n\r\n# Note: return_matrix is preloaded in your workspace\r\n\r\n# Display all possible pair-wise scatter plots\r\npairs(return_matrix, pch=16, col='slateblue1')\r\n\r\n# Compute 3 x 3 covariance and correlation matrices\r\nvar(return_matrix)\r\ncor(return_matrix)\r\n\r\n\r\n# Section 6 Constant expected return model\r\n\r\nVBLTX_prices <- get.hist.quote(instrument=\"vbltx\", start=\"2005-09-01\", end=\"2010-09-30\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet = TRUE)\r\nFMAGX_prices <- get.hist.quote(instrument=\"fmagx\", start=\"2005-09-01\", end=\"2010-09-30\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet = TRUE)\r\nSBUX_prices <- get.hist.quote(instrument=\"sbux\", start=\"2005-09-01\",end=\"2010-09-30\", quote=\"AdjClose\",provider=\"yahoo\", origin=\"1970-01-01\",compression=\"m\", retclass=\"zoo\", quiet = TRUE)\r\n\r\n# Change the class of the time index to yearmon, which is appropriate for monthly data.\r\n# index() and as.yearmon() are functions in the zoo package \r\nindex(VBLTX_prices) <- as.yearmon(index(VBLTX_prices))\r\nindex(FMAGX_prices) <- as.yearmon(index(FMAGX_prices))\r\nindex(SBUX_prices) <- as.yearmon(index(SBUX_prices))\r\n\r\n# Create merged price data\r\nall_prices <- merge(VBLTX_prices, FMAGX_prices, SBUX_prices)\r\n# Rename columns\r\ncolnames(all_prices) <- c(\"VBLTX\", \"FMAGX\", \"SBUX\")\r\n\r\n# Calculate cc returns as difference in log prices\r\nall_returns <- diff(log(all_prices))\r\n\r\n# Create matrix with returns\r\nreturn_matrix <- coredata(all_returns)\r\n\r\n\r\n# The variable return_matrix is preloaded in your workspace\r\n\r\n# Number of observations\r\nn_obs <- nrow(return_matrix)\r\n\r\n# Estimates of sigma2hat\r\nsigma2hat_vals <- apply(return_matrix, 2, var)\r\n\r\n# Standard Error of sigma2hat\r\nse_sigma2hat <- sigma2hat_vals / sqrt(n_obs/2)\r\n\r\nse_sigma2hat\r\n\r\n\r\n# Calculate the correlation matrix\r\ncor_matrix <- cor_matrix(return_matrix)\r\n\r\n# Get the lower triangular part of that 'cor_matrix'\r\nrhohat_vals <- c(cor_matrix[4],cor_matrix[7],cor_matrix[8])\r\n\r\n# Set the names\r\nnames(rhohat_vals) <- c(\"VBLTX,FMAGX\",\"VBLTX,SBUX\",\"FMAGX,SBUX\")\r\n\r\n# Compute the estimated standard errors for correlation\r\nse_rhohat <- (1 - rhohat_vals^2) / sqrt(nrow(return_matrix))\r\n\r\nse_rhohat\r\n\r\n\r\n# The \"all_returns\" zoo object is preloaded in your workspace\r\nt.test(all_returns[,1])\r\n\r\n\r\n# The \"all_returns\" zoo object is preloaded in your workspace\r\n\r\n# Test the correlation between VBLTX,FMAGX\r\ncor.test(all_returns[,1],all_returns[,2])\r\n\r\n\r\n# The \"all_returns\" zoo object is preloaded in your workspace\r\n\r\n# Test the normality of the returns of VBLTX\r\njarque.bera.test(all_returns[,1])\r\n\r\n\r\nlibrary(\"boot\")\r\n# Function for bootstrapping sample mean: \r\nmean_boot <- function(x, idx) {\r\n ans <- mean(x[idx])\r\n ans \r\n} \r\n# Construct VBLTX_mean_boot:\r\nVBLTX_mean_boot <- boot(return_matrix[, 'VBLTX'], statistic = mean_boot, 999)\r\n\r\n# Print the class of VBLTX_mean_boot\r\nclass(VBLTX_mean_boot)\r\n\r\n# Print VBLTX_mean_boot\r\nVBLTX_mean_boot\r\n\r\n# Plot bootstrap distribution and qq-plot against normal\r\nplot(VBLTX_mean_boot)\r\n\r\n\r\n# Section 7 - Intro to Portfolio Theory\r\n\r\n\r\n# Load relevant packages\r\nlibrary(\"PerformanceAnalytics\")\r\nlibrary(\"zoo\")\r\n\r\n# Load the data\r\nds_url <- \"http://s3.amazonaws.com/assets.datacamp.com/course/compfin/lab8.RData\"\r\nload(url(ds_url))\r\n# Explore the data set\r\nhead(returns_df)\r\ntail(returns_df)\r\n\r\n\r\n# The returns_df data is preloaded in your workspace\r\n\r\n# Estimate the parameters: multivariate\r\nmu_hat_annual <- apply(returns_df,2,mean)*12 \r\nsigma2_annual <- apply(returns_df, 2, var)*12\r\nsigma_annual <- sqrt(sigma2_annual)\r\ncov_mat_annual <- cov(returns_df)*12 \r\ncov_hat_annual <- cov(returns_df)[1,2]*12 \r\nrho_hat_annual <- cor(returns_df)[1,2]\r\n\r\n# The annual estimates of the CER model parameters for Boeing and Microsoft\r\nmu_boeing <- mu_hat_annual[\"rboeing\"]\r\nmu_msft <- mu_hat_annual[\"rmsft\"]\r\nsigma2_boeing <- sigma2_annual[\"rboeing\"]\r\nsigma2_msft <- sigma2_annual[\"rmsft\"]\r\nsigma_boeing <- sigma_annual[\"rboeing\"]\r\nsigma_msft <- sigma_annual[\"rmsft\"]\r\nsigma_boeing_msft <- cov_hat_annual\r\nrho_boeing_msft <- rho_hat_annual\r\n \r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# The ratio Boeing stock vs Microsoft stock (adds up to 1)\r\nboeing_weights <- seq(from=-1, to=2, by=0.1)\r\nmsft_weights <- seq(from=2, to=-1, by=-0.1)\r\n\r\n# Portfolio parameters\r\nmu_portfolio <- mu_boeing * boeing_weights + mu_msft * msft_weights\r\n\r\nsigma2_portfolio <- boeing_weights^2 * sigma2_boeing + msft_weights^2 * sigma2_msft + 2*boeing_weights*msft_weights*sigma_boeing_msft \r\n\r\nsigma_portfolio <- sqrt(sigma2_portfolio)\r\n\r\n# Plotting the different portfolios\r\nplot(sigma_portfolio, mu_portfolio, type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"Microsoft\", pos=4)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# Annual risk-free rate of 3% per year for the T-bill\r\nt_bill_rate <- 0.03\r\n\r\n# Ratio Boeing stocks\r\nboeing_weights <- seq(from=-1, to=2, by=0.1)\r\nt_bill_weights <- (1 - boeing_weights)\r\n# Portfolio parameters\r\nmu_portfolio_boeing_bill <- boeing_weights * mu_boeing + t_bill_weights * t_bill_rate\r\n\r\nsigma_portfolio_boeing_bill <- boeing_weights * sigma_boeing\r\n\r\n# Plot previous exercise\r\nplot(sigma_portfolio, mu_portfolio, type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"MSFT\", pos=4)\r\n\r\n# Portfolio Combination Boeing and T-bills\r\npoints(sigma_portfolio_boeing_bill, mu_portfolio_boeing_bill, col='blue', type='b')\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# Sharp ratio Boeing\r\nsharp_ratio_boeing <- (mu_boeing - t_bill_rate) / sigma_boeing\r\n\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# The global minimum variance portfolio\r\nglobal_min_var_portfolio <- globalMin.portfolio(mu_hat_annual, cov_mat_annual)\r\n\r\nglobal_min_var_portfolio\r\n\r\n# Summary of global_min_var_portfolio that takes into account the annual risk-free rate of 3% per year\r\nsummary(global_min_var_portfolio, risk.free=0.03)\r\n\r\n# Portfolio weights Boeing and Microsoft\r\nplot(global_min_var_portfolio)\r\n\r\n# Plot previous exercises\r\nplot(sigma_portfolio, mu_portfolio, type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"MSFT\", pos=4)\r\n\r\n# Plot the position of the global minimum variance portfolio\r\ntext(x=global_min_var_portfolio$sd, y=global_min_var_portfolio$er, labels=\"Global min\", pos=2)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# The tangency portfolio\r\ntangency_portfolio <- tangency.portfolio(mu_hat_annual, cov_mat_annual, risk.free=0.03)\r\n\r\ntangency_portfolio\r\n\r\n# Summary of tangency_portfolio with annual risk free rate of 3%\r\nsummary(tangency_portfolio, risk.free=0.03)\r\n\r\n# Portfolio weights Boeing and Microsoft\r\nplot(tangency_portfolio)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# Annual risk-free rate of 3% per year for the T-bill\r\nt_bill_rate <- 0.03\r\n\r\n# Set of tangency portfolio weights\r\ntangency_weights <- seq(from=0, to=2, by=0.1)\r\nt_bill_weights <- 1 - tangency_weights\r\n# Portfolio parameters\r\nmu_portfolio_tangency_bill <- tangency_weights * tangency_portfolio$er + t_bill_weights * t_bill_rate\r\n\r\nsigma_portfolio_tangency_bill <- tangency_weights * tangency_portfolio$sd\r\n\r\n# Plot previous exercises\r\nplot(sigma_portfolio, mu_portfolio, type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"MSFT\", pos=4)\r\n\r\n# Plot portfolio combinations of tangency portfolio and T-bills\r\ntext(x=tangency_portfolio$sd, y=tangency_portfolio$er, labels=\"Tangency\", pos=2)\r\npoints(sigma_portfolio_tangency_bill, mu_portfolio_tangency_bill, col='blue', type='b', pch=16)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace.\r\n# Type \"ls()\" in the console to see them.\r\n\r\n# Define the portfolio ratio's\r\ntangency_weight <- 0.3\r\nt_bill_weight <- (1 - tangency_weight)\r\n \r\n# Define the portfolio parameters\r\nmu_portfolio_efficient <- tangency_weight * tangency_portfolio$er + t_bill_weight * 0.03\r\n\r\nsd_portfolio_efficient <- tangency_weight * tangency_portfolio$sd\r\n\r\n# Plot previous exercises\r\nplot(sigma_portfolio, mu_portfolio, type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"MSFT\", pos=4)\r\ntext(x=tangency_portfolio$sd, y=tangency_portfolio$er, labels=\"Tangency\", pos=2)\r\npoints(sigma_portfolio_tangency_bill, mu_portfolio_tangency_bill, type=\"b\", col=\"blue\", pch=16)\r\n\r\n# Plot Efficient Portfolio with 30% Tangency\r\n\r\ntext(x=sd_portfolio_efficient, y=mu_portfolio_efficient, labels=\"Efficient Portfolio with 30% Tangency\", pos=4, cex=0.75)\r\npoints(sd_portfolio_efficient, mu_portfolio_efficient, type='b', col='orange', pch=16, cex=2)\r\n\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. \r\n# Type \"ls()\" in the console to see them. \r\n\r\n# Calculate the weight of the tangency portfolio in the portfolio\r\ntangency_weight <- sigma_boeing / tangency_portfolio$sd\r\n\r\n# Calculate the portfolio parameters\r\nmu_portfolio_efficient <- t_bill_rate + tangency_weight * (tangency_portfolio$er - t_bill_rate)\r\n\r\nsd_portfolio_efficient <- tangency_weight * tangency_portfolio$sd\r\n\r\n# Plot previous exercises\r\nplot(sigma_portfolio, mu_portfolio,bg=\"NA\", type=\"b\", pch=16, ylim=c(0, max(mu_portfolio)), xlim=c(0, max(sigma_portfolio)), xlab=expression(sigma[p]), ylab=expression(mu[p]),col=c(rep(\"green\", 18), rep(\"red\", 13)))\r\ntext(x=sigma_boeing, y=mu_boeing, labels=\"Boeing\", pos=4)\r\ntext(x=sigma_msft, y=mu_msft, labels=\"MSFT\", pos=4)\r\ntext(x=tangency_portfolio$sd, y=tangency_portfolio$er, labels=\"Tangency\", pos=2)\r\npoints(sigma_portfolio_tangency_bill, mu_portfolio_tangency_bill, type=\"b\", col=\"blue\", pch=16)\r\n\r\n# Plot Efficient Portfolio with the same risk as Boeing\r\npoints(sd_portfolio_efficient, mu_portfolio_efficient, type=\"p\", col=\"orange\", pch=16, cex=2)\r\ntext(x=sd_portfolio_efficient, y=mu_portfolio_efficient, labels=\"Efficient Portfolio with same risk as Boeing\", pos=2, cex=0.75)\r\n\r\n\r\n\r\n# Section 8 - Computing Efficient Potfolio\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# Load the relevant packages\r\nlibrary(\"zoo\")\r\n\r\n# Load the working environment\r\nload(url(\"http://s3.amazonaws.com/assets.datacamp.com/course/compfin/lab9.RData\"))\r\n\r\n# Explore the data set\r\nhead(returns_df)\r\ntail(returns_df)\r\n\r\n# Timeplots with stocks on individual graphs\r\nmy.panel <- function(...) {\r\n lines(...)\r\n abline(h=0)\r\n}\r\nplot(returns_df, lwd=2, panel=my.panel, col=\"blue\")\r\n\r\n# Timeplots with stocks on same graph\r\nplot(returns_df, plot.type = \"single\", main=\"Returns\", col=1:4, lwd=2)\r\nabline(h=0)\r\nlegend(x=\"bottomleft\", legend=colnames(returns_df), col=1:4, lwd=2)\r\n\r\n\r\n# All data is preloaded in your workspace. Type 'ls()' in the console to see what has been loaded.\r\n\r\n# Parameters CER model\r\nmu_hat_month <- apply(returns_df, 2, mean)\r\nmu_hat_month\r\nsigma2_month <-apply(returns_df, 2, var)\r\n \r\nsigma2_month\r\nsigma_month <-sqrt(sigma2_month)\r\n \r\nsigma_month\r\ncov_mat_month <- var(returns_df)\r\ncov_mat_month\r\ncor_mat_month <- cor(returns_df)\r\n \r\ncor_mat_month\r\n\r\n# Pairwise scatterplots\r\npairs(coredata(returns_df), col='blue', pch=16)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# Calculate the global minimum variance portfolio\r\nglobal_min_var_portfolio = globalMin.portfolio(er=mu_hat_month, cov.mat=cov_mat_month, shorts=TRUE)\r\n \r\nglobal_min_var_portfolio\r\n\r\n# Plot the portfolio weights of our four stocks\r\nplot(global_min_var_portfolio)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# set restriction matrices\r\nD_matrix <- 2* cov_mat_month\r\nD_matrix\r\nd_vector <- rep(0,4)\r\nd_vector\r\nA_matrix <- cbind(rep(1,4),diag(4))\r\nA_matrix\r\nb_vector <- c(1,rep(0,4))\r\nb_vector\r\n\r\n# use solve.QP to minimize portfolio variance\r\nquad_prog <- solve.QP(D_matrix, d_vector, A_matrix, b_vector)\r\n \r\nquad_prog\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# The global minimum variance portfolio\r\nglobal_min_var_portfolio <- globalMin.portfolio(mu_hat_month, cov_mat_month, shorts=FALSE)\r\n \r\nglobal_min_var_portfolio \r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# highest average return\r\nmu_target <- max(mu_hat_month)\r\n\r\n# short sales allowed\r\nefficient_porfolio_short <- efficient.portfolio(er = mu_hat_month, cov.mat = cov_mat_month, target = mu_target, shorts = TRUE)\r\n \r\nefficient_porfolio_short\r\nplot(efficient_porfolio_short)\r\n\r\n# no short sales allowed\r\nefficient_porfolio_no_short <- efficient.portfolio(er = mu_hat_month, cov.mat = cov_mat_month, target = mu_target, shorts = FALSE)\r\n \r\nefficient_porfolio_no_short\r\nplot(efficient_porfolio_no_short)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# The efficient frontier of risky assets \r\nefficient_frontier <- efficient.frontier(mu_hat_month, cov_mat_month, alpha.min=-1, alpha.max=1)\r\nsummary(efficient_frontier)\r\n\r\n \r\nsummary(efficient_frontier)\r\n\r\n# The plot\r\nplot(efficient_frontier, plot.assets=T, col= \"blue\", lwd = 2)\r\n\r\n\r\n# All data and CER parameters are preloaded in your workspace. Type 'ls()' in the console to see them.\r\n\r\n# risk free rate\r\nt_bill_rate <- 0.005\r\n\r\n# Tangency portfolio short sales allowed\r\ntangency_portfolio_short <- tangency.portfolio(er = mu_hat_month,\r\n cov.mat =cov_mat_month,\r\n risk.free = t_bill_rate,\r\n shorts = T)\r\n \r\nsummary(tangency_portfolio_short)\r\n#plot\r\nplot(tangency_portfolio_short)\r\n\r\n# Tangency portfolio short sales not allowed\r\ntangency_portfolio_no_short <- tangency_portfolio_no_short <- tangency.portfolio(er = mu_hat_month,\r\n cov.mat =cov_mat_month,\r\n risk.free = t_bill_rate,\r\n shorts = F)\r\n \r\nsummary(tangency_portfolio_no_short)\r\n#plot\r\nplot(tangency_portfolio_no_short)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "e6b78fe10275e07a147c19c5db7c6ae409ac088c", "size": 33544, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction to Computational Finance with R.r", "max_stars_repo_name": "KT12/R", "max_stars_repo_head_hexsha": "d7aa803eab845b79f8eee5812ece31c76d665419", "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": "Introduction to Computational Finance with R.r", "max_issues_repo_name": "KT12/R", "max_issues_repo_head_hexsha": "d7aa803eab845b79f8eee5812ece31c76d665419", "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": "Introduction to Computational Finance with R.r", "max_forks_repo_name": "KT12/R", "max_forks_repo_head_hexsha": "d7aa803eab845b79f8eee5812ece31c76d665419", "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.2538461538, "max_line_length": 216, "alphanum_fraction": 0.6992904841, "num_tokens": 9869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6915852604506453}} {"text": "# Master Thesis Project - Extreme Value Theory\n# We use here QQ-plots to assess graphically the\n# goodness of fit of our extreme distributions\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the five stocks then\n# getting the LVMH and the Total data\ndf_plain <- loadStockData_plain(CHOICE)\n\n# Fitting\n\t# Computing the 95 % - quantiles for each of the stocks\n\tquantiles <- c(quantile(df_plain[[1]],0.95), quantile(df_plain[[2]],0.95), quantile(df_plain[[3]],0.975),\n\t\t\t\t\tquantile(df_plain[[4]],0.95), quantile(df_plain[[5]],0.95))\n\t\t\t\t\t\n\t# Getting the data above the threshold\n\tdata_bnp <- df_plain[[1]]\n\tdata_bnp <- data_bnp[data_bnp > quantiles[1]]\n\n\tdata_carrefour <- df_plain[[2]]\n\tdata_carrefour <- data_carrefour[data_carrefour > quantiles[2]]\n\n\tdata_lvmh <- df_plain[[3]]\n\tdata_lvmh <- data_lvmh[data_lvmh > quantiles[3]]\n\n\tdata_sanofi <- df_plain[[4]]\n\tdata_sanofi <- data_sanofi[data_sanofi > quantiles[4]]\n\n\tdata_total <- df_plain[[5]]\n\tdata_total <- data_total[data_total > quantiles[5]]\n\n\t# Fitting the data, and getting the corresponding location, scale and \n\t# shape parameters respectively, for each stock\n\tbnp_fit <- (gev.fit(data_bnp))\n\tcarrefour_fit <- gev.fit(data_carrefour)\n\tlvmh_fit <- gev.fit(data_lvmh)\n\tsanofi_fit <- gev.fit(data_sanofi)\n\ttotal_fit <- gev.fit(data_total)\n\t\n\t# Saving the GEV parameters for later use\n\tparams_bnp <- bnp_fit$mle\n\tparams_carrefour <- carrefour_fit$mle\n\tparams_lvmh <- lvmh_fit$mle\n\tparams_sanofi <- sanofi_fit$mle\n\tparams_total <- total_fit$mle\n\n# Drawing the QQ-plots\nN <- dim(df_plain)[1]\nqVect <- (N + 1 - 1:N)/(N + 1)\n\n\t# Ordering the samples (increasing sort)\n\tdata_bnp <- sort(df_plain[[1]])\n\tdata_carrefour <- sort(df_plain[[2]])\n\tdata_lvmh <- sort(df_plain[[3]])\n\tdata_sanofi <- sort(df_plain[[4]])\n\tdata_total <- sort(df_plain[[5]])\n\t\n\t# Getting the quantiles of the fitting distributions\n\tgev_bnp <- qgev(qVect,params_bnp[3],params_bnp[1],params_bnp[2])\n\tgev_carrefour <- qgev(qVect,params_carrefour[3],params_carrefour[1],params_carrefour[2])\n\tgev_lvmh <- qgev(qVect,params_lvmh[3],params_lvmh[1],params_lvmh[2])\n\tgev_sanofi <- qgev(qVect,params_sanofi[3],params_sanofi[1],params_sanofi[2])\n\tgev_total <- qgev(qVect,params_total[3],params_total[1],params_total[2])\n\t\n\t# Plotting for all the Data\n\tquartz()\n png(file = \"QQ_BNP.png\")\n\tplot(qVect,gev_bnp, main = \"QQ-plot BNP\", xlab =\"\", ylab = \"\")\n\tabline(lm(gev_bnp~qVect), col = \"red\")\n\tdev.off()\n\tgraphics.off()\n\n\tquartz()\n\tpng(file = \"QQ_Carrefour.png\")\n\tplot(qVect, gev_carrefour, main = \"QQ-plot Carrefour\", xlab =\"\", ylab = \"\")\n\tabline(lm(gev_carrefour~qVect), col = \"red\")\n\tdev.off()\n\tgraphics.off()\n\n\tquartz()\n\tpng(file = \"QQ_LVMH.png\")\n\tplot(qVect, gev_lvmh, main = \"QQ-plot LVMH\", xlab =\"\", ylab = \"\")\n\tabline(lm(gev_lvmh~qVect), col = \"red\")\n\tdev.off()\n\tgraphics.off()\n\n\tquartz()\n\tpng(file = \"QQ_Sanofi.png\")\n\tplot(qVect, gev_sanofi, main = \"QQ-plot Sanofi\", xlab =\"\", ylab = \"\")\n\tabline(lm(gev_sanofi~qVect), col = \"red\")\n\tdev.off()\n\tgraphics.off()\n\n\tquartz()\n\tpng(file = \"QQ_Total.png\")\n\tplot(qVect, gev_total, main = \"QQ-plot Total\", xlab =\"\", ylab = \"\")\n\tabline(lm(gev_total~qVect), col = \"red\")\n\tdev.off()\n\tgraphics.off()\n\t\n\t# Plotting only for the high quantiles\n\t\t\n\t\t# Computing the 95 % - quantiles for each of the stocks\n\t\tquantiles <- c(quantile(df_plain[[1]],0.95), quantile(df_plain[[2]],0.95), quantile(df_plain[[3]],0.975),\n\t\t\t\t\tquantile(df_plain[[4]],0.95), quantile(df_plain[[5]],0.95))\n\t\t\t\t\t\n\t\t# Getting the data above the threshold\n\t\tdata_bnp <- df_plain[[1]]\n\t\tdata_bnp <- data_bnp[data_bnp > quantiles[1]]\n\n\t\tdata_carrefour <- df_plain[[2]]\n\t\tdata_carrefour <- data_carrefour[data_carrefour > quantiles[2]]\n\n\t\tdata_lvmh <- df_plain[[3]]\n\t\tdata_lvmh <- data_lvmh[data_lvmh > quantiles[3]]\n\n\t\tdata_sanofi <- df_plain[[4]]\n\t\tdata_sanofi <- data_sanofi[data_sanofi > quantiles[4]]\n\n\t\tdata_total <- df_plain[[5]]\n\t\tdata_total <- data_total[data_total > quantiles[5]]\n\t\t\n\t\t# BNP\n\t\tN_BNP <- length(data_bnp)\n\t\tqVectBNP <- (N_BNP + 1 - 1:N_BNP)/(N_BNP + 1)\n\t\t\n\t\tdata_bnp <- sort(data_bnp)\n\t\tgev_bnp <- qgev(qVectBNP,params_bnp[3],params_bnp[1],params_bnp[2])\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_BNP2.png\")\n\t\tplot(qVectBNP,gev_bnp, main = \"QQ-plot BNP Paribas, above \\n95 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_bnp~qVectBNP), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\t# Carrefour\n\t\tN_Carrefour <- length(data_carrefour)\n\t\tqVectCarrefour <- (N_Carrefour + 1 - 1:N_Carrefour)/(N_Carrefour + 1)\n\t\t\n\t\tdata_carrefour <- sort(data_carrefour)\n\t\tgev_carrefour <- qgev(qVectCarrefour,params_carrefour[3],params_carrefour[1],params_carrefour[2])\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Carrefour2.png\")\n\t\tplot(qVectCarrefour,gev_carrefour, main = \"QQ-plot Carrefour, above \\n95 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_carrefour~qVectCarrefour), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\n\t\t\n\t\t# LVMH\n\t\tN_LVMH <- length(data_lvmh)\n\t\tqVectLVMH <- (N_LVMH + 1 - 1:N_LVMH)/(N_LVMH + 1)\n\t\t\n\t\tdata_lvmh <- sort(data_lvmh)\n\t\tgev_lvmh <- qgev(qVectLVMH,params_lvmh[3],params_lvmh[1],params_lvmh[2])\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_LVMH2.png\")\n\t\tplot(qVectLVMH,gev_lvmh, main = \"QQ-plot LVMH, above \\n97.5 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_lvmh~qVectLVMH), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\t\n\t\n\t\t# Sanofi\n\t\tN_Sanofi <- length(data_sanofi)\n\t\tqVectSanofi <- (N_Sanofi + 1 - 1:N_Sanofi)/(N_Sanofi + 1)\n\t\t\n\t\tdata_sanofi <- sort(data_sanofi)\n\t\tgev_sanofi <- qgev(qVectSanofi,params_sanofi[3],params_sanofi[1],params_sanofi[2])\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Sanofi2.png\")\n\t\tplot(qVectSanofi,gev_sanofi, main = \"QQ-plot Sanofi, above \\n95 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_sanofi~qVectSanofi), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\t\n\t\n\t\t# Total\n\t\tN_Total <- length(data_total)\n\t\tqVectTotal <- (N_Total + 1 - 1:N_Total)/(N_Total + 1)\n\t\t\n\t\tdata_total <- sort(data_total)\n\t\tgev_total <- qgev(qVectTotal,params_total[3],params_total[1],params_total[2])\n\t\t\n\t\tquartz()\n \tpng(file = \"QQ_Total2.png\")\n\t\tplot(qVectTotal,gev_total, main = \"QQ-plot Total, above \\n95 %-quantile data\", xlab =\"\", ylab = \"\")\n\t\tabline(lm(gev_total~qVectTotal), col = \"red\")\n\t\tdev.off()\n\t\tgraphics.off()\t\t\n\n", "meta": {"hexsha": "18bf081e8a8237f49dcd6bd1ef5dc0f61b94d6c9", "size": 6672, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_tache8/QQPlots.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_tache8/QQPlots.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_tache8/QQPlots.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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.4716981132, "max_line_length": 113, "alphanum_fraction": 0.6762589928, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6914389879391115}} {"text": "z1 <- 1.5 + 3i\nz2 <- 1.5 + 1.5i\nprint(z1 + z2) # 3+4.5i\nprint(z1 - z2) # 0+1.5i\nprint(z1 * z2) # -2.25+6.75i\nprint(z1 / z2) # 1.5+0.5i\nprint(-z1) # -1.5-3i\nprint(Conj(z1)) # 1.5-3i\nprint(abs(z1)) # 3.354102\nprint(z1^z2) # -1.102483-0.383064i\nprint(exp(z1)) # -4.436839+0.632456i\nprint(Re(z1)) # 1.5\nprint(Im(z1)) # 3\n", "meta": {"hexsha": "daca9a3ee386238e9dd63acb3adc9c8235b29d85", "size": 357, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Arithmetic-Complex/R/arithmetic-complex.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-Complex/R/arithmetic-complex.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-Complex/R/arithmetic-complex.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": 25.5, "max_line_length": 39, "alphanum_fraction": 0.5098039216, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6914361322419151}} {"text": "# trees.r\n# MWL, Lecture 2\n# Author(s): [Phil Snyder]\n\n#install.packages(\"mlbench\") # we can download new libraries right from the R terminal!\nlibrary(mlbench)\n#help(package=\"mlbench\")\ndata(BreastCancer)\n#help(topic=\"BreastCancer\", package=\"mlbench\")\nBreastCancer$Id <- NULL # Just get rid of this column. We won't need it.\n\n# Let's fit a tree to our data\nlibrary(rpart) # rpart stands for \"recursive partitioning\"\nbasicTree <- rpart(Class ~ ., BreastCancer, method='class')\nbasicTree \nplot(basicTree) \ntext(basicTree, cex=0.7) # cex controls text size\n# Try leaving the \"type='class'\" parameter out of the next line.\n# What do you think happens? Is this maybe a good thing to do in this application?\nbasicTreePredictions <- predict(basicTree, BreastCancer, type='class')\nbasicTreeResults <- table(basicTreePredictions == BreastCancer$Class) / length(basicTreePredictions)\nbasicTreeResults # TRUE: 0.9642, FALSE: 0.0357\n\n# Why don't we try growing our tree so far down that every node contains only one class?\ngodTree <- rpart(Class ~ ., BreastCancer, method='class', \n control=c(cp=-1, minsplit=2, minbucket=1))\nplot(godTree)\ntext(godTree, cex=0.6) \ngodTreePredictions <- predict(godTree, BreastCancer, type='class')\ngodTreeResults <- table(godTreePredictions == BreastCancer$Class) / length(godTreePredictions)\ngodTreeResults # TRUE: 1, FALSE: 0\n\n\"\nAmazing! We have a perfect predictor. All other machine learning algorithms cower in \nsight of the glorious predictive power of godTree.\n\nOf course, I'm kidding. What happens when a new data point comes along and, due to \nuncertainty, randomness, etc., doesn't conform perfectly to the model we have constructed?\nWe are interested in how well our predictor performs on *unseen*, future data, so we must \n'holdout' some data when we fit our model, then see how well the model performs on our\nholdout data. This will give us a good estimate of how well our model *actually* performs\non unseen data.\n\nIn general, we partition our data into a 'train' set, which we fit our model to, \nand a 'test' set, which we evaluate our model on. This is the most basic form of \ncross-validation.\n\"\n\npartition <- sample(nrow(BreastCancer), floor(0.7 * nrow(BreastCancer)))\ntrainData <- BreastCancer[partition,]\ntestData <- BreastCancer[-partition,] # can you guess what the '-' operator is doing here?\n\ngodTree <- rpart(Class ~ ., trainData, method='class', \n control=c(cp=-1, minsplit=2, minbucket=1))\ngodTreeTrainPredictions <- predict(godTree, trainData, type='class')\ngodTreeTestPredictions <- predict(godTree, testData, type='class')\n\ngodTreeTrainResults <- table(godTreeTrainPredictions \n == trainData$Class) / length(godTreeTrainPredictions)\ngodTreeTrainResults # Accuracy on train set TRUE: 1, FALSE: 0\ngodTreeTestResults <- table(godTreeTestPredictions \n == testData$Class) / length(godTreeTestPredictions)\ngodTreeTestResults # Accuracy on test set (approx.) TRUE: 0.9523, FALSE: 0.0476\n\n# Still pretty good, but this is a relatively easy classification problem.\n# When we have significantly higher accuracy on the training data as opposed to the \n# test data, this is called 'overfitting'. We fit our model to the train data *too* well.\n\n\"\nWe now have a model, and a way to accurately test the predictive power of our model by\npartitioning our data into a training set and a test set. The question remains, what \nparameters should our model have, and what values should they take on? \nIn the case of linear regression, our parameters are \nthe slope and intercept of the regression line. In the case of decision trees, our \nparameters should control how far down we grow our tree. There are a few ways to do this,\nbut in the rpart function we may control the growth of our tree by varying the \ncomplexity parameter (cp), the minimum # of data points in a node needed to consider a \nsplit (minsplit), the minimum amount of data points that are allowed to sit in a \nleaf (minbucket), or the maxdepth of the tree (maxdepth). \nYou may look up what exactly a 'complexity parameter' is, but all \nyou really need to know is that the lower your cp, the more your tree will grow (subject\nto the minsplit, minbucket, maxdepth constraints). Setting cp = -1 (like in the \ngodTree example) will tell rpart to keep splitting until it cannot split anymore \n(again, subject to the minsplit, minbucket, maxdepth constraints).\n\nIn general, finding optimal parameters is an optimization problem. Usually a numerical\noptimization problem (i.e., there is no closed form optimal solution). More on this \nin later lectures.\n\nWe will use an algorithm called 'grid search' to find an optimal parameter set. \nGrid search is just a fancy name for trying-every-reasonable-combination-of-parameters. Since\ncp, minsplit, minbucket, and maxdepth are each different ways of measuring the same thing,\nwe can effectively tell rpart to ignore the minsplit, minbucket, and maxdepth constraints and only \nconsider the cp for a 'good enough' optimization of our parameters.\n\"\n\n# R is a functional language, so it can be frustratingly difficult to do something as \n# simple as add an element to the end of an array (vector). We use the foreach library\n# to streamline the process. We will also be using a new dataset from a new library\n# ElemStatLearn, 'Spam', which is more difficult to classify and illustrates \n# the concept better.\n#install.packages(c(\"foreach\", \"ElemStatLearn\"))\nlibrary(foreach)\nlibrary(ElemStatLearn)\ndata(spam)\n#help(topic=\"spam\", package=\"ElemStatLearn\")\n\npartition <- sample(nrow(spam), floor(0.7 * nrow(spam)))\ntrainData <- spam[partition,]\ntestData <- spam[-partition,] \n\ncpValues <- c(0.5, 0.1, 0.05, 0.01, 0.005, 0.001, 0.0005, 0.0001)\ntreesLoss <- foreach(val = cpValues, .combine='c') %do% {\n ctrl <- rpart.control(cp=val, minsplit=2, minbucket=1) # maxdepth defaults to 30\n tree <- rpart(spam ~ ., trainData, method='class', control=ctrl)\n treePredictions <- predict(tree, testData, type='class')\n # proportion incorrect\n loss <- table(treePredictions == testData$spam)[\"FALSE\"][[1]] / length(treePredictions)\n return(loss)\n}\nresults <- data.frame(cp = cpValues, loss = treesLoss)\n# x log scale and reversed\nplot(results, log='x', xlim=c(max(results$cp), min(results$cp)), type='o') \n\n\"\nGreat. Around 1e-3 seems optimal. BUT, we have made yet another naive mistake. \nDecision trees are *high variance* predictors. This means that the decision trees\nwe generate are highly dependent on the specific data points in our training dataset. \nIf we had sampled a different training set, it's possible we may have had a different \noptimal value. To counterbalance this variability, we use k-fold cross-validation.\nWikipedia has a nice paragraph on k-fold CV:\nhttps://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation\n\nIn the above article 'validation set' is similar to a test set. We will discuss \nvalidation sets and why we need them later. K-fold CV reduces variability (in \nthe traditional statistical sense of the word) by averaging our results.\n\nThis issue alludes to something you will need to know about (eventually), but probably \nwon't be covered this lecture. That is the Bias-Variance Tradeoff \nhttps://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff\n\"\n\n# do 10-fold CV\ntrainData <- trainData[sample(nrow(spam)),] # randomly permute the rows in our data frame\npartitionSize <- floor(nrow(trainData) / 10)\ntreesLoss <- foreach(val = cpValues, .combine='c') %do% {\n ctrl <- rpart.control(cp=val, minsplit=2, minbucket=1) \n summedResults <- 0\n for (i in seq(1, nrow(trainData) - partitionSize, partitionSize)) {\n validationSetIndices <- i:(i + partitionSize - 1) # seq from i to (partitionSize-1)\n validationData <- trainData[validationSetIndices,]\n nonValidationData <- trainData[-validationSetIndices,]\n tree <- rpart(spam ~ ., nonValidationData, method='class', control=ctrl)\n treePredictions <- predict(tree, validationData, type='class')\n loss <- table(treePredictions == validationData$spam)[\"FALSE\"][[1]] / length(treePredictions)\n summedResults <- summedResults + loss\n }\n averagedResults <- summedResults / 10\n return(averagedResults)\n}\ncvResults <- data.frame(cp = cpValues, loss = treesLoss)\nplot(cvResults, log='x', xlim=c(max(results$cp), min(results$cp)))\n\n# Now we have a nice, smooth curve, and the optimal cp value will either be 1e-3 or 5e-4 depending \n# on how easy to classify your test set happens to be (Sometimes we repeat the k-fold CV process\n# itself multiple times to eliminate this 'lucky draw' element). If you're bored you can modify \n# the code and plot the standard error bars on top of each data point. Another way of choosing the \n# optimal parameter is to choose the value that gives the loosest fit to the training data yet is \n# still within one standard error of the \"best\" value.\n\n# So how good is a decision tree with an optimal parameter value?\nbestTree <- rpart(spam ~ ., trainData, method='class', control=c(cp=1e-3, minsplit=2, minbucket=1))\nbestTreePredictions <- predict(bestTree, testData, type='class')\nbestTreeResults <- table(bestTreePredictions == testData$spam) / length(bestTreePredictions)\nbestTreeResults # (approx.) TRUE: 0.9225, FALSE: 0.07748\n\n\"\nNow that we've made it this far, I can tell you a secret: Decision Trees are relatively crude \npredictors. Yet we are still able to correctly identify 92% of emails as either spam or \nnot spam using a singe decision tree and the 'bag-of-words' model (this is how the variables \nin our spam data were generated, see [ESL 9.2.5]). To create even more powerful tree-based \npredictors, we must learn about ensembles... (see treeEnsembles.r)\n\"\n", "meta": {"hexsha": "ba3e4cf4fbf097d8017ce67c21a4a0566f32bf32", "size": 9788, "ext": "r", "lang": "R", "max_stars_repo_path": "2015-2016.Meetings/02.trees/trees.r", "max_stars_repo_name": "NViday/machine_learning_workshop_Winter17", "max_stars_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-02-07T09:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T09:49:35.000Z", "max_issues_repo_path": "2015-2016.Meetings/02.trees/trees.r", "max_issues_repo_name": "NViday/machine_learning_workshop_Winter17", "max_issues_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "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": "2015-2016.Meetings/02.trees/trees.r", "max_forks_repo_name": "NViday/machine_learning_workshop_Winter17", "max_forks_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-27T11:06:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-27T11:06:24.000Z", "avg_line_length": 53.1956521739, "max_line_length": 101, "alphanum_fraction": 0.7451982019, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7879312031126511, "lm_q1q2_score": 0.6913913332901934}} {"text": "library(shiny)\nlibrary(matrixcalc)\nlibrary(plotly)\n\ngetLikelihood <- function(point, expectation, covMatrix) {\n pointMinusMean <- t(as.matrix(point - expectation))\n \n covMatrixInverse <- solve(covMatrix)\n nom <- exp(-(pointMinusMean %*% covMatrixInverse %*% t(pointMinusMean)) / 2)\n denom <- sqrt((2 * pi) ^ nrow(covMatrix) * det(covMatrix))\n \n return(nom / denom)\n}\n\ngetPlugInProbability <- function(point, lambda, prior, expectations, covMatrix) {\n likelihood <- getLikelihood(point, expectations, covMatrix)\n \n probability <- lambda * prior * likelihood;\n \n return (probability)\n}\n\nfunction(input, output, session, ...) {\n output$err <- function() {\n # E <- matrix(c(input$E1, input$E3, input$E2, input$E4), nrow = 2)\n # if (!matrixcalc::is.positive.definite(E)) {\n # return(\"Error: covariance matrix has to be positive definite.\")\n # }\n return(\"\")\n }\n \n output$p1 <- renderPlotly({\n lambdas <- c(input$la1, input$la2)\n prior <- c(input$ratio / 100, 1 - (input$ratio / 100))\n expectations <- list(\n c(input$mu11, input$mu12),\n c(input$mu21, input$mu22)\n )\n \n covMatrix <- list(\n matrix(c(input$E11, input$E12, input$E13, input$E14), nrow = 2, ncol = 2, byrow = TRUE),\n matrix(c(input$E21, input$E22, input$E23, input$E24), nrow = 2, ncol = 2, byrow = TRUE)\n )\n \n center <- c((input$mu11 + input$mu21) / 2, (input$mu12 + input$mu22) / 2)\n \n \n xs <- seq(from = center[1] - 5, to = center[1] + 5, by = 0.1)\n ys <- seq(from = center[2] - 5, to = center[2] + 5, by = 0.1)\n z <- c()\n \n \n for (y in ys) {\n curr <- c()\n for (x in xs) {\n arg <- c(x, y)\n value <- (getPlugInProbability(c(x, y), lambdas[1], prior[1], expectations[[1]], covMatrix[[1]]) - getPlugInProbability(c(x, y), lambdas[2], prior[2], expectations[[2]], covMatrix[[2]]))\n \n curr <- c(curr, value)\n }\n z <- rbind(z, curr)\n }\n \n \n fig <- plot_ly(\n type = 'contour',\n x = ~xs,\n y = ~ys,\n z = ~z)\n fig\n })\n \n output$p2 <- renderPlotly({\n lambdas <- c(input$la1, input$la2)\n prior <- c(input$ratio / 100, 1 - (input$ratio / 100))\n expectations <- list(\n c(input$mu11, input$mu12),\n c(input$mu21, input$mu22)\n )\n \n covMatrix <- list(\n matrix(c(input$E11, input$E12, input$E13, input$E14), nrow = 2, ncol = 2, byrow = TRUE),\n matrix(c(input$E21, input$E22, input$E23, input$E24), nrow = 2, ncol = 2, byrow = TRUE)\n )\n \n center <- c((input$mu11 + input$mu21) / 2, (input$mu12 + input$mu22) / 2)\n \n \n xs <- seq(from = center[1] - 5, to = center[1] + 5, by = 0.1)\n ys <- seq(from = center[2] - 5, to = center[2] + 5, by = 0.1)\n z <- c()\n \n \n for (y in ys) {\n curr <- c()\n for (x in xs) {\n arg <- c(x, y)\n value <- (getPlugInProbability(c(x, y), lambdas[1], prior[1], expectations[[1]], covMatrix[[1]]) - getPlugInProbability(c(x, y), lambdas[2], prior[2], expectations[[2]], covMatrix[[2]]))\n \n curr <- c(curr, value)\n }\n z <- rbind(z, curr)\n }\n \n \n fig <- plot_ly(\n type = 'surface',\n x = ~xs,\n y = ~ys,\n z = ~z)\n fig\n })\n}", "meta": {"hexsha": "f85e58b8ad4d7ae850fe3dbf4049f6dea9c33bb5", "size": 3223, "ext": "r", "lang": "R", "max_stars_repo_path": "7 - Plug-in algorithm/shiny/server.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "7 - Plug-in algorithm/shiny/server.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "7 - Plug-in algorithm/shiny/server.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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.5221238938, "max_line_length": 194, "alphanum_fraction": 0.542972386, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073577, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6911408080785179}} {"text": "write(round(pnorm(40, 30, 4), 3), stdout())\r\nwrite(round(1 - pnorm(21, 30, 4), 3), stdout())\r\nwrite(round(pnorm(35, 30, 4) - pnorm(30, 30, 4), 3), stdout())", "meta": {"hexsha": "fa1974a31ba8791f622fc6e65d505ea823ef1a2a", "size": 156, "ext": "r", "lang": "R", "max_stars_repo_path": "normal-distribution-1/accepted_solutions/18822925.r", "max_stars_repo_name": "hermes-jr/my-hackerrank-solutions", "max_stars_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "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": "normal-distribution-1/accepted_solutions/18822925.r", "max_issues_repo_name": "hermes-jr/my-hackerrank-solutions", "max_issues_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "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": "normal-distribution-1/accepted_solutions/18822925.r", "max_forks_repo_name": "hermes-jr/my-hackerrank-solutions", "max_forks_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "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.0, "max_line_length": 62, "alphanum_fraction": 0.5897435897, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6911360865795192}} {"text": "# x, y: the x and y coordinates of the hull points\n# n: the number of points in the curve.\nbezierCurve <- function(x, y, n=10)\n\t{\n\toutx <- NULL\n\touty <- NULL\n\n\ti <- 1\n\tfor (t in seq(0, 1, length.out=n))\n\t\t{\n\t\tb <- bez(x, y, t)\n\t\toutx[i] <- b$x\n\t\touty[i] <- b$y\n\n\t\ti <- i+1\n\t\t}\n\n\treturn (list(x=outx, y=outy))\n\t}\n\nbez <- function(x, y, t)\n\t{\n\toutx <- 0\n\touty <- 0\n\tn <- length(x)-1\n\tfor (i in 0:n)\n\t\t{\n\t\toutx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]\n\t\touty <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]\n\t\t}\n\n\treturn (list(x=outx, y=outy))\n\t}\n\n# Example usage\nx <- c(4,6,4,5,6,7)\ny <- 1:6\nplot(x, y, \"o\", pch=20)\npoints(bezierCurve(x,y,20), type=\"l\", col=\"red\")\n", "meta": {"hexsha": "8d3817683d7483758896cd33fd16d7bf19af2b5a", "size": 669, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Bitmap-B-zier-curves-Cubic/R/bitmap-b-zier-curves-cubic.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/Bitmap-B-zier-curves-Cubic/R/bitmap-b-zier-curves-cubic.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/Bitmap-B-zier-curves-Cubic/R/bitmap-b-zier-curves-cubic.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": 16.725, "max_line_length": 54, "alphanum_fraction": 0.5216741405, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.691000745292361}} {"text": "#!/usr/bin/env Rscript\n\nremoveOutliers <- function(dataset) {\n datasetRemoved = list()\n\n lsrl = lm(dataset$y ~ dataset$x)\n cookd = cooks.distance(lsrl)\n\n datasetRemoved$x = dataset$x[cookd < (2/length(dataset$x))]\n datasetRemoved$y = dataset$y[cookd < (2/length(dataset$x))]\n return(datasetRemoved)\n}\n\nremoveDuplicates <- function(dataset) {\n datasetRemoved = list()\n datasetRemoved$x = dataset$x[c(TRUE, diff(dataset$x) != 0)]\n datasetRemoved$y = dataset$y[c(TRUE, diff(dataset$x) != 0)]\n return(datasetRemoved)\n}\n\n# Datasets\ndataA = list()\ndataB = list()\ndataAB = list()\n\n# Read Files\n# NOTE: we can't just readline() b/c running this script w/ Rscript is \"non-interactive\"...\ncat(\"First File to Read: \")\nfileA = readLines(file(\"stdin\"), 1)\ndataAfile = read.csv(paste(\"data/\", fileA, \".csv\", sep=\"\"), header = TRUE)\ncat(\"Second File to Read: \")\nfileB = readLines(file(\"stdin\"), 1)\ndataBfile = read.csv(paste(\"data/\", fileB, \".csv\", sep=\"\"), header = TRUE)\ncloseAllConnections()\n\n# Assign to Datasets\ndataA$x = dataAfile$TOTAL.AMP\ndataA$y = dataAfile$VOLT\ndataB$x = dataBfile$TOTAL.AMP\ndataB$y = dataBfile$VOLT\n\n# Filter Outliers (optional)\ndataA = removeOutliers(dataA)\ndataB = removeOutliers(dataB)\n\n# Remove Duplicate Current Readings (optional)\ndataA = removeDuplicates(dataA)\ndataB = removeDuplicates(dataB)\n\n# Find combined data set\ndataAB$x = c(dataA$x, dataB$x)\ndataAB$y = c(dataA$y, dataB$y)\n\n# TODO correlation coefficient for each dataset?\n# TODO display LSRL for each set?\n# TODO keep original dataset, plot outliers\n\n# Plot Datasets (optional)\nx11()\nplot(dataA$x, dataA$y, main=\"Motor Comparison, Amps vs. Volts\", xlab=\"Amps\", ylab=\"Volts\", col=\"blue\")\npoints(dataB$x, dataB$y, col=\"green\")\nabline(lm(dataA$y ~ dataA$x), col=\"blue\")\nabline(lm(dataB$y ~ dataB$x), col=\"green\")\nabline(lm(dataAB$y ~ dataAB$x), col=\"black\")\n\n# TODO avoid recomputing Linear Models, store in dataA$lm? Also store dataA$residuals? (Or just dataA$lm$residuals)\n\n# Find SSRs\ndataA$ssr = sum(resid(lm(dataA$y ~ dataA$x)) ^ 2)\ndataB$ssr = sum(resid(lm(dataB$y ~ dataB$x)) ^ 2)\ndataAB$ssr = sum(resid(lm(dataAB$y ~ dataAB$x)) ^ 2)\n\n# Do Chow Test to find F statistic\nk = 2\ndf = length(dataA$x) + length(dataB$x) - (2 * k)\n\nfstat = ((dataAB$ssr - (dataA$ssr + dataB$ssr)) / k) / ((dataA$ssr + dataB$ssr) / (df))\n\n# Print Info\ncat(\"SSR A:\\t\", dataA$ssr, \"\\n\")\ncat(\"SSR B:\\t\", dataB$ssr, \"\\n\")\ncat(\"SSR AB:\\t\", dataAB$ssr, \"\\n\")\ncat(\"k:\\t\", k, \"\\n\")\ncat(\"df:\\t\", df, \"\\n\")\ncat(\"F Stat:\\t\", fstat, \"\\n\")\ncat(\"P-Val:\\t\", pf(fstat, k, df, lower.tail=FALSE), \"\\n\")\n\n# Basically a bunch of hacks\ncat(\"Press [Enter] to Quit...\")\nenter = readLines(file(\"stdin\"), 1)\ncloseAllConnections()\n", "meta": {"hexsha": "f452b92af04f12e1e19dc7869b8d4556b1c1d7e5", "size": 2695, "ext": "r", "lang": "R", "max_stars_repo_path": "script.r", "max_stars_repo_name": "karagenit/chow", "max_stars_repo_head_hexsha": "70422ccc1cdbf9099bca5eb641f82e16e238aeb2", "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": "script.r", "max_issues_repo_name": "karagenit/chow", "max_issues_repo_head_hexsha": "70422ccc1cdbf9099bca5eb641f82e16e238aeb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-09T03:49:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T03:49:37.000Z", "max_forks_repo_path": "script.r", "max_forks_repo_name": "karagenit/chow", "max_forks_repo_head_hexsha": "70422ccc1cdbf9099bca5eb641f82e16e238aeb2", "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.2934782609, "max_line_length": 115, "alphanum_fraction": 0.6690166976, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.690984555256791}} {"text": "# Example 1 p. 389 Figure 10.3\r\nlibrary(rsm)\r\nrotd <- ccd(3, n0 = c(4,2), alpha = \"rotatable\", randomize = FALSE)\r\nrotdm <- rotd[ , 3:5]\r\nlibrary(Vdgraph)\r\nVdgraph(rotdm)\r\n\r\n# Figure 10.5 p. 392\r\n# create design with rsm\r\nlibrary(rsm)\r\nbbd3 <- bbd(3,randomize=FALSE,n0=3)\r\nlibrary(Vdgraph)\r\nVdgraph(bbd3[ , 3:5])\r\n\r\n# Figure 10.6 p. 392\r\nlibrary(Vdgraph)\r\nFDSPlot(bbd3[ , 3:5], mod=2)\r\n\r\n# Figure 10.8 p. 394\r\nlibrary(Vdgraph)\r\ndata(SCDH2)\r\nVdgraph(SCDH2)\r\n\r\n# Figure 10.9 p. 395\r\n# first get the ccd2\r\nlibrary(rsm)\r\nccd2<- ccd(2, n0 = c(3,2), alpha = \"rotatable\", randomize = FALSE)[ ,3:4]\r\nCompare2FDS(SCDH2,ccd2,\"SCD\",\"CCD\",mod=2)\r\n\r\n# Figure 10.10 p. 396\r\nlibrary(Vdgraph)\r\ndata(D310)\r\nVdgraph(D310)\r\n\r\n# Example 2 p. 396-397\r\nlibrary(rsm)\r\nccd.pick(k=3)\r\n\r\n# Example 3 p. 397\r\nlibrary(rsm)\r\nccd.up<-ccd(y~x1+x2+x3,n0=c(4,2),alpha=\"rotatable\",randomize=FALSE)\r\nVdgraph(ccd.up[ , 3:5])\r\n\r\n# Example 4 p. 398\r\nccd.up<-ccd(y~x1+x2+x3,n0=c(4,2),alpha=\"rotatable\",\r\n coding=list(x1~(Temp-150)/10,x2~(Press-50)/5, x3~(Rate-4/1)),randomize=FALSE)\r\nhead(ccd.up)\r\n\r\n# Example 5 p. 398\r\nlibrary(rsm)\r\nTreb<-bbd(y ~ x1 + x2 + x3, randomize = FALSE, n0 = 3,\r\n coding=list(x1~(A-6)/2, x2~(B-15)/5, x3~(C-2.5)/.5))\r\nhead(Treb)\r\n\r\n# Example 6 p. 399\r\nlibrary(Vdgraph)\r\ndata(D310)\r\nD310\r\n\r\n# Example 7 p. 400\r\ndes <- transform(D310, Temp=10*x1+150, Press=5*x2+50, Rate = x3 + 4)\r\ndes[sample(1:10) ,4:6]\r\n\r\n# Example 8 p. 401\r\nlibrary(daewr)\r\ndata(qsar)\r\n\r\n# Example 9 p.403 and Figure 10.13 p. 404\r\nlibrary(AlgDesign)\r\ndesgn1<-optFederov(~quad(.),data=qsar,nTrials=15,center=TRUE, \r\n criterion=\"D\",nRepeats=40)\r\ndesgn2<-optFederov(~quad(.),data=qsar,nTrials=15,center=TRUE, \r\n criterion=\"I\",nRepeats=40)\r\nCompare2FDS(desgn1$design, desgn2$design, \"D-optimal\", \"I-optimal\", mod=2)\r\n\r\n# Example 10 p. 404\r\ndesgn2$design\r\n\r\n# Example 11 p. 406\r\nk1 <- .15; k2 <- .72; gamma0 <- 2.65; t0 <- 0.41\r\nx <- c(seq(1:25))\r\ndfdk1 <- c(rep(0, 25))\r\ndfdk2 <- c(rep(0, 25))\r\ndfdgamma0 <- c(rep(0, 25))\r\ndfdt0 <- c(rep(0, 25))\r\nfor (i in 1:25) {\r\n dfdk1[i] <- -1 * gamma0 * exp(-k1 * (x[i] - t0)) *(x[i] - t0)\r\n dfdk2[i] <-gamma0 * exp(-k2 * (x[i] - t0)) * (x[i] - t0)\r\n dfdgamma0[i] <- exp(-k1 * (x[i] - t0)) - exp( -k2 * ( x[i] - t0))\r\n dfdt0[i] <- gamma0 * exp(-k1 * (x[i] - t0)) * k1 - gamma0 * \r\n exp(-k2 * (x[i] - t0)) * k2; }\r\ngrid <- data.frame(x, dfdk1, dfdk2, dfdgamma0, dfdt0)\r\n\r\n# Example 12 p. 407\r\nlibrary(AlgDesign)\r\ndesgn2<-optFederov(~ +dfdk1+dfdk2+dfdgamma0+dfdt0,data=grid,nTrials=8,center=TRUE, criterion=\"D\",nRepeats=20)\r\ndesgn2\r\n\r\n# This additional code illustrates fitting a model to simulated data from the design\r\ndesign<-desgn2$design\r\nk1 <- .15; k2 <- .72; gamma0 <- 2.65; t0 <- 0.41\r\n# this is the simulated response\r\ndesign$y<-gamma0*(exp(-k1*(design$x-t0))-exp(-k2*(design$x-t0)))+rnorm(8,0,.05)\r\n# this is the code to fit the model\r\nmod.nls<-nls(y~gamma0*(exp(-k1*(x-t0))-exp(-k2*(x-t0))),data=design,\r\n start=list(gamma0=2.65,k1=.15,k2=.72,t0=0.41))\r\nsummary(mod.nls)\r\n\r\n# Example 13 p. 408\r\nlibrary(daewr)\r\ndata(cement)\r\nhead(cement)\r\n\r\n# Example 14 p. 408\r\nlibrary(rsm)\r\ngrout.lin <- rsm(y ~ SO(x1, x2, x3),data = cement, subset = (Block == 1))\r\nanova(grout.lin)\r\n\r\n# Example 15 p. 409\r\nlibrary(daewr)\r\ndata(Treb)\r\nhead(Treb)\r\n\r\n# Example 16 p. 410\r\nlibrary(rsm)\r\ntreb.quad <- rsm(y ~ SO(x1, x2, x3), data = Treb)\r\nsummary(treb.quad)\r\n\r\n# Example 17 p. 411 \r\nlibrary(daewr)\r\ndata(cement)\r\ngrout.quad <- rsm(y ~ Block + SO(x1,x2,x3), data = cement)\r\nsummary(grout.quad)\r\n\r\n# Example 18 p. 412 - 413\r\nlibrary(daewr)\r\ndata(Tet)\r\nmod.nln1 <-nls(Conc ~ gamma0 * (exp( -k1 * (Time - t0)) - exp( -k2 * (Time - t0))), \r\n data = Tet, start = list(gamma0 = 10, k1 = .12, k2 = .5, t0 = .5))\r\nsummary(mod.nln1)\r\n\r\n# Example 20 p. 413-414 Figure 10.15\r\nlibrary(daewr)\r\ndata(Treb)\r\nlibrary(rsm)\r\ntreb.quad <- rsm(y ~ SO(x1, x2, x3), data = Treb)\r\npar (mfrow=c(2,2))\r\ncontour(treb.quad, ~ x1+x2+x3 )\r\npar (mfrow=c(1,1))\r\n\r\n# Example 21 p. 414-415 Figure 10.16\r\npar (mfrow=c(2,2))\r\npersp(treb.quad, ~ x1+x2+x3, zlab=\"Distance\", contours=list(z=\"bottom\") )\r\npar (mfrow=c(1,1))\r\n\r\n# Example 22 p. 415-416, Figure 10.17\r\npar (mfrow=c(1,2))\r\ncontour(treb.quad, x1~x3, at=list(x2=1))\r\npersp(treb.quad, x1~x3, at=list(x2=1),zlab=\"Distance\", contours=list(z=\"bottom\"))\r\npar (mfrow=c(1,1))\r\n\r\n# Example 23 p. 418\r\n# slice at stationary point instead of coding value\r\npar (mfrow=c(2,2))\r\ncontour(treb.quad, ~ x1+x2+x3, at = xs(treb.quad) )\r\npar (mfrow=c(1,1))\r\n\r\n# Example 24 p. 419\r\nridge<-steepest(treb.quad, dist=seq(0, 1.412, by=.1), descent=FALSE)\r\nridge\r\n\r\n# Figure 10.20 p. 420\r\npar (mfrow=c(2,1))\r\nleg.txt<-c(\"A\",\"B\",\"C\")\r\nplot(ridge$dist,ridge$yhat, type=\"l\",xlab=\"radius\",ylab=\"Max. Predicted\")\r\nplot(ridge$dist,seq(1,22,by=1.5), type=\"n\", xlab=\"radius\", ylab=\"Factors\")\r\nlines(ridge$dist,ridge$A,lty=1)\r\nlines(ridge$dist,ridge$B,lty=2)\r\nlines(ridge$dist,ridge$C,lty=3)\r\nlegend(1.2,19,leg.txt,lty=c(1,2,3))\r\npar (mfrow=c(1,1))\r\n\r\n#Example 25 p. 421\r\nstart<-c(12.5,400)\r\nprod <- function(x) {\r\n time <- x[1]\r\n Temp <- x[2]\r\n k1 <- .523 * exp(-9847 * ((1/Temp - 1/400 )))\r\n k2 <- .2 * exp(-12327 * ((1/Temp - 1/400 )))\r\n f <- 132 * (exp(-k1 * time) - exp( -k2 *time)) * k1/(k1-k2)\r\n}\r\nui <- matrix(c(1, -1, 0, 0, 0, 0, 1, -1), 4, 2)\r\nci <- c(0, -25, 375, -425)\r\nconstrOptim(start, prod, NULL, ui, ci)\r\n\r\n# Figure 10.21 p. 422\r\npar (mfrow=c(1,1))\r\ntime<-seq(0,25,length=52)\r\nTemp<-seq(375,425,length=52)\r\np<-matrix(rep(0,2704),nrow=52)\r\nfor (i in 1:52) {\r\n for (j in 1:52) {\r\n k1<-.523*exp(-9847*((1/Temp[j]-1/400)))\r\n k2<-.2*exp(-12327*((1/Temp[j]-1/400)))\r\n p[i,j]<--132*(exp(-k1*time[i])-exp(-k2*time[i]))*k1/(k1-k2)\r\n }\r\n}\r\ncontour(time,Temp,p,xlab=\"Time, hrs\",ylab=\"Temp, Deg K\")\r\n\r\n# Example 26 p. 424\r\n# maximize tsr for cost <=10 cents\r\n# Note: since no R packages allow nonlinear equality constraints\r\n# I included this constraint in the tsr function by adding the \r\n# 100*maxumum of (cost -10) and zero \r\nstart<-c(100,.6,40)\r\ntsrcost<-function(x) {\r\n Temp<-x[1]\r\n Ratio<-x[2]\r\n AOPPM<-x[3]\r\n tsrcost<- -(-226+3.375*Temp+86.5*Ratio+2.646*AOPPM-.0128*Temp*Temp-17.5*Ratio*Ratio-.0121*AOPPM*AOPPM\r\n + -.3857*Ratio*Temp-.0126*AOPPM*Temp-.0333*AOPPM*Ratio)+\r\n + 100*max((.8313+1.27*Ratio+.37*Ratio*AOPPM-10),0)\r\n}\r\nui<-matrix(c(1,-1,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,1,-1),6,3)\r\nci<-c(70,-140,.5,-1.5,5,-65)\r\nconstrOptim(start,tsrcost,NULL,ui,ci)\r\n# note this minimizes tsrcost, subject to ui%*%x-ci>=0\r\n\r\n# Example 27 p. 426\r\nx<-c(0,0,0)\r\nsaPred<-function(x) 125.4106 -8.1233*x[1]+17.0266*x[2]+.4277*x[3]+2.4184*x[1]*x[2]\r\n-8.4376*x[1]*x[3]+9.0134*x[2]*x[3]+33.88054*x[1]^2+14.81976*x[2]^2+13.07001*x[3]^2\r\n\r\npvPred<-function(x) .661354-.1963*x[1]-.02016*x[2]-.00291*x[3]+.02399*x[1]*x[2]\r\n+.010327*x[1]*x[3]-.0374*x[2]*x[3]+.15126*x[1]^2+.118423*x[2]^2+.0679*x[3]^2\r\n\r\ndpPred<-function(x) 39.35608+3.19547*x[1]+.21729*x[2]-1.46979*x[3]+.58873*x[1]*x[2]\r\n-.62136*x[1]*x[3]-1.53234*x[2]*x[3]+.41413*x[1]^2-2.39408*x[2]^2-2.36399*x[3]^2\r\n\r\nlibrary(desirability)\r\nsaD<-dMax(100, 217)\r\npvD<-dMax(0.6, 1.3)\r\ndpD<-dTarget(38, 40, 42)\r\noverallD<-dOverall(saD, pvD, dpD)\r\n\r\n# Code on web page referred to on p. 426\r\nrsmOpt <- function(x, dObject, space = \"square\")\r\n{\r\n sa <- saPred(x)\r\n pv <- pvPred(x)\r\n dp <- dpPred(x)\r\n \r\n out <- predict(dObject, data.frame(sa = sa, pv = pv, dp = dp))\r\n \r\n if(space == \"circular\")\r\n {\r\n if(sqrt(sum(x^2)) > 1.0) out <- 0\r\n } else if(space == \"square\") if(any(abs(x) > 1.0)) out <- 0\r\n out\r\n}\r\n\r\n\r\nsearchGrid <- expand.grid(Mixtime = seq(-1.0, 1.0, length = 5),\r\n filTtime = seq(-1.0, 1.0, length = 5),\r\n PackMth = seq(-1.0, 1.0, length = 5))\r\nfor(i in 1:dim(searchGrid)[1])\r\n{\r\n tmp <- optim(as.vector(searchGrid[i,]),\r\n rsmOpt,\r\n dObject = overallD,\r\n space = \"square\",\r\n control = list(fnscale = -1))\r\n if(i == 1)\r\n {\r\n best <- tmp\r\n } else {\r\n if(tmp$value > best$value) best <- tmp\r\n }\r\n}\r\n\r\npredOutcomes <-c(saPred(c(-0.2924993,-1,-1)), pvPred(c(-0.2924993,-1,-1)), dpPred(c(-0.2924993,-1,-1)))\r\nprint(predOutcomes)\r\n\r\n# Example 28 p. 427\r\n#Create Blocked bbd\r\nlibrary(rsm)\r\n# four-factor design\r\nbbd(4,n0=1,randomize=FALSE)\r\n# five-factor design\r\nbbd(5,n0=3,randomize=FALSE)\r\n#Create Blocked CCD designs\r\n# two-factor design\r\nccd(2,n0=c(3,3),alpha=\"orthogonal\",randomize=FALSE)\r\n# three-factor design\r\nccd(3, n0=2,alpha=\"orthogonal\",randomize=FALSE, blocks=Block~( x1*x2*x3))\r\n# four-factor design\r\nccd(4, n0=2, alpha=\"orthogonal\",randomize=FALSE, blocks=Block~(x1*x2*x3*x4))\r\n# five-factor design\r\nccd(4, generators=(x5~x1*x2*x3*x4), n0=c(6,1),alpha=\"orthogonal\",randomize=FALSE)\r\n\r\n# Example 29 p. 428\r\nlibrary(AlgDesign)\r\nfact<-gen.factorial(levels=2,nVars=3)\r\nfact<-rbind(fact,fact)\r\ncenter<-data.frame(matrix(rep(c(0,0,0),6),ncol=3))\r\nstar<-data.frame(rbind(diag(3),-diag(3)))\r\ncand<-rbind(fact,center,star)\r\nbdesign<-optBlock(~quad(),cand,blocksizes=c(4,4,4,4,4,4,4),criterion=\"Dpc\",nRepeats=1000)\r\nbdesign\r\n\r\n# Example 30 p. 429\r\nlibrary(daewr)\r\ndata(qsar) \r\nlibrary(AlgDesign)\r\ndesgn1<-optBlock(~quad(.),qsar,blocksizes=c(4,4,4,4,4),criterion=\"Dpc\",nRepeats=1000)\r\ndesgn1\r\n\r\n# Example 31 p. 430\r\nlibrary(daewr)\r\ndata(pastry)\r\nclass(pastry$Block)\r\nlibrary(rsm)\r\nblkrsm<-rsm(y~Block+SO(x1,x2,x3), data=pastry)\r\nsummary(blkrsm)\r\n\r\n#Example 32 p. 432\r\n# REML analysis using lmer\r\nlibrary(daewr)\r\ndata(cake)\r\nlibrary(lme4)\r\nmmod<-lmer(y~x1+x2+x1:x2+x1sq+x2sq+(1|Ovenrun),data=cake)\r\nsummary(mmod)\r\n# Least Squares Analysis using rsm\r\nlibrary(rsm)\r\nmmodls<-rsm(y ~ SO(x1,x2), data=cake)\r\nsummary(mmodls)\r\n\r\n# Example 33 EESPRS page 434\r\nlibrary(\"AlgDesign\")\r\n# uses gen.factorial function from AlgDesign to create Factorial portion of the design\r\nsp<-gen.factorial(2,2,varNames=c(\"P\",\"Q\"))\r\nWp<-gen.factorial(2,2,varNames=c(\"A\",\"B\"))\r\nA<-Wp$A\r\n#stacks whole plots\r\nwp<-c(rep((1:4),each=4))\r\nA<-c(rep((Wp$A),each=4))\r\nB<-c(rep((Wp$B),each=4))\r\nFac<-cbind(wp,A,B,rbind(sp,sp,sp,sp))\r\n# Subplot Axial Portion \r\nA<-c(rep(0,4))\r\nB<-c(rep(0,4))\r\nP<-c(-2,2,0,0)\r\nQ<-c(0,0,-2,2)\r\nwp<-c(rep(5,4))\r\nspa<-cbind(wp,A,B,P,Q)\r\n# Whole Plot Axial Portion\r\nwp<-c(rep((6:9),each=4))\r\nA<-c(rep(c(-2,2,0,0),each=4))\r\nB<-c(rep(c(0,0,-2,2),each=4))\r\nP<-c(rep(0,16))\r\nQ<-c(rep(0,16))\r\nwpa<-cbind(wp,A,B,P,Q)\r\n# center points\r\nwp<-c(rep((10:11),each=4))\r\nA<-c(rep(0,8))\r\nB<-c(rep(0,8))\r\nC<-c(rep(0,8))\r\nD<-c(rep(0,8))\r\nwpc<-cbind(wp,A,B,P,Q)\r\nSPDs<-rbind(Fac,spa,wpa,wpc)\r\n############################################\r\n\r\n# Example 34 p. 438\r\nlibrary(daewr)\r\nEEw1s2( )\r\nEE15R5WP<-EEw1s2('EE15R5WP')\r\nEE15R5WP\r\n# extra example fitting model with this design\r\n# sample data\r\ny<-c(-0.714811191,-0.829505189,-0.848985975,-0.110751257,1.4710031138,-0.611644758,\r\n -1.087524003,0.8956219826,-0.130413701,-0.735548889,-0.129036864,-0.534510763,\r\n -0.004106583,0.204772326,-0.302557987)\r\nEE15R5WP<-data.frame(EE15R5WP,y)\r\ncolnames(EE15R5WP)<-c('WP','A','P','Q','y')\r\n# fit the model with \\texttt{lmer} function in the \\texttt{lme4} package\r\nmodre<-lmer(y~A+I(A^2)+(1|WP)+P+I(P^2)+Q+I(Q^2)+A:P+\r\n A:Q+P:Q,data=EE15R5WP)\r\nsummary(modre)\r\n# fit the model with the \\texttt{rsm} function in the \\texttt{rsm} package\r\nmodls<-rsm(y~SO(A,P,Q),data=EE15R5WP)\r\nsummary(modls)\r\n\r\n", "meta": {"hexsha": "f2d60794fcf4c27d42ac5468a568559f4ab0e9b2", "size": 11413, "ext": "r", "lang": "R", "max_stars_repo_path": "Samples/Chapter10.r", "max_stars_repo_name": "wilsongis/3DP_Experiments", "max_stars_repo_head_hexsha": "da9bd3b4ba1d82bac7dcfa27d86634add59db087", "max_stars_repo_licenses": ["MIT", "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": "Samples/Chapter10.r", "max_issues_repo_name": "wilsongis/3DP_Experiments", "max_issues_repo_head_hexsha": "da9bd3b4ba1d82bac7dcfa27d86634add59db087", "max_issues_repo_licenses": ["MIT", "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": "Samples/Chapter10.r", "max_forks_repo_name": "wilsongis/3DP_Experiments", "max_forks_repo_head_hexsha": "da9bd3b4ba1d82bac7dcfa27d86634add59db087", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0407124682, "max_line_length": 117, "alphanum_fraction": 0.603960396, "num_tokens": 4697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.690913790194632}} {"text": "# From JoAnn Alvarez\n\nrequire(rms)\nset.seed(1)\nage <- rnorm(200,40,12)\nsex <- factor(sample(c('female','male'),200,TRUE))\nlogit <- (sex=='male') + (age-40)/5\ny <- ifelse(runif(200) <= plogis(logit), 1, 0)\nf <- lrm(y ~ pol(age,2)*sex)\nanova(f)\n# Compare a 30 year old female to a 40 year old male\n# (with or without age x sex interaction in the model)\ncontrast(f, list(sex='female', age=30), list(sex='male', age=40))\n# Test for interaction between age and sex, duplicating anova\ncontrast(f, list(sex='female', age=30),\n list(sex='male', age=30),\n list(sex='female', age=c(40,50)),\n list(sex='male', age=c(40,50)), type='joint')\n# Duplicate overall sex effect in anova with 3 d.f.\ncontrast(f, list(sex='female', age=c(30,40,50)),\n list(sex='male', age=c(30,40,50)), type='joint')\n\n\njim <- contrast(f, list(sex = \"male\", age=30),\n list(sex = \"male\", age=40))\nprint(jim, fun = exp)\njane <- contrast(f, list(sex = c(\"male\", \"female\"), age=30),\n list(sex = c(\"male\", \"female\"), age=40))\nprint(jane, fun = exp)\n\n\n\n\n# From http://stats.stackexchange.com/questions/191063/lrm-and-orm-contrast-rms-package\n\nrequire(rms)\nset.seed(1)\nx <- factor(rbinom(100,2,0.6), labels = c(\"a\",\"b\",\"c\"), ordered = TRUE)\ny <- factor(rbinom(100,1,0.5), labels=c(\"no\",\"yes\"))\nf <- lrm(x ~ y)\ng <- orm(x ~ y)\ncoef(f); coef(g)\n\nprint(contrast(f, list(y='no'), list(y='yes')), X=TRUE)\nprint(contrast(g, list(y='no'), list(y='yes')), X=TRUE)\n\n\n", "meta": {"hexsha": "93c88fdc0f7536fa5b1e4d1e4bb85ddbdfbec47b", "size": 1499, "ext": "r", "lang": "R", "max_stars_repo_path": "SilveR/R/library/rms/tests/contrast.r", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": "SilveR/R/library/rms/tests/contrast.r", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": "SilveR/R/library/rms/tests/contrast.r", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 31.2291666667, "max_line_length": 87, "alphanum_fraction": 0.5983989326, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6909137867068029}} {"text": "=begin\n # sample-group01.rb\n\n require \"algebra\"\n e = Permutation[0, 1, 2, 3, 4]\n a = Permutation[1, 0, 3, 4, 2]\n b = Permutation[0, 2, 1, 3, 4]\n p a * b #=> [2, 0, 3, 4, 1]\n \n g = Group.new(e, a, b)\n g.complete!\n p g == PermutationGroup.symmetric(5) #=> true\n \n \n \n \n \n \n \n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "ece31ea430762f5269f78bdea0f35cfd5cb0dfe2", "size": 312, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-group01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-group01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-group01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.1818181818, "max_line_length": 47, "alphanum_fraction": 0.5064102564, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6909015550613204}} {"text": "A <- matrix(c(3,1,4,1),ncol = 2)\nmat <- A \nfor(i in 1:99){ \n\tmat <- (mat %*% A)\n}\nprint(mat)\n\n\n# inspired by:\n# https://www.youtube.com/watch?v=PFDu9oVAE-g&list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&index=13\n# 14 min, 30 seconds\n\n\nB <- matrix(c(3,0,0,2), ncol = 2)\nmat2 <- B\nfor(i in 1:99){\n\tmat2 <- (mat2 %*% B)\n}\nprint(mat2)\n\nmat2[1,1] == 3^100 #true\nmat2[2,2] == 2^100 #true\n", "meta": {"hexsha": "5e46f60e462a5e4c6602e9fcffa51d4154fe01de", "size": 375, "ext": "r", "lang": "R", "max_stars_repo_path": "matrixMult100.r", "max_stars_repo_name": "DU-ds/MiscRScripts", "max_stars_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "matrixMult100.r", "max_issues_repo_name": "DU-ds/MiscRScripts", "max_issues_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "matrixMult100.r", "max_forks_repo_name": "DU-ds/MiscRScripts", "max_forks_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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.3043478261, "max_line_length": 94, "alphanum_fraction": 0.6, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6909015510820792}} {"text": "# Master Thesis Project - Extreme Value Theory\n# Looking into the distribution of B^(n)[t]\n# Killian Martin--Horgassan\n# 23-04-2015\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"/Users/kimartin/Desktop/R_files_pdm/Tache5/randomWalk.r\")\nsource(\"/Users/kimartin/Desktop/R_files_pdm/Tache5/Epsilon_is.r\")\nsource(\"/Users/kimartin/Desktop/R_files_pdm/Tache5/brokenLine.r\")\nsource(\"/Users/kimartin/Desktop/R_files_pdm/Tache5/brownianMotion.r\")\n\n\n# Let the user enter the time horizon of the brownian motion\ncat(\"Time step ?\")\nt <- as.numeric(readline(\"t :\\n\"))\n\n# Number of trials\ncat(\"Sample size ?\")\nN <- as.numeric(readline(\"N :\\n\"))\n\n# n must be large for B^(n)[t] to be a good approximation of B[t]\nn <- 1000\n\n# Generating the Brownian Motion\nBM_vect <- rep(0,N)\nfor (i in 1:N) {\n\tBM_vect[i] <- (brownianMotion(t,1/n))[floor(n*t)]\n}\n\n# Plot the Brownian Motion\nquartz() \n\ntitle <- paste(\"Sample from a distribution\", expression(B[t]^(n)), \" with t = \", t)\n\nhist(BM_vect, main = \"Density plot\", freq = FALSE, col = \"lightgreen\")\ncurve(dnorm(x, mean = mean(BM_vect), sd = sd(BM_vect)), add = TRUE, col = \"darkblue\", lwd = 4)\nprint(var(BM_vect))\ncurve(dnorm(x, mean = 0, sd = sqrt(t)), add = TRUE, col = \"red\", lwd = 4)\n\n\n", "meta": {"hexsha": "8aa0e76ba7c1d0995a63820366fa0899697361ec", "size": 1308, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_buildingBM/brownianMotionDistribution.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_buildingBM/brownianMotionDistribution.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_buildingBM/brownianMotionDistribution.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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.829787234, "max_line_length": 94, "alphanum_fraction": 0.6949541284, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.690901542990765}} {"text": "# Hankui in SDSU\n# source(\"build_graph.r\");\n\n# build the CNN structure \n## con_indicator (2 or 4) indicates the whether convolution is used or not\n## is_shallow indicates the DNN structure\n# input_dim_x=13; input_dim_y=3;\n\nsource(\"cnn.common.r\");\n\n#************************************************************************************************************************\n## non-linear activation function\n## type = 0: RELU\n## type = 1: parametric RELU He et al. 2015\n## type = 6: RELU6\nnon_linear <- function(x, ndim=shape(100), type=1) {\n\talphas <- tf$Variable(tf$ones(1L)*0.25);\t\n\tif (type==1) {\n\t\tpos <- tf$nn$relu(x);\n\t\t# neg <- alphas * (x - abs(x)) * 0.5; ## not work\n\t\t# neg <- (x - abs(x)) * 0.5; ## work\n\t\t# neg <- tf$scalar_mul(alphas, (x - abs(x)) * 0.5 ); ## not work\n\t\tneg <- tf$multiply(alphas, (x - abs(x)) * 0.5 ); ## work\n\t\tresult <- pos + neg; \n\t} else if (type==6) {\n\t\tresult <- tf$nn$relu6(x);\n\t} else result <- tf$nn$relu(x);\n\t\n\tresult\n}\n\n\n#************************************************************************************************************************\n## a neural network unit including a linear transformation (convolution/fully connection) and a non-linear function\n## leftwidth*leftlength*n1 representing the dimension of the convolution layer to be normalized if is_norm=TRUE and is_con=TRUE\n## n1 representing the dimension of the fully connected layer to be normalized if is_norm=TRUE and is_con=FALSE\nnn_unit <- function (x_image, W_conv1, b_conv1, leftwidth=1, leftlength=11, n1=100, is_norm=TRUE, is_training=TRUE, non.linear.type=0, is_con=TRUE, is_pad=FALSE, is_max_pool=FALSE) {\n\n\t# i=1\n\t# is_training = TRUE\n\t# x_image=h_convs[[i]]\n\t# W_conv1=weightlists[[i]]\n\t# b_conv1=baislists[[i]]\n\t# leftwidth=left_widths[i]\n\t# leftlength=left_lengths[i]\n\t# n1=n_nodes[i]\n\t# is_training=is_training; \n\t# non.linear.type=non.linear.type;\n\t# is_con=TRUE\n\t# is_pad=FALSE\n\n\t\n\tif (is_norm) {\n\t\tif (is_con) { \n\t\t\th_cov_nopad_1 <- conv2d_no_pad(x_image, W_conv1, is_pad); \n\t\t\th_batch_1 <- batch_norm_wrapper(h_cov_nopad_1, is_training, ndim=shape(leftwidth,leftlength,n1) ); \n\t\t\th_conv1 <- non_linear(h_batch_1, type=non.linear.type);\n\t\t} else { \n\t\t\th_fc_last <- tf$matmul(x_image, W_conv1); \n\t\t\th_batch_last <- batch_norm_wrapper(h_fc_last, is_training, ndim=shape(n1) ); \n\t\t\th_conv1 <- non_linear(h_batch_last, type=non.linear.type);\n\t\t}\n\t\t# h_conv1 <- tf$nn$relu6(h_batch_1);\n\t} else {\n\t\tif (is_con) { \n\t\t\th_cov_nopad_1 <- conv2d_no_pad(x_image, W_conv1, is_pad) + b_conv1; \n\t\t\th_conv1 <- non_linear(h_cov_nopad_1, type=non.linear.type);\n\t\t} else {\n\t\t\th_cov_nopad_1 <- tf$matmul(x_image, W_conv1) + b_conv1; \n\t\t\th_conv1 <- non_linear(h_cov_nopad_1, type=non.linear.type);\n\t\t}\n\t}\n\tif (is_max_pool==TRUE) {\n\t\th_conv1_pull <- max_pool_2x2(h_conv1);\n\t\th_conv1 <- h_conv1_pull;\n\t} else if (is_max_pool==2) {\n\t\t# print(\"Average pooling has been used \\n\");\n\t\th_conv1_pull <- avg_pool_2x2(h_conv1);\n\t\t# h_conv1_pull <- max_pool_2x2(h_conv1);\n\t\t# h_conv1_pull <- max_pool_1x2(h_conv1);\n\t\th_conv1 <- h_conv1_pull;\n\t}\n\t# h_pool1_in <- max_pool_1x2(h_conv1);\n\th_conv1\n}\n\n#************************************************************************************************************************\n## global variables for building graph\nmax_depth <- 21; \nweightlists <<- vector(\"list\", max_depth); \nbaislists <<- vector(\"list\", max_depth); \n\n#************************************************************************************************************************\n## build the graph for training or testing\n## con_indicator (2 or 4) indicates the whether convolution is used or not\n## is_shallow indicates the DNN structure\n# is_training=TRUE;\n# input_dim_x=13; input_dim_y=3;\nbuild_graph <- function (con_indicator, is_training=TRUE, x, input_dim_x, input_dim_y, input_dim_z=1L, is_norm=TRUE, is_shallow=TRUE) {\n\n\tinput_dim_stacked <- input_dim_x*input_dim_y*input_dim_z;\n\tnon.linear.type <- 6;\n\tnon.linear.type <- 1;\n\tnon.linear.type <- 0;\n\tcat(\"\\tbuild_graph with non.linear.type\", non.linear.type, \"\\n\");\n\t## ***************************************\n\t## option 2: 2d filter followed by a fully connected layer\n\tisdim <- FALSE;\n\t# isdim <- TRUE;\n\tn_nodes <- vector(mode=\"integer\", length=max_depth);\n\tdepth <<- 4;\n\tconv_depth <- depth-2;\n\t# n1 <- 0L; n2 <- 0L; n3 <- 0L; n4 <- 0L; n5 <- 0L; n6 <- 0L; n7 <- 0L;\n\tif (con_indicator==2) {\n\t\t# left_lengths <- vector(mode=\"integer\", length=max_depth);\n\t\t## dimension left after convolution \n\t\tleft_lengths <- rep(1L, max_depth);\n\t\tleft_widths <- left_lengths;\n\t\t\n\t\tcon_dims <- rep(1L, max_depth);\n\t\tcon_dim2 <- rep(1L, max_depth);\n\t\t\n\t\tcon_dims[1 ] <- 3;\n\t\tcon_dim2[1:6] <- 3;\n\t\t\n\t\tn_nodes[1] <- 64L;\n\t\tn_nodes[2] <- 128L;\n\t\tn_nodes[3] <- 256L; \n\t\t# n_nodes[1] <- 128L;\n\t\t# n_nodes[2] <- 256L;\n\t\t# n_nodes[3] <- 1024L; ## tested on May 23 2018 for simplified VGG accuracy\n\t\tleft_lengths[1] <- 11L;\n\t\tleft_lengths[2] <- 9L;\n\t\t# left_lengths[3] <- 7L; \t\t\n\t\t\n\t\tif (is_shallow==FALSE) {\n\t\t\tdepth <<- 8;\n\t\t\tconv_depth <- depth-2;\n\t\t\t\n\t\t\tleft_lengths[1] <- 11L;\n\t\t\tleft_lengths[2] <- 9L;\n\t\t\tleft_lengths[3] <- 7L; \n\t\t\tleft_lengths[4] <- 5L; \n\t\t\tleft_lengths[5] <- 3L; \n\t\t\tleft_lengths[6] <- 1L; \n\t\t\t\n\t\t\tn_nodes[1] <- 128L;\n\t\t\tn_nodes[1] <- 64L; ## revised on Nov 1 2018\n\t\t\tn_nodes[2] <- 128L;\n\t\t\tn_nodes[3] <- 256L;\n\t\t\tn_nodes[4] <- 256L;\n\t\t\tn_nodes[5] <- 512L;\n\t\t\tn_nodes[6] <- 512L;\n\t\t\tn_nodes[7] <- 1024L; \n\t\t} else if (is_shallow==5) {\n\t\t\tdepth <<- 19;\n\t\t\tconv_depth <- depth-3;## note this has been changed from depth-2 to depth-3 on June 20, 2018\n\t\t\tleft_widths[1:1 ] <- 3;\n\t\t\t\n\t\t\tcon_dims[1:2 ] <- 3;\n\t\t\tcon_dim2[1:17] <- 3;\n\t\t\t\t\n\t\t\tleft_lengths[1 ] <- 13L;\n\t\t\tleft_lengths[2 ] <- 11L;\n\t\t\tleft_lengths[3 ] <- 11L; \n\t\t\tleft_lengths[4 ] <- 9L; \n\t\t\tleft_lengths[5 ] <- 9L; \n\t\t\tleft_lengths[6 ] <- 9L; \n\t\t\tleft_lengths[7 ] <- 9L; \n\t\t\tleft_lengths[8 ] <- 7L; \n\t\t\tleft_lengths[9 ] <- 7L; \n\t\t\tleft_lengths[10] <- 7L; \n\t\t\tleft_lengths[11] <- 5L; \n\t\t\tleft_lengths[12] <- 5L; \n\t\t\tleft_lengths[13] <- 5L; \n\t\t\tleft_lengths[14] <- 3L; \n\t\t\tleft_lengths[15] <- 3L; \n\t\t\t# left_lengths[16] <- 3L; ## NOTE THAT THIS HAS BEEN CHANGED FROM 1 to 3\n\t\t\tleft_lengths[16] <- 1L; ## NOTE THAT THIS HAS BEEN CHANGED FROM 3 to 1 on June 20, 2018\n\t\t\tleft_lengths[17] <- 1L; \n\n\t\t\tn0 <- 64 ; n_nodes[ 1] <- n0; n_nodes[ 2] <- n0; \n\t\t\tn0 <- 128 ; n_nodes[ 3] <- n0; n_nodes[ 4] <- n0; \n\t\t\tn0 <- 256 ; n_nodes[ 5] <- n0; n_nodes[ 6] <- n0; n_nodes[ 7] <- n0; n_nodes[ 8] <- n0; \n\t\t\tn0 <- 512 ; n_nodes[ 9] <- n0; n_nodes[10] <- n0; n_nodes[11] <- n0; n_nodes[12] <- n0; n_nodes[13] <- n0; n_nodes[14] <- n0; n_nodes[15] <- n0; n_nodes[16] <- n0; \n\t\t\tn0 <- 1024; n_nodes[17] <- n0; n_nodes[18] <- n0; \n\t\t}\n\t\t\n\t\t# is_use_pooling = 2; \n\t\t# is_use_pooling = TRUE; \n\t\tis_use_pooling = FALSE; \n\t\tif (is_use_pooling>=1) {\n\t\t\tcon_dims[1:2] <- 3;\n\t\t\tcon_dim2[1:6] <- 3;\n\t\t\t\n\t\t\tn_nodes[1] <- 64L;\n\t\t\tn_nodes[2] <- 128L;\n\t\t\tn_nodes[3] <- 256L; \n\t\t\tleft_lengths[1] <- 13L;\n\t\t\tleft_lengths[2] <- 7L;\n\t\t\tleft_lengths[3] <- 4L;\n\t\t\tleft_widths[1] <- 3L;\n\t\t\tleft_widths[2] <- 2L;\n\t\t\tleft_widths[3] <- 1L;\n\t\t\t\n\t\t\tif (is_shallow==FALSE) {\n\t\t\t\tdepth <<- 7;\n\t\t\t\tconv_depth <- depth-2;\n\t\t\t\tcon_dims[1:3] <- 3;\n\t\t\t\tcon_dim2[1:5] <- 3;\n\t\t\t\t\n\t\t\t\tleft_lengths[1] <- 13L;\n\t\t\t\tleft_lengths[2] <- 7L;\n\t\t\t\tleft_lengths[3] <- 4L;\n\t\t\t\tleft_lengths[4] <- 2L;\n\t\t\t\tleft_lengths[5] <- 1L;\n\t\t\t\t\n\t\t\t\tleft_widths[1] <- 3L;\n\t\t\t\tleft_widths[2] <- 2L;\n\t\t\t\tleft_widths[3] <- 1L;\n\t\t\t\t\n\t\t\t\tn_nodes[1] <- 64L;\n\t\t\t\tn_nodes[2] <- 128L;\n\t\t\t\tn_nodes[3] <- 256L;\n\t\t\t\tn_nodes[4] <- 256L;\n\t\t\t\tn_nodes[5] <- 512L;\n\t\t\t\tn_nodes[6] <- 1024L; \n\t\t\t} else if (is_shallow==5) {\n\t\t\t\tdepth <<- 16;\n\t\t\t\tconv_depth <- depth-3;## note this has been changed from depth-2 to depth-3 on June 20, 2018\n\t\t\t\t\n\t\t\t\tcon_dims[1:7 ] <- 3;\n\t\t\t\tcon_dim2[1:13] <- 3;\n\t\t\t\t\t\n\t\t\t\tleft_lengths[1 ] <- 13L;\n\t\t\t\tleft_lengths[2 ] <- 13L;\n\t\t\t\tleft_lengths[3 ] <- 13L;\n\t\t\t\tleft_lengths[4 ] <- 7L;\n\t\t\t\tleft_lengths[5 ] <- 7L;\n\t\t\t\tleft_lengths[6 ] <- 7L; \n\t\t\t\tleft_lengths[7 ] <- 4L; \n\t\t\t\tleft_lengths[8 ] <- 4L;\n\t\t\t\tleft_lengths[9 ] <- 4L;\n\t\t\t\tleft_lengths[10] <- 2L;\n\t\t\t\tleft_lengths[11] <- 2L;\n\t\t\t\tleft_lengths[12] <- 2L;\n\t\t\t\tleft_lengths[13] <- 1L; \n\t\t\t\t\n\t\t\t\t\n\t\t\t\tleft_widths[1 ] <- 3L;\n\t\t\t\tleft_widths[2 ] <- 3L;\n\t\t\t\tleft_widths[3 ] <- 3L;\n\t\t\t\tleft_widths[4 ] <- 2L;\t\n\t\t\t\tleft_widths[5 ] <- 2L;\n\t\t\t\tleft_widths[6 ] <- 2L;\n\t\t\t\tleft_widths[7 ] <- 1L;\n\n\t\t\t\t# left_lengt14hs[1 ] <- 13L;\n\t\t\t\t# left_lengths[2 ] <- 11L;\n\t\t\t\t# left_lengths[3 ] <- 11L; \n\t\t\t\t# left_lengths[4 ] <- 9L; \n\t\t\t\t# left_lengths[5 ] <- 9L; \n\t\t\t\t# left_lengths[6 ] <- 9L; \n\t\t\t\t# left_lengths[7 ] <- 9L; \n\t\t\t\t# left_lengths[8 ] <- 7L; \n\t\t\t\t# left_lengths[9 ] <- 7L; \n\t\t\t\t# left_lengths[10] <- 7L; \n\t\t\t\t# left_lengths[11] <- 5L; \n\t\t\t\t# left_lengths[12] <- 5L; \n\t\t\t\t# left_lengths[13] <- 5L; \n\t\t\t\t# left_lengths[14] <- 3L; \n\t\t\t\t# left_lengths[15] <- 3L; \n\t\t\t\t# left_lengths[16] <- 1L; ## NOTE THAT THIS HAS BEEN CHANGED FROM 3 to 1 on June 20, 2018\n\t\t\t\t# left_lengths[17] <- 1L; \n\n\t\t\t\tn0 <- 64 ; n_nodes[ 1] <- n0; n_nodes[ 2] <- n0; \n\t\t\t\tn0 <- 128 ; n_nodes[ 3] <- n0; n_nodes[ 4] <- n0; \n\t\t\t\tn0 <- 256 ; n_nodes[ 5] <- n0; n_nodes[ 6] <- n0; n_nodes[ 7] <- n0; \n\t\t\t\tn0 <- 512 ; n_nodes[ 8] <- n0; n_nodes[ 9] <- n0; n_nodes[10] <- n0; n_nodes[11] <- n0; n_nodes[12] <- n0; n_nodes[13] <- n0; \n\t\t\t\tn0 <- 1024; n_nodes[14] <- n0; n_nodes[15] <- n0;\n\t\t\t}\n\t\t} ## pooling is true\n\t\t\n\t\t## weights and bias\n\t\tfor (i in 1:depth) {\n\t\t\tscale_factor <- 2;\n\t\t\tif (i==1) {\n\t\t\t\t# weightlists[[i]] <- weight_variable(shape(con_dims[i], con_dim2[i], 1, n_nodes[i]), stddev=sqrt(scale_factor/(con_dims[i]*con_dim2[i]*n_nodes[i])) );\n\t\t\t\tweightlists[[i]] <- weight_variable(shape(con_dims[i], con_dim2[i], 1, n_nodes[i]), stddev=sqrt(scale_factor/(con_dims[i]*con_dim2[i])) );\n\t\t\t\tbaislists [[i]] <- bias_variable(shape(1, left_lengths[i], n_nodes[i]) );\n\t\t\t} else if (i<=conv_depth) {\n\t\t\t\tweightlists[[i]] <- weight_variable(shape(con_dims[i], con_dim2[i], n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/(con_dims[i]*con_dim2[i]*n_nodes[i])) );\n\t\t\t\tbaislists [[i]] <- bias_variable(shape(1, left_lengths[i], n_nodes[i]) );\n\t\t\t} else if (i==(conv_depth+1) ) { ## last convolution layer\n\t\t\t\tconcatenation <- left_widths[i-1] * left_lengths[i-1];\n\t\t\t\tif (is_use_pooling>=1) concatenation <- ceiling(left_widths[i-1]/2) * ceiling(left_lengths[i-1]/2); ## max pool is used \n\t\t\t\t# weightlists[[i]] <- weight_variable(shape(1 * left_lengths[i-1] * n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/(1*1*n_nodes[i])) );\n\t\t\t\tweightlists[[i]] <- weight_variable(shape(concatenation * n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/(1*1*n_nodes[i])) );\n\t\t\t\tbaislists [[i]] <- bias_variable(shape(1, n_nodes[i]) );\n\t\t\t} else if (i<=(depth-1) ) { ## fully connected layers \n\t\t\t\t# concatenation <- left_widths[i-1] * left_lengths[i-1];\n\t\t\t\t# if (is_use_pooling) concatenation <- ceiling(left_widths[i-1]/2) * ceiling(left_lengths[i-1]/2); ## max pool is used \n\t\t\t\t# weightlists[[i]] <- weight_variable(shape(1 * left_lengths[i-1] * n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/(1*1*n_nodes[i])) );\n\t\t\t\tweightlists[[i]] <- weight_variable(shape(n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/(1*1*n_nodes[i])) );\n\t\t\t\tbaislists [[i]] <- bias_variable(shape(1, n_nodes[i]) );\t\t\t\n\t\t\t} else {\n\t\t\t\tW_fc_n <- weight_variable(shape(n_nodes[i-1], classn), stddev=sqrt(scale_factor/(1*1*n_nodes[i-1])) ); \n\t\t\t\tb_fc_n <- bias_variable(shape(classn) );\n\t\t\t\tweightlists[[i]] <- W_fc_n; \n\t\t\t\tbaislists [[i]] <- b_fc_n; \n\t\t\t}\n\t\t}\n\t\t\n\t\t## convolution\n\t\th_conv0 <- tf$reshape(x, shape(-1L, input_dim_y, input_dim_x, input_dim_z));\n\t\t\n\t\th_convs <- list(); \n\t\th_convs[[1]] <- h_conv0; \n\t\tif (is_use_pooling==FALSE) { ## pooling is NOT used\n\t\t\tif (is_shallow<5) {\n\t\t\t\tfor (i in 1:conv_depth)\n\t\t\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE); \n\t\t\t} else {\n\t\t\t\tfor (i in 1 :1 )\n\t\t\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=TRUE);\n\t\t\t\tfor (i in 2:conv_depth)\n\t\t\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=(left_lengths[i-1]==left_lengths[i]) );\n\t\t\t}\n\t\t} else { ## pooling is used is_max_pool = if (left_widths[i-1]>1 && left_lengths[i-1]>1) { TRUE } else if (left_widths[i-1]==1 && left_lengths[i-1]>1) {2} else {FALSE}\n\t\t\t\t## revised on Aug 10 2019 for pooling is true \n\t\t\tfor (i in 1:conv_depth) { \n\t\t\t\t# is_max_pool = if (left_widths[i-1]>1 && left_lengths[i-1]>1) { TRUE } else if (left_widths[i-1]==1 && left_lengths[i-1]>1) {2} else {FALSE};\n\t\t\t\t# is_max_pool = if (left_lengths[i]==left_lengths[i+1]) {FALSE} else { if (left_widths[i]>1 && left_lengths[i]>1) { TRUE } else if (left_widths[i]==1 && left_lengths[i]>1) {2} else {FALSE} };\n\t\t\t\tis_max_pool <- (left_lengths[i]!=left_lengths[i+1]);\n\t\t\t\tif (is_max_pool && is_use_pooling==2) is_max_pool <- 2;\n\t\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=TRUE, is_max_pool=is_max_pool); \n\t\t\t}\n\t\t}\n\t\t## fully connected layer\n\t\t# h_pool2_flat <- tf$reshape(h_convs[[conv_depth+1]], shape(-1L, 1 * left_lengths[conv_depth] * n_nodes[conv_depth]));\n\t\th_pool2_flat <- tf$reshape(h_convs[[conv_depth+1]], shape(-1L, concatenation*n_nodes[conv_depth]));\n\t\th_convs[[conv_depth+1]] <- h_pool2_flat; \n\t\t\n\t\tfor (i in (conv_depth+1):(depth-1) ) \n\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftlength=left_lengths[i], n1=n_nodes[i], is_norm=is_norm, is_training=is_training, non.linear.type=non.linear.type, is_con=FALSE); \n\n\t\t\n\t\tif (isdim) {\n\t\t\tcat(\"W_fc_n: \") ; get_dim(W_fc_n);\n\t\t\tcat(\"b_fc_n: \") ; get_dim(b_fc_n);\n\t\t\tcat(\"y_conv: \") ; get_dim(y_conv);\n\t\t\tstop(\"Stop because of isdim CHECK\");\n\t\t}\n\t\t\n\t}\n\n\t## ***************************************\n\t## option 4: only contain fully connected layers\n\tif (con_indicator==4) {\n\t\tconv_depth <- 0;\n\t\t## ***************************************\n\t\t## option 4: only one filter is applied\n\t\tif (is_shallow==TRUE) {\n\t\t\tn0 <- 256L;\n\t\t\tn1 <- 512L;\n\t\t\tnn <- 512L; ## S2: z=256; x=512; 39*z+ z* x + x* x + x* 15 (410880): ?\n\t\t\tn_nodes[1] <- n0;\n\t\t\tn_nodes[2] <- n1;\n\t\t\tn_nodes[3] <- n1;\n\t\t} else if (is_shallow==FALSE) {\n\t\t\tdepth <<- 8; \n\t\t\tn0 <- 256L;\n\t\t\tn1 <- 512L;\n\t\t\tnn <- 1024L; ## S2: z=256; x=512; y=1024L; 39*x + x* x + x* x + x* x + x* x + x* y + y*y + y*15 (2656768): 84.5174%\n\t\t\t##S3: z=256L; x=512L; y=1024L; 39*z + z* z + z* z + z* x + x* x + x* y + y*y + y*15 (2122496)\n\n\t\t\tn_nodes[1] <- n0;\n\t\t\tn_nodes[2] <- n0;\n\t\t\tn_nodes[3] <- n0;\n\t\t\tn_nodes[4] <- n1;\n\t\t\tn_nodes[5] <- n1;\n\t\t\tn_nodes[6] <- nn;\n\t\t\tn_nodes[7] <- nn; \n\t\t} else {\n\t\t\tdepth <<- 19;\n\t\t\tn0 <- 64 ; n_nodes[ 1] <- n0; n_nodes[ 2] <- n0; \n\t\t\tn0 <- 128 ; n_nodes[ 3] <- n0; n_nodes[ 4] <- n0; \n\t\t\tn0 <- 256 ; n_nodes[ 5] <- n0; n_nodes[ 6] <- n0; n_nodes[ 7] <- n0; n_nodes[ 8] <- n0; \n\t\t\tn0 <- 512 ; n_nodes[ 9] <- n0; n_nodes[10] <- n0; n_nodes[11] <- n0; n_nodes[12] <- n0; n_nodes[13] <- n0; n_nodes[14] <- n0; n_nodes[15] <- n0; n_nodes[16] <- n0; \n\t\t\t# n0 <- 4096; n_nodes[17] <- n0; n_nodes[18] <- n0; \n\t\t\tn0 <- 1024; n_nodes[17] <- n0; n_nodes[18] <- n0; \n\t\t}\n\n\t\t## weights and bias\n\t\twidths0 <- input_dim_stacked; \n\t\t# weightlists <- list(); \n\t\t# baislists <- list(); \n\t\tfor (i in 1:depth) {\n\t\t\tscale_factor <- 2;\n\t\t\tif (i==1) {\n\t\t\t\tweightlists[[i]] <<- weight_variable(shape(widths0, n_nodes[i]), stddev=sqrt(scale_factor/n_nodes[i]) );\n\t\t\t\tbaislists [[i]] <<- bias_variable(shape(n_nodes[i]) );\n\t\t\t} else if (i<=depth-1) {\n\t\t\t\tweightlists[[i]] <<- weight_variable(shape(n_nodes[i-1], n_nodes[i]), stddev=sqrt(scale_factor/n_nodes[i]) );\n\t\t\t\tbaislists [[i]] <<- bias_variable(shape(n_nodes[i]) );\n\t\t\t} else {\n\t\t\t\tW_fc_n <- weight_variable(shape(n_nodes[i-1], classn), stddev=sqrt(scale_factor/n_nodes[i-1]) ); \n\t\t\t\tb_fc_n <- bias_variable(shape(classn) );\n\t\t\t\tweightlists[[i]] <<- W_fc_n; \n\t\t\t\tbaislists [[i]] <<- b_fc_n; \n\t\t\t}\n\t\t}\n\n\t\t## convolution / non-linear functions\n\t\th_conv0 <- tf$cast(tf$reshape(x, shape(-1L, widths0)), tf$float32);\n\t\t\n\t\th_convs <- list(); \n\t\th_convs[[1]] <- h_conv0; \n\t\tfor (i in 1:(depth-1) )\n\t\t\th_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftlength=left_lengths[i], n1=n_nodes[i], is_norm=is_norm, is_training=is_training, non.linear.type=non.linear.type, is_con=FALSE); \n\n\t\t## softmax layer\n\t\th_fc_n_drop <- h_convs[[depth]]; \n\t\t\n\t\t## final layer\n\t\t# y_conv <- tf$nn$softmax(tf$matmul(h_fc_n_drop, W_fc_n) + b_fc_n);\n\t\t\n\t\tif (isdim) {\n\t\t\tcat(\"W_fc2 : \") ; get_dim(W_fc2 );\n\t\t\tcat(\"b_fc2 : \") ; get_dim(b_fc2 );\n\t\t\tcat(\"y_conv: \") ; get_dim(y_conv);\n\t\t\tstop(\"Stop because of isdim CHECK\");\n\t\t}\n\t}\n\t\n\t# last_active <- tf$matmul(h_convs[[depth]], W_fc_n); \n\tlast_active <- tf$matmul(h_convs[[depth]], W_fc_n) + b_fc_n; \n\tlast_mean <- tf$reduce_mean(last_active, 1L);\n\ty_conv <- tf$nn$softmax(last_active);\n\t\n\t## regularizer\n\tregularizer <- 0;\n\t# for (i in 1:(depth-1) ) {\n\t\t# if (i<=conv_depth) {\n\t\t\t# regularizer <- regularizer+tf$nn$l2_loss(weightlists[[i]]); \n\t\t# } else regularizer <- regularizer+10*tf$nn$l2_loss(weightlists[[i]]); \n\t# }\n\t# regularizer <- regularizer+10*tf$nn$l2_loss(W_fc_n); \n\n\tfor (i in 1:(depth-1) ) {\n\t\tregularizer <- regularizer+tf$nn$l2_loss(weightlists[[i]]); \n\t}\n\tregularizer <- regularizer+tf$nn$l2_loss(W_fc_n); \n\t\n\t## print information\n\tcat(\"\\tcon_indicator =\", con_indicator, \"depth =\", depth, \"conv_depth =\", conv_depth, \"is_use_pooling =\", is_use_pooling, \"\\n\\t\");\n\tfor (i in 1:(depth-1) ) cat(\"width[\", i, \"] = \", n_nodes[i], \" \", sep=\"\");\n\tcat(\"\\n\");\n\t# if (con_indicator==2) cat(\"\\t\\tn3 = \", n3, \"n4 = \", n4, \"n5 = \", n5, \"n6 = \", n6, \"\\n\"); \n\n\tlist(\"y_conv\"=y_conv, \"regularizer\"=regularizer, \"last_active\"=last_active, last_mean=\"last_mean\")\n}\n\n\t\t\t# if (is_shallow<6) {\n\t\t\t\t# i = 1;\n\t\t\t\t# is_max_pool = TRUE; \n\t\t\t\t# h_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=TRUE, is_max_pool=is_max_pool); \n\t\t\t# } else {\n\t\t\t\t# for (i in 1 :1 )\n\t\t\t\t\t# h_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=TRUE);\n\t\t\t\t# for (i in 2:conv_depth)\n\t\t\t\t\t# h_convs[[i+1]] <- nn_unit(h_convs[[i]], weightlists[[i]], baislists[[i]], leftwidth=left_widths[i], leftlength=left_lengths[i], n1=n_nodes[i], is_training=is_training, is_con=TRUE, is_pad=(left_lengths[i-1]==left_lengths[i]) );\n\t\t\t# }\n", "meta": {"hexsha": "6844ee95c1d30441bddb9ee69882c0ac1398f6a5", "size": 18852, "ext": "r", "lang": "R", "max_stars_repo_path": "build_graph.r", "max_stars_repo_name": "hankui/cnn_time_series", "max_stars_repo_head_hexsha": "b35a3430f6a2326cb44f126e983112123f6babb2", "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": "build_graph.r", "max_issues_repo_name": "hankui/cnn_time_series", "max_issues_repo_head_hexsha": "b35a3430f6a2326cb44f126e983112123f6babb2", "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": "build_graph.r", "max_forks_repo_name": "hankui/cnn_time_series", "max_forks_repo_head_hexsha": "b35a3430f6a2326cb44f126e983112123f6babb2", "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": 39.7721518987, "max_line_length": 235, "alphanum_fraction": 0.5952153618, "num_tokens": 6856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6908320822233978}} {"text": "library(FinancialMath)\n\n# kapital pozostajacy do splacenia\nkapital <- 45058.08\n\n# liczba pozostalych rat\nlba_pozostalych_rat <- 185\n\n# oprocentowanie\noprocentowanie <- c(2.35, 2.45)\n\n# liczba dni w jakich obowiazywalo oprocentowanie\n# 20.01.2021 ZMIANA WYSOKOSCI ODSETEK\ndni_oprocentowania <- c(20, 11)\n\n##########################################\n#\n# rata #175\n#\n##########################################\n\noprocentowanie <- oprocentowanie / 100\nrata <- amort.period(Loan = kapital, n = lba_pozostalych_rat, i = oprocentowanie[2], ic = 12, pf = 12)\nrata <- round(rata[2], digits = 2)\n\n# obliczanie raty kapitalowej przy zalozeniu ze przez caly okres obowiazuje oprocentowanie docelowe\nrata_odsetkowa_doc <- round(kapital * sum(dni_oprocentowania) / 365 * oprocentowanie[2], digits = 2)\nrata_kapitalowa <- rata - rata_odsetkowa_doc\n\n# oblicanie faktycznej raty odsetkowej\nrata_odsetkowa <- kapital * dni_oprocentowania / 365 * oprocentowanie\nrata_odsetkowa <- round(sum(rata_odsetkowa), digits = 2)\n\ncat(\"rata_kapitalowa[175] = \", rata_kapitalowa, \"\\n\")\ncat(\"rata_odsetkowa[175] = \", rata_odsetkowa, \"\\n\")\ncat(\"rata[175] = \", rata_kapitalowa + rata_odsetkowa, \"\\n\")\ncat(\"rata[176+] = \", rata, \"\\n\")", "meta": {"hexsha": "114e4c20246d6619fbe8ba440730f78032f7c00e", "size": 1212, "ext": "r", "lang": "R", "max_stars_repo_path": "rata_175_mB.r", "max_stars_repo_name": "MaciejRydzy/mBank", "max_stars_repo_head_hexsha": "3de55628c189fcc8aff41f7127c18d6b9725c47d", "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": "rata_175_mB.r", "max_issues_repo_name": "MaciejRydzy/mBank", "max_issues_repo_head_hexsha": "3de55628c189fcc8aff41f7127c18d6b9725c47d", "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": "rata_175_mB.r", "max_forks_repo_name": "MaciejRydzy/mBank", "max_forks_repo_head_hexsha": "3de55628c189fcc8aff41f7127c18d6b9725c47d", "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.7567567568, "max_line_length": 102, "alphanum_fraction": 0.6782178218, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6907884649381243}} {"text": "# ----------------------------------------\n# App Title: Benford's Law and Sequences\n# Author: Jimmy Doi\n# ----------------------------------------\nlibrary(shinyIncubator)\n\nshinyUI(navbarPage(\"Benford's Law: Sequences\",\n\n###################################################################################################\n## tabPanel: Additive Sequence ##\n###################################################################################################\ntabPanel(\"(1) Additive Sequence\",\n fluidPage( \n tags$head(tags$link(rel = \"icon\", type = \"image/x-icon\", href = \n \"https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico\")), \n\n progressInit(),\n \n # Give the page a title\n h3(\"Benford's Law: Additive Sequence\"),\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(\"Consider a sequence of numbers where we fix the initial two numbers and then the\n value of each subsequent number is the sum of the previous two. We will call this an\",\n tags$b(\"additive sequence.\"),\n \"When the initial two numbers are both 1 then this yields the famous Fibonacci sequence. \n If you only consider the first digit of each number in an additive sequence and examine its distribution,\n is it the case that it closely follows \", \n HTML(\"Benford's Law?\"), \n \"This app generates an additive sequence, for a given length and initial sequence numbers, \n and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law\",\n style=\"font-size:11pt\"),\n HTML(\"
\"),\n \n # Generate a row with a sidebar\n fluidRow( \n \n column(4,wellPanel(\n \n sliderInput(\"seq1\", \n label = h5(\"First Sequence Number\"),\n min = 1, max = 9, value = 1, step=1),br(),\n \n sliderInput(\"seq2\", \n label = h5(\"Second Sequence Number\"),\n min = 1, max = 9, value = 1, step=1),br(),\n \n sliderInput(\"length\", \n label = h5(HTML(\"Length of sequence (n)\")),\n min = 150, max = 1000, value = 150, step=50),br(),\n \n br(), br(), br(), br(), \n \n div(\"Shiny app by\", \n 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\", \n a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\", \n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n \n div(\"Shiny source files:\",\n 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 )),\n column(8,\n div(span(tags$b(\"First 50 numbers in the sequence (first digit in\"),style=\"font-size:9pt\"),\n span(\n span(\"red\",style=\"font-size:9pt; color:red; font-weight:bold\"),tags$b(\"):\",\n conditionalPanel(\"input.seq1==1 & input.seq2==1\", \n span(HTML(\"   \"),\"[Fibonacci sequence]\",\n style=\"text-align: right;color:blue;font-size:9pt;display:inline-block\"),\n style=\"text-align: right;font-size:0pt;display:inline-block;\"), \n conditionalPanel(\"input.seq1==2 & input.seq2==1\",\n span(HTML(\"   \"),\"[Lucas sequence]\",\n style=\"text-align: right;color:blue;font-size:9pt;display:inline-block\"),\n style=\"text-align: right;font-size:0pt;display:inline-block;\"),style=\"font-size:9pt\")),\n style=\"font-size:0pt\"),\n div(\n div(span(textOutput(\"num.1a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.1b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.2a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.2b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.3a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.3b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.4a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.4b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.5a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.5b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.6a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.6b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.7a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.7b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.8a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.8b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.9a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.9b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.10a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.10b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.11a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.11b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.12a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.12b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.13a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.13b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.14a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.14b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.15a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.15b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.16a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.16b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.17a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.17b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.18a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.18b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.19a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.19b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.20a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.20b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.21a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.21b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.22a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.22b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.23a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.23b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.24a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.24b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.25a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.25b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.26a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.26b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.27a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.27b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.28a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.28b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.29a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.29b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.30a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.30b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.31a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.31b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.32a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.32b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.33a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.33b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.34a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.34b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.35a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.35b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.36a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.36b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.37a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.37b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.38a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.38b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.39a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.39b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.40a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.40b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.41a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.41b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.42a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.42b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.43a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.43b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.44a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.44b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.45a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.45b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.46a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.46b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.47a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.47b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.48a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.48b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.49a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.49b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"num.50a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"num.50b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n span(\"\",style=\"font-size: 9pt\"),style=\"display:inline-block\"),\n style=\"font-size:0;\"),\n \n div(span(\"[Sequence has \",style=\"text-align: right;font-size:9pt;display:inline-block\"),\n span(HTML(\" \"),style=\"text-align: right;font-size:9pt\"),\n span(textOutput(\"textlength\"),style=\"text-align: right;font-size:9pt;display:inline-block;color:teal\"),\n span(HTML(\" \"),style=\"text-align: right;font-size:9pt\"),\n span(\"numbers total]\",style=\"text-align: right;font-size:9pt;display:inline-block\"),\n style=\"text-align: right;font-size:0pt;display:inline-block;\"),\n \n HTML(\"
\"),\n \n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test\")),\n verbatimTextOutput(\"goodness\")),\n column(8,\n plotOutput(\"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###################################################################################################\n## tabPanel: Power Sequence ##\n###################################################################################################\ntabPanel(\"(2) Power Sequence\",\n fluidPage( \n \n # Give the page a title\n h3(\"Benford's Law: Power Sequence\"),\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(\"Consider a sequence of the form\", \n HTML(\"b1, b2, …, b n, \"),\n \"where \", tags$em(\"b\"), \"is called the base. \n We will call this a \", HTML(\"power sequence.\"), \"\n If you only consider the first digit of each number in a power sequence and examine its distribution,\n is it the case that it closely follows \", \n HTML(\"Benford's Law?\"), \n \"This app generates the power sequence, for a given\", HTML(\"b and n,\"), \n \"and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law.\",\n style=\"font-size:11pt\"),\n HTML(\"
\"),\n \n fluidRow( \n \n column(4,wellPanel(\n \n sliderInput(\"pow.base\", \n label = h5(HTML(\"Base value (b)\")),\n min = 2, max = 9, value = 2, step=1),br(),\n \n sliderInput(\"pow.length\", \n label = h5(HTML(\"Length of sequence (n)\")),\n min = 150, max = 300, value = 150, step=10),br(),\n \n br(), br(), br(), br(), \n \n div(\"Shiny app by\", \n 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\", \n a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\", \n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n \n div(\"Shiny source files:\",\n 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 )),\n column(8,\n div(span(tags$b(\"First 20 numbers in the sequence (first digit in\"),style=\"font-size:9pt\"),\n span(\n span(\"red\",style=\"font-size:9pt; color:red; font-weight:bold\"),tags$b(\"):\",style=\"font-size:9pt\")),\n style=\"font-size:0pt\"),\n div(\n div(span(textOutput(\"e.num.1a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.1b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.2a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.2b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.3a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.3b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.4a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.4b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.5a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.5b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.6a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.6b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.7a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.7b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.8a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.8b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.9a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.9b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.10a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.10b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.11a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.11b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.12a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.12b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.13a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.13b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.14a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.14b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.15a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.15b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.16a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.16b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.17a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.17b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.18a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.18b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.19a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.19b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"e.num.20a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"e.num.20b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n span(\"\",style=\"font-size: 9pt\"),style=\"display:inline-block\"),\n style=\"font-size:0;\"),\n div(span(\"[Sequence has \",style=\"font-size:9pt;display:inline-block\"),\n span(HTML(\" \"),style=\"font-size:9pt\"),\n span(textOutput(\"powlength\"),style=\"font-size:9pt;display:inline-block;color:teal\"),\n span(HTML(\" \"),style=\"font-size:9pt\"),\n span(\"numbers total]\",style=\"font-size:9pt;display:inline-block\"),style=\"font-size:0pt;display:inline-block;\",align=\"right\"),\n \n HTML(\"
\"),\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test\")),\n verbatimTextOutput(\"e.goodness\")),\n column(8,\n plotOutput(\"e.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###################################################################################################\n## tabPanel: Prime Numbers Sequence ##\n###################################################################################################\ntabPanel(\"(3) Prime Numbers Sequence\",\n fluidPage( \n \n # Give the page a title\n h3(\"Generalized Benford's Law: Prime Numbers Sequence\"),\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 \n p(\"Consider the sequence of prime numbers less than or equal to some power of 10. An article from 2009\n shows that the distribution of the first digit of these prime numbers\n is well described by what's known as\", HTML(\"Generalized Benford's Law (GBL)\"),\".\n This app generates the prime numbers less than or equal to\", HTML(\"103, 104, \n 105, or 106\"), \"and applies a goodness of fit test of the observed frequencies of first digits to GBL.\"\n ),\n \n p(\"More information on the Generalized Benford's Law can be found in the following journal article:\"),\n \n div(\"Luque, B. and Lacasa, L.(2009)\",\n HTML(\"'The first-digit frequencies of prime numbers and Riemann zeta zeros'\"), \n em(\"Proc. R. Soc. A\"),\", 465, 2197-2216\", style=\"padding-left: 20px; display:block; border-left: 5px solid #faebbc;margin-left:0px\"),\n \n HTML(\"
\"),\n\n # Generate a row with a sidebar\n fluidRow( \n \n column(4,wellPanel(\n \n selectInput(\"my.n\", label = h5(\"Generate sequence of prime numbers less than or equal to\"), \n choices = list(\"1,000\" = 1000, \"10,000\" = 10000, \"100,000\" = 100000, \"1,000,000\" = 1000000), \n selected = 1000),\n \n br(), br(), br(), br(), \n \n div(\"Shiny app by\", \n 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\", \n a(href=\"http://statweb.calpoly.edu/jdoi/\",target=\"_blank\", \n \"Jimmy Doi\"),align=\"right\", style = \"font-size: 8pt\"),\n \n div(\"Shiny source files:\",\n 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 )),\n column(8,\n div(span(tags$b(\"First 80 numbers in the sequence (first digit in\"),style=\"font-size:9pt\"),\n span(\n span(\"red\",style=\"font-size:9pt; color:red; font-weight:bold\"),tags$b(\"):\",style=\"font-size:9pt\")),\n style=\"font-size:0pt\"),\n div(\n div(span(textOutput(\"pr.num.1a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.1b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.2a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.2b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.3a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.3b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.4a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.4b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.5a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.5b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.6a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.6b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.7a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.7b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.8a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.8b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.9a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.9b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.10a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.10b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.11a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.11b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.12a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.12b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.13a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.13b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.14a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.14b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.15a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.15b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.16a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.16b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.17a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.17b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.18a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.18b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.19a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.19b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.20a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.20b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.21a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.21b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.22a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.22b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.23a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.23b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.24a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.24b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.25a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.25b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.26a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.26b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.27a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.27b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.28a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.28b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.29a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.29b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.30a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.30b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.31a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.31b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.32a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.32b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.33a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.33b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.34a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.34b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.35a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.35b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.36a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.36b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.37a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.37b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.38a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.38b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.39a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.39b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.40a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.40b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.41a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.41b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.42a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.42b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.43a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.43b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.44a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.44b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.45a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.45b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.46a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.46b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.47a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.47b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.48a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.48b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.49a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.49b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.50a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.50b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.51a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.51b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.52a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.52b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.53a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.53b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.54a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.54b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.55a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.55b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.56a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.56b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.57a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.57b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.58a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.58b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.59a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.59b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.60a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.60b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.61a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.61b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.62a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.62b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.63a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.63b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.64a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.64b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.65a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.65b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.66a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.66b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.67a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.67b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.68a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.68b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.69a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.69b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.70a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.70b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"),\n div(span(textOutput(\"pr.num.71a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.71b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.72a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.72b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.73a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.73b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.74a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.74b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.75a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.75b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.76a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.76b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.77a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.77b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.78a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.78b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.79a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.79b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n div(span(textOutput(\"pr.num.80a\"),style=\"font-size: 9pt; color:red; font-weight:bold; display:inline-block\"),\n span(textOutput(\"pr.num.80b\"),style=\"font-size: 9pt; color:black; display:inline-block\"),span(HTML(\" \"),style=\"font-size:9pt\"),\n style=\"display:inline-block\"), \n style=\"font-size:0;\"),\n div(span(\"[Sequence has \",style=\"font-size:9pt;display:inline-block\"),\n span(HTML(\" \"),style=\"font-size:9pt\"),\n span(textOutput(\"num.primes\"),style=\"font-size:9pt;display:inline-block;color:teal\"),\n span(HTML(\" \"),style=\"font-size:9pt\"),\n span(\"prime numbers total]\",style=\"font-size:9pt;display:inline-block\"),style=\"font-size:0pt;display:inline-block;\",align=\"right\"),\n \n HTML(\"
\"),\n fluidRow(\n column(4,\n p(tags$b(\"Goodness of Fit Test\")),\n verbatimTextOutput(\"pr.goodness\")),\n column(8,\n plotOutput(\"pr.pmf\")\n ) # closes column-8\n ), #closes fluidRow\n HTML(\"
\")\n ) #closes column-8\n ) #closes fluidRow\n ) #closes fluidPage\n) #closes tabPanel#3\n) #closes navbarPage\n) #closes shinyUI\n", "meta": {"hexsha": "87cbda03ede0173e6f5fa93e55da02e962e9c375", "size": 62090, "ext": "r", "lang": "R", "max_stars_repo_path": "BenfordSeq/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": "BenfordSeq/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": "BenfordSeq/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": 84.9384404925, "max_line_length": 146, "alphanum_fraction": 0.5968755033, "num_tokens": 15691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.6907862779418811}} {"text": "r_pacf_1 = ARMAacf(ar=c(1.3, -0.24), lag.max=20, pacf=TRUE)\r\nprint('For AR(2) process')\r\ncat('l=1',r_pacf_1[1])\r\ncat('l=2',r_pacf_1[2])\r\n\r\nr_pacf_2 = ARMAacf(ma=c(0.6), lag.max=20, pacf=TRUE)\r\nprint('For MA(1) process')\r\ncat('l=1',r_pacf_2[1])\r\ncat('l=2',r_pacf_2[2])", "meta": {"hexsha": "0f3d55ae4051108c2562787b41fadfd4003dbe8a", "size": 267, "ext": "r", "lang": "R", "max_stars_repo_path": "2/4_1.r", "max_stars_repo_name": "ENaveen98/Applied-Time-Series-Analysis", "max_stars_repo_head_hexsha": "419f2772fb1774be1ad9f2e18ba6ccfc947cfc41", "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": "2/4_1.r", "max_issues_repo_name": "ENaveen98/Applied-Time-Series-Analysis", "max_issues_repo_head_hexsha": "419f2772fb1774be1ad9f2e18ba6ccfc947cfc41", "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": "2/4_1.r", "max_forks_repo_name": "ENaveen98/Applied-Time-Series-Analysis", "max_forks_repo_head_hexsha": "419f2772fb1774be1ad9f2e18ba6ccfc947cfc41", "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.6666666667, "max_line_length": 60, "alphanum_fraction": 0.6254681648, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6903996996513067}} {"text": "\nblkwin <- function(np) {\n rad <- seq(0,2*pi,2*pi/(np-1))\n w <- (.42 - .5*cos(rad) + .08*cos(2*rad))\n return(w)\n}\n\nhamwin <- function(np) {\n w <- .54 - .46 * cos(seq(0,2*pi,2*pi/(np-1)))\n return(w)\n}\n\nhanwin <- function(np) {\n w <- .5 - .5 * cos(seq(0,2*pi,2*pi/(np-1)))\n return(w)\n}\n", "meta": {"hexsha": "a3a3c642d7b4f96354f0939c27bc1ce63210ca50", "size": 291, "ext": "r", "lang": "R", "max_stars_repo_path": "R/winfns.r", "max_stars_repo_name": "NemoursResearch/FormantTracking", "max_stars_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:47:04.000Z", "max_issues_repo_path": "R/winfns.r", "max_issues_repo_name": "NemoursResearch/FormantTracking", "max_issues_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "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/winfns.r", "max_forks_repo_name": "NemoursResearch/FormantTracking", "max_forks_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T18:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T18:20:28.000Z", "avg_line_length": 17.1176470588, "max_line_length": 47, "alphanum_fraction": 0.4948453608, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6902486057789421}} {"text": "# Example : 6 Chapter : 8.6 Page No: 457\n# Singualar Value Decomposition\ngradematrixA<-matrix(c(-6,0,4,2,2,4,0,-6,0,-6,2,4,4,2,-6,0),ncol=4)\nprint(\"SVD of Grade matrix is\")\nprint(svd(gradematrixA))\n#The answers may vary due to rounding off values", "meta": {"hexsha": "91c1dffb3cac5c23c45d0ce64a99528e16c08ed5", "size": 252, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.6.2/Ex8.6_6.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.6.2/Ex8.6_6.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.6.2/Ex8.6_6.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 42.0, "max_line_length": 67, "alphanum_fraction": 0.6944444444, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.690178035582501}} {"text": "=begin\n # sample-diagonalization01.rb\n\n require \"algebra\"\n M = SquareMatrix(Rational, 3)\n a = M[[1,-1,-1], [-1,1,-1], [2,1,-1]]\n puts \"A = \"; a.display; puts\n #A =\n # 1, -1, -1\n # -1, 1, -1\n # 2, 1, -1\n \n e = a.diagonalize\n \n puts \"Charactoristic Poly.: #{e.chpoly} => #{e.facts}\";puts\n #Charactoristic Poly.: t^3 - t^2 + t - 6 => (t - 2)(t^2 + t + 3)\n \n puts \"Algebraic Numbers:\"\n e.roots.each do |po, rs|\n puts \"#{rs.join(', ')} : roots of #{po} == 0\"\n end; puts\n #Algebraic Numbers:\n #a, -a - 1 : roots of t^2 + t + 3 == 0\n \n puts \"EigenSpaces: \"\n e.evalues.uniq.each do |ev|\n puts \"W_{#{ev}} = <#{e.espaces[ev].join(', ')}>\"\n end; puts\n #EigenSpaces:\n #W_{2} = <[4, -5, 1]>\n #W_{a} = <[1/3a + 1/3, 1/3a + 1/3, 1]>\n #W_{-a - 1} = <[-1/3a, -1/3a, 1]>\n \n puts \"Trans. Matrix:\"\n puts \"P =\"\n e.tmatrix.display; puts\n puts \"P^-1 * A * P = \"; (e.tmatrix.inverse * a * e.tmatrix).display; puts\n #P =\n # 4, 1/3a + 1/3, -1/3a\n # -5, 1/3a + 1/3, -1/3a\n # 1, 1, 1\n #\n #P^-1 * A * P =\n # 2, 0, 0\n # 0, a, 0\n # 0, 0, -a - 1\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "d1927d6bb814687f9a0acf80e824151ab688df95", "size": 1113, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-diagonalization01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-diagonalization01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-diagonalization01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.7142857143, "max_line_length": 75, "alphanum_fraction": 0.4636118598, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6897517822205895}} {"text": "f <- function(x) (x + 3)^2\nf <- Vectorize(f)\nlf <- function(x) log(f(x))\nlf <- Vectorize(lf)\n\nlf_prime_num <- function(x) numDeriv::grad(lf, x)\n\nlf_prime_analytical <- function(x) (2*(x+3))/f(x)\n\ncurve(lf_prime_num(x), 0, 10)\ncurve(lf_prime_analytical(x), 0 , 10, lwd = 2, lty = 2, col = 2, add = TRUE)\n", "meta": {"hexsha": "fc732fad958173d535f7adfd0e9fd1e262a5e38e", "size": 303, "ext": "r", "lang": "R", "max_stars_repo_path": "code/extra/test_log_f_derivative.r", "max_stars_repo_name": "maxbiostat/propriety_power_priors", "max_stars_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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/extra/test_log_f_derivative.r", "max_issues_repo_name": "maxbiostat/propriety_power_priors", "max_issues_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-29T19:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T15:58:08.000Z", "max_forks_repo_path": "code/extra/test_log_f_derivative.r", "max_forks_repo_name": "maxbiostat/propriety_power_priors", "max_forks_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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": 25.25, "max_line_length": 76, "alphanum_fraction": 0.6270627063, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6897480991850922}} {"text": "horner <- function(a, x) {\n iv <- 0\n for(i in length(a):1) {\n iv <- iv * x + a[i]\n }\n iv\n}\n\ncat(horner(c(-19, 7, -4, 6), 3), \"\\n\")\n", "meta": {"hexsha": "f5ff5b6abceba635c547893621d4cd8f586d079d", "size": 138, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.8, "max_line_length": 38, "alphanum_fraction": 0.4275362319, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6896504693674522}} {"text": "# Util\r\n\r\nstandard_error <- function(X, y, robust){\r\n if (robust %in% c(\"White\", \"white\", \"HC0\")) {\r\n std_error <- robust_stde0(X, y)\r\n cov_type <- \"heteroskadestic (White)\"\r\n } else if (robust %in% c(\"Hinkley\", \"hinkley\", \"HC1\")) {\r\n std_error <- robust_stde1(X, y)\r\n cov_type <- \"heteroskadestic (Hinkley)\"\r\n } else if (robust %in% c(\"Horn\", \"horn\", \"HC2\")) {\r\n std_error <- robust_stde2(X, y)\r\n cov_type <- \"heteroskadestic (Horn)\"\r\n } else if (robust %in% c(\"MacKinnon\", \"mackinnon\", \"HC3\")) {\r\n std_error <- robust_stde3(X, y)\r\n cov_type <- \"heteroskadestic (MacKinnon)\"\r\n } else {\r\n std_error <- stde(X, y)\r\n cov_type <- \"homoskadestic\"\r\n }\r\n return(list(\"value\"=std_error, \"cov_type\"=cov_type))\r\n}\r\n\r\n# Formula\r\n\r\n#' @export\r\nhomoskedastic_standard_error <- function(X, y){\r\n diag(homoskedastic_covariance_estimator(X, y))^(1/2)\r\n}\r\n\r\n#' @export\r\nwhite_heteroskedastic_standard_error <- function(X, y){\r\n diag(white_heteroskedastic_covariance_estimator(X, y))^(1/2)\r\n}\r\n\r\n#' @export\r\nhinkley_heteroskedastic_standard_error <- function(X, y){\r\n diag(hinkley_heteroskedastic_covariance_estimator(X, y))^(1/2)\r\n}\r\n\r\n#' @export\r\nhorn_heteroskedastic_standard_error <- function(X, y){\r\n diag(horn_heteroskedastic_covariance_estimator(X, y))^(1/2)\r\n}\r\n\r\n#' @export\r\nmackinnon_heteroskedastic_standard_error <- function(X, y){\r\n diag(mackinnon_heteroskedastic_covariance_estimator(X, y))^(1/2)\r\n}\r\n\r\n\r\n# Abbreviation\r\n\r\n#' @export\r\nstde <- homoskedastic_standard_error\r\n\r\n#' @export\r\nrobust_stde0 <- white_heteroskedastic_standard_error\r\n\r\n#' @export\r\nrobust_stde1 <- hinkley_heteroskedastic_standard_error\r\n\r\n#' @export\r\nrobust_stde2 <- horn_heteroskedastic_standard_error\r\n\r\n#' @export\r\nrobust_stde3 <- mackinnon_heteroskedastic_standard_error\r\n\r\n", "meta": {"hexsha": "6a0690f35765b1da8207bb9ce8673e93c0a30327", "size": 1855, "ext": "r", "lang": "R", "max_stars_repo_path": "R/standard_error.r", "max_stars_repo_name": "kevinkevin556/econometrics", "max_stars_repo_head_hexsha": "735a25f3eea03d9d1d1d27d90e7c1ef311604c84", "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/standard_error.r", "max_issues_repo_name": "kevinkevin556/econometrics", "max_issues_repo_head_hexsha": "735a25f3eea03d9d1d1d27d90e7c1ef311604c84", "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/standard_error.r", "max_forks_repo_name": "kevinkevin556/econometrics", "max_forks_repo_head_hexsha": "735a25f3eea03d9d1d1d27d90e7c1ef311604c84", "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.2794117647, "max_line_length": 69, "alphanum_fraction": 0.6592991914, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6896397482489709}} {"text": "png(\"#49_custom_pie_plot.png\" , width = 480, height = 480 )\n\n#Data\n\nx <- c(15, 9, 75, 90, 1, 1, 11, 5, 9, 8, 33, 11, 11, 20, 14, 13, 10, 28, 33, 21, 24, 25, 11, 33)\n\n#Fonction clock plot\nclock.plot <- function (x, col = rainbow(n), ...) {\n if( min(x)<0 ) x <- x - min(x)\n if( max(x)>1 ) x <- x/max(x)\n n <- length(x)\n if(is.null(names(x))) names(x) <- 0:(n-1)\n m <- 1.05\n plot(0, \n type = 'n', # do not plot anything\n xlim = c(-m,m), ylim = c(-m,m), \n axes = F, xlab = '', ylab = '', ...)\n a <- pi/2 - 2*pi/200*0:200\n polygon( cos(a), sin(a) )\n v <- .02\n a <- pi/2 - 2*pi/n*0:n\n segments( (1+v)*cos(a), (1+v)*sin(a), \n (1-v)*cos(a), (1-v)*sin(a) )\n segments( cos(a), sin(a), \n 0, 0, \n col = 'light grey', lty = 3) \n ca <- -2*pi/n*(0:50)/50\n for (i in 1:n) {\n a <- pi/2 - 2*pi/n*(i-1)\n b <- pi/2 - 2*pi/n*i\n polygon( c(0, x[i]*cos(a+ca), 0),\n c(0, x[i]*sin(a+ca), 0),\n col=col[i] )\n v <- .1\n text((1+v)*cos(a), (1+v)*sin(a), names(x)[i])\n }\n}\nclock.plot(x, \n main = \"Number of visitors to a web site for each hour of the day\")\n \ndev.off()\n", "meta": {"hexsha": "b480c3151598313f9ba28f123518ad9f6aa0613d", "size": 1145, "ext": "r", "lang": "R", "max_stars_repo_path": "OLD_GALLERY_RSCRIPT/#49_custom_pie_plot.r", "max_stars_repo_name": "JedStephens/R-graph-gallery", "max_stars_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 447, "max_stars_repo_stars_event_min_datetime": "2016-10-05T14:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:20:42.000Z", "max_issues_repo_path": "OLD_GALLERY_RSCRIPT/#49_custom_pie_plot.r", "max_issues_repo_name": "JedStephens/R-graph-gallery", "max_issues_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2016-10-20T14:45:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T19:15:22.000Z", "max_forks_repo_path": "OLD_GALLERY_RSCRIPT/#49_custom_pie_plot.r", "max_forks_repo_name": "JedStephens/R-graph-gallery", "max_forks_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172, "max_forks_repo_forks_event_min_datetime": "2015-12-01T15:34:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:37:06.000Z", "avg_line_length": 27.2619047619, "max_line_length": 96, "alphanum_fraction": 0.4558951965, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6896240144845031}} {"text": "## 1. Introduction ##\n\nlibrary(readr)\nhouses <- read_tsv('AmesHousing_1.txt')\n\nscale_land <- 'ordinal'\nscale_roof <- 'nominal'\nkitchen_variable <- 'discrete'\n\n## 2. The Mode for Ordinal Variables ##\n\nlibrary(dplyr)\n\ncompute_mode <- function(vector) {\n counts_df <- tibble(vector) %>% \n group_by(vector) %>% \n summarise(frequency=n()) %>% \n arrange(desc(frequency)) \n\n counts_df$vector[1]\n}\n\ncomputed_mode <- compute_mode(houses$`Land Slope`)\n\n## 3. The Mode for Nominal Variables ##\n\n# The function we wrote (you can copy-paste yours from the previous screen)\nlibrary(dplyr)\n\ncompute_mode <- function(vector) {\n counts_df <- tibble(vector) %>% \n group_by(vector) %>% \n summarise(frequency = n()) %>% \n arrange(desc(frequency)) \n\n counts_df$vector[1]\n}\ncompute_mode_table <- function(vector) {\n counts_df <- tibble(vector) %>% \n group_by(vector) %>% \n summarise(frequency = n()) %>% \n arrange(desc(frequency)) \n \n list('mode' = counts_df$vector[1], 'values' = counts_df$frequency)\n}\n\nmode <- compute_mode_table(houses$`Roof Style`)$mode\nvalue_counts <- compute_mode_table(houses$`Roof Style`)$values\n\n## 4. The Mode for Discrete Variables ##\n\nlibrary(dplyr)\n\ncompute_mode <- function(vector) {\n counts_df <- tibble(vector) %>% \n group_by(vector) %>% \n summarise(frequency = n()) %>% \n arrange(desc(frequency)) \n\n counts_df$vector[1]\n}\nbedroom_variable <- 'discrete'\nbedroom_mode <- compute_mode(houses$`Bedroom AbvGr`)\n\nprice_variable <- 'continuous'\nprice_mode <- compute_mode(houses$SalePrice)\n\n## 5. Special Cases ##\n\nlibrary(dplyr)\n\nhouses %>% \n mutate(intervals_group = cut(SalePrice, \n breaks = seq(0,800000,100000))) %>%\n group_by(intervals_group) %>% \n summarize(frequency = n())\nmode <- 150000\nmean <- mean(houses$SalePrice)\nmedian <- median(houses$SalePrice)\n\nsentence_1 <- TRUE\nsentence_2 <- TRUE\n\n## 6. Skewed Distributions ##\n\ndistribution_1 <- c('mean' = 3021 , 'median' = 3001, 'mode' = 2947)\ndistribution_2 <- c('median' = 924 , 'mode' = 832, 'mean' = 962)\ndistribution_3 <- c('mode' = 202, 'mean' = 143, 'median' = 199)\nshape_1 <- 'right skew'\nshape_2 <- 'right skew'\nshape_3 <- 'left skew'\n\n## 7. Challenge: Symmetrical Distributions ##\n\nlibrary(dplyr)\n\ncompute_mode <- function(vector) {\n counts_df <- tibble(vector) %>% \n group_by(vector) %>% \n summarise(frequency = n()) %>% \n arrange(desc(frequency)) \n\n counts_df$vector[1]\n}\nlibrary(ggplot2)\n\nggplot(data = houses,\n aes(x = `Mo Sold`)) +\n geom_density(alpha = 0.1, \n color='blue', \n fill='blue') +\n geom_vline(aes(xintercept = compute_mode(`Mo Sold`), \n color = 'Mode'), \n size = 1.2 ) +\n geom_vline(aes(xintercept = median(`Mo Sold`), \n color = 'Median'), \n size = 1.2 ) +\n geom_vline(aes(xintercept = mean(`Mo Sold`), \n color = 'Mean'), \n size = 1.2 ) +\n scale_y_continuous(labels = scales::comma) +\n xlim(1,12)+\n scale_colour_manual(values = c(\"Mode\" = \"green\", \n \"Median\" = \"black\", \n \"Mean\" = \"orange\"), \n name = \"\") +\n theme_bw() + \n theme(legend.position='top') +\n xlab(\"Mo Sold\") + \n ylab(\"Density\")", "meta": {"hexsha": "f69d1f1d62036a1bca72711b0cfb38aec5b810b5", "size": 3465, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/2. Statistics Intermediate in R Averages and Variability/3. The Mode.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/2. Statistics Intermediate in R Averages and Variability/3. The Mode.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "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 Analyst in R/Step 5 - Probability and Statistics/2. Statistics Intermediate in R Averages and Variability/3. The Mode.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 26.6538461538, "max_line_length": 75, "alphanum_fraction": 0.5766233766, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6895443656906414}} {"text": "anscombe.sum <- function(df){\nresults <- as.list(new.env()); # create a list to return with data\nresults$n <- length(df$x) # sample size\nresults$x.mean <- mean(df$x) # mean of x\nresults$y.mean <- mean(df$y) # mean of y\nlm.xy <- lm(y ~ x, data=df) # fit slr\nresults$eq.reg <- lm.xy$coefficients # regression coefficients\nresults$b1.se <- summary(lm.xy)$coefficients[2,2] # SE of slope\nresults$b1.t <- summary(lm.xy)$coefficients[2,3] # t-stat of slope\nresults$x.SS <- sum((df$x-results$x.mean)^2) # x sum of squares\nresults$ResSS <- sum(lm.xy$residuals^2) # residual SS of y\nresults$RegSS <- sum((df$y-results$y.mean)^2)-results$ResSS # reg SS\nresults$xy.cor <- cor(df$x, df$y) # correlation\nresults$xy.r2 <- summary(lm.xy)$r.squared # R^2 for regression\nreturn(results)\n}\n# calculate and store summaries by data group g\nresults.temp <- by(anscombe.long, anscombe.long$g, anscombe.sum)\n# make a table\nx.table <- cbind( t(t(unlist(results.temp[[1]])))\n, t(t(unlist(results.temp[[2]])))\n, t(t(unlist(results.temp[[3]])))\n, t(t(unlist(results.temp[[4]])))\n, t(t(unlist(results.temp[[5]])))\n, t(t(unlist(results.temp[[6]])))\n, t(t(unlist(results.temp[[7]])))\n, t(t(unlist(results.temp[[8]])))\n, t(t(unlist(results.temp[[9]])))\n, t(t(unlist(results.temp[[10]])))\n, t(t(unlist(results.temp[[11]])))\n, t(t(unlist(results.temp[[12]])))\n, t(t(unlist(results.temp[[13]])))\n, t(t(unlist(results.temp[[14]])))\n, t(t(unlist(results.temp[[15]])))\n, t(t(unlist(results.temp[[16]])))\n, t(t(unlist(results.temp[[17]])))\n, t(t(unlist(results.temp[[18]])))\n, t(t(unlist(results.temp[[19]])))\n, t(t(unlist(results.temp[[20]])))\n, t(t(unlist(results.temp[[21]])))\n, t(t(unlist(results.temp[[22]])))\n, t(t(unlist(results.temp[[23]])))\n, t(t(unlist(results.temp[[24]])))\n, t(t(unlist(results.temp[[25]])))\n)\ncolnames(x.table) <- 1:4 # label the table columns", "meta": {"hexsha": "c08bd42d778d4c503da0d850d71abc83ba01d42f", "size": 1834, "ext": "r", "lang": "R", "max_stars_repo_path": "RData/FormuleUn.r", "max_stars_repo_name": "thomasm1/MirrorByCryptoMaven", "max_stars_repo_head_hexsha": "73506e40e9ddad9e10b1b53ad9697828abbaad23", "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": "RData/FormuleUn.r", "max_issues_repo_name": "thomasm1/MirrorByCryptoMaven", "max_issues_repo_head_hexsha": "73506e40e9ddad9e10b1b53ad9697828abbaad23", "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": "RData/FormuleUn.r", "max_forks_repo_name": "thomasm1/MirrorByCryptoMaven", "max_forks_repo_head_hexsha": "73506e40e9ddad9e10b1b53ad9697828abbaad23", "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": 39.8695652174, "max_line_length": 68, "alphanum_fraction": 0.6488549618, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6894950541255861}} {"text": "heart <- read.table(\"http://stat.ethz.ch/Teaching/Datasets/heart.dat\", header = TRUE)\n\nneg.ll <- function(beta, data) {\n llh = 0\n for (i in 1:nrow(data)) {\n g = beta[1] + beta[2] * data$age[i]\n llh = llh + log(choose(data$m[i], data$N[i])) + data$N[i] * g - data$m[i] * log(1 + exp(g))\n }\n -llh\n}\n\nbeta0.grid <- seq(-10, 10, length = 101)\nbeta1.grid <- seq(-1, 1, length = 101)\n\nneg.ll.values <- matrix(nrow = 101, ncol = 101)\n\nfor (b0 in 1:101) {\n for (b1 in 1:101) {\n neg.ll.values[b0, b1] <- neg.ll(c(beta0.grid[b0], beta1.grid[b1]), heart)\n }\n}\n\ncontour(beta0.grid, beta1.grid, neg.ll.values, nlevels = 10)\n\nfit <- glm(cbind(N, m - N) ~ age, family = binomial, data = heart)\n\nprint(fit)\n\nprint(optim(c(0, 0), neg.ll, data = heart))\n\npredict(fit, newdata = data.frame(age = 20:69), type = \"response\")", "meta": {"hexsha": "24b802837e0229ae825a2bbebe8bfecf3b5166cd", "size": 842, "ext": "r", "lang": "R", "max_stars_repo_path": "Computational_Statistics/Exercices/7_3.r", "max_stars_repo_name": "DanDoge/course_ethz", "max_stars_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "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": "Computational_Statistics/Exercices/7_3.r", "max_issues_repo_name": "DanDoge/course_ethz", "max_issues_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "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": "Computational_Statistics/Exercices/7_3.r", "max_forks_repo_name": "DanDoge/course_ethz", "max_forks_repo_head_hexsha": "73e5f77e3694d6134169127c0500898402683c32", "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.1612903226, "max_line_length": 99, "alphanum_fraction": 0.5771971496, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553803, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6890102884631879}} {"text": "\n##### 1. Electricity\n### Obj : 빌딩의 전력량 예측하는 모델\n### Data : Electric\n### Hypothesis : surface_area를 input으로 쓰면 electricity를 예측하는데 도움이 될 것이다.\n### feature : surface_area(Input), electricity(Output)\n### Process : Data Load -> EDA -> Modeling -> Test\n\n##### Data Load\nElec <- read.csv('/Users/mac/Downloads/dev/study/R_ML/Class 1/Data/Electric.csv')\n\n##### EDA ... Data Structure & Plot\nstr(Elec)\nplot(Elec$surface_area, Elec$electricity, cex = 3, pch = 19)\n\n\n##### 난수 발생 알고리즘 초기값 고정 ... Training 할 때마다 샘플이 동일한 기준에서 돌아가야 하니까\nset.seed(3)\n\n##### Training Set을 전체 데이터의 70% 지정 (Training Data)\ntrain <- sample(1:nrow(Elec), 0.7 * nrow(Elec))\n\n##### 실제 전력량 (Output, Answer)\nreal_electricity <- Elec$electricity[-train]\n\n##### Model_1 ... 전력량과 면적의 1차 함수\nModel_1 <- lm(electricity ~ surface_area, data = Elec[train, ])\npredicted_electricity_1 <- predict(Model_1, Elec[-train, ])\ntest_error_1 <- mean((real_electricity - predicted_electricity_1)^2)\n\n##### Model_5 ... 전력량과 면적의 5차 함수\nModel_5 <- lm(electricity ~ poly(surface_area, 5), data = Elec[train, ])\npredicted_electricity_5 <- predict(Model_5, Elec[-train, ])\ntest_error_5 <- mean((real_electricity - predicted_electricity_5)^2)\n\n##### Model_10 ... 전력량과 면적의 10차 함수\nModel_10 <- lm(electricity ~ poly(surface_area, 10), data = Elec[train, ])\npredicted_electricity_10 <- predict(Model_10, Elec[-train, ])\ntest_error_10 <- mean((real_electricity - predicted_electricity_10)^2)\n\n##### 각각의 Error(Cost) 값\ntest_error_1\ntest_error_5\ntest_error_10\n\n## EDA ... 구현한 모든 모델 시각화 \nplot(Elec$surface_area, Elec$electricity, cex = 3, pch = 15)\na <- seq(500, 820, length = 1000) # surface_area의 값 범위(500~820)를 1000등분 함\n\npoints(a, predict(Model_1, data.frame(surface_area = a)), type = 'l', lwd = 10, col = 1)\npoints(a, predict(Model_5, data.frame(surface_area = a)), type = 'l', lwd = 10, col = 5)\npoints(a, predict(Model_10, data.frame(surface_area = a)), type = 'l', lwd = 3, col = 10)\n\n##### 2. Cars\n### obj : 자동차의 연비를 예측하는 모델\n### Data : Cars.csv\n### Hypothesis : weight를 Input으로 쓰면 mpg를 예측하는데 도움이 될 것이다.\n### Feature : weight(Input), mpg(Output)\n### Process : Data Load -> EDA -> Modeling(Train) -> (Validation) -> Test -> Visualization\n\n##### Data Load\nCars <- read.csv(\"/Users/mac/Downloads/dev/study/R_ML/Class 1/Data/Cars.csv\")\n\n##### Data Structure\nstr(Cars)\n\n##### 데이터 샘플링 초기값 설정\nset.seed(1)\n\n##### Training Set을 전체 데이터의 60%로 지정\ntrain <- sample(1:nrow(Cars), 0.6 * nrow(Cars))\n##### Validatiaon Set을 전체 데이터의 20%로 지정\nvalidation <- sample(setdiff(1:nrow(Cars), train), 0.2 * nrow(Cars)) # setdiff = 뺸 나머지, 1:768의 vector 주머니에서 train을 빼라\n##### Test Set을 전체 데이터의 20%로 지정\ntest <- setdiff(1:nrow(Cars), c(train, validation))\n\n##### Model_1 : weight(무게)와 mpg(연비) 1차 함수\nModel_1 <- lm(mpg ~ weight, data = Cars[train, ])\npred_weight_1 <- predict(Model_1, Cars[validation, ])\nvalidation_error_1 <- mean((Cars$mpg[validation] - pred_weight_1)^2)\n\n##### Model_2 : weight(무게)와 mpg(연비) 10차 함수\nModel_2 <- lm(mpg ~ poly(weight, 10), data = Cars[train, ])\npred_weight_2 <- predict(Model_2, Cars[validation, ])\nvalidation_error_2 <- mean((Cars$mpg[validation] - pred_weight_2)^2)\n\n##### Model_3 : weight + horsepower\nModel_3 <- lm(mpg ~ weight + horsepower, data = Cars[train, ])\npred_weight_3 <- predict(Model_3, Cars[validation, ])\nvalidation_error_3 <- mean((Cars$mpg[validation] - pred_weight_3)^2)\n\n\n\nplot(Cars$weight, Cars$mpg, cex = 3, pch = 15)\n\n##### Machine Learning System Design\n### 일반적으로 이 과정을 수십, 수백, 수천 번 반복한다.\n### 이 실험의 과정이 한 달이 걸리고, 한 달이 지났을 때,\n### Validation Error가 제일 낮아지는 모형을 선택했다.\n### 이제 Model에 대한 Test Error를 한 번 딱 측정하고 끝낸다.\n\n\n##### K-Fold로 나눴다면, 실험이 끝날 때까지 가지고 가야 한다.\n##### Cross Validation은 독립적이라서 병렬처리할 수 있다.\n# 구조화된 데이터 ... Random Forest, Boost, Decision Tree (~14년 Random Forest, 그 이후에는 Boost 계열이 많이 활용)\n# 비구조화된 데이터(이미지, 음성, 텍스트 데이터) ... Deep Learning", "meta": {"hexsha": "5c565e387774929f41c74008caf7788e73383173", "size": 3790, "ext": "r", "lang": "R", "max_stars_repo_path": "study/machine-learning/r/Script/ML-2-Script.r", "max_stars_repo_name": "data-block/dev", "max_stars_repo_head_hexsha": "e7a71eda6f1c4f18b262aa07899577529b7e827c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-29T12:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T02:36:57.000Z", "max_issues_repo_path": "study/machine-learning/r/Script/ML-2-Script.r", "max_issues_repo_name": "data-block/dev", "max_issues_repo_head_hexsha": "e7a71eda6f1c4f18b262aa07899577529b7e827c", "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": "study/machine-learning/r/Script/ML-2-Script.r", "max_forks_repo_name": "data-block/dev", "max_forks_repo_head_hexsha": "e7a71eda6f1c4f18b262aa07899577529b7e827c", "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.7547169811, "max_line_length": 117, "alphanum_fraction": 0.6778364116, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6889368574175695}} {"text": "hist_nwj <- function(x, alpha=0.01, pvalue=0.99, breaks=NULL, suppress='no') {\r\n ## plot histogram and normal, Weibull, and Johnson distributions\r\n ## add lines for upper tolerance limits for given alpha and pvalue\r\n ## alpha = 1 - confidence\r\n ## pvalue = coverage (tolerance interval only)\r\n\r\n ## install.packages('tolerance')\r\n library(tolerance)\r\n ## install.packages('SuppDists')\r\n library(SuppDists)\r\n \r\n ## normal distribution calculations\r\n tol_out_norm <- normtol.int(x, alpha = alpha, P=pvalue, side=1)\r\n upper_tolerance_limit_norm <- tol_out_norm$'1-sided.upper'\r\n\r\n ## Weibull distribution calculations\r\n if (min(x) < 0) {\r\n cat('\\n')\r\n cat('#####################################################################\\n')\r\n cat('Skip Weibull: Negative values cannot be fit with Weibull distribution\\n')\r\n cat(' Some day I should add logic to skip if that is the case\\n')\r\n cat('#####################################################################\\n')\r\n } else {\r\n tol_out_weib <- exttol.int(x, alpha=alpha, P=pvalue, side=1, dist=\"Weibull\")\r\n shape <- tol_out_weib$'shape.1'\r\n scale <- tol_out_weib$'shape.2'\r\n upper_tolerance_limit_weib <- tol_out_weib$'1-sided.upper'\r\n }\r\n \r\n ## Johnson distribution calculations\r\n tol_out_john <- johnson_tol(x, alpha=alpha, P=pvalue, side=1)\r\n jparms <- tol_out_john$jparms\r\n if (jparms$type == 'SB') {\r\n upper_tolerance_limit_john <- NA\r\n } else {\r\n upper_tolerance_limit_john <- tol_out_john$xtol_upper$`root approximation`\r\n } \r\n \r\n ## create vectors with density distributions\r\n xmin <- min(x)\r\n xmax <- max(x,\r\n upper_tolerance_limit_norm,\r\n upper_tolerance_limit_weib,\r\n upper_tolerance_limit_john,\r\n na.rm = TRUE)\r\n chuncks <- (xmax-xmin)/1000\r\n xrange <- seq(xmin,xmax,by=chuncks)\r\n xmean <- mean(x)\r\n xsd <- sd(x)\r\n xdensity_norm <- dnorm(xrange,xmean,xsd) \r\n xdensity_weib <- dweibull(xrange,shape=shape,scale=scale)\r\n xdensity_john <- dJohnson(xrange, jparms)\r\n maxdensity <- max(xdensity_norm, xdensity_weib, xdensity_john, na.rm=TRUE)\r\n\r\n ## make histogram\r\n ## warning: xlim range can mess up x-axis\r\n ## obtain histogram parameters but suppress plot\r\n out <- hist(x, plot=FALSE)\r\n if (is.null(breaks)) breaks <- length(out$breaks)\r\n ymax <- max(out$density, maxdensity)\r\n ## create plot\r\n hist(x, breaks=breaks,\r\n xlim=c(xmin,xmax+(xmax-xmin)/breaks), \r\n ylim=c(0,maxdensity),\r\n freq=FALSE)\r\n\r\n ## add distributions\r\n lines(x=xrange, y=xdensity_norm, col='red', lty=1)\r\n lines(x=xrange, y=xdensity_weib, col='blue', lty=1)\r\n lines(x=xrange, y=xdensity_john, col='black', lty=1)\r\n\r\n ## add lines for mean and upper 1-sided 99/99 tolerance limits\r\n abline(v=xmean,col=\"red\")\r\n abline(v=upper_tolerance_limit_norm,col=\"red\", lty=2)\r\n abline(v=upper_tolerance_limit_weib,col=\"blue\", lty=2)\r\n abline(v=upper_tolerance_limit_john,col=\"black\",lty=2)\r\n\r\n ## print to screen\r\n if (suppress == 'no') {\r\n cat(\"Tolerance limit input parameters:\\n\")\r\n cat(\" upper, 1-sided,\", pvalue*100,\"/\",(1-alpha)*100,\"\\n\")\r\n cat(\"\\n\")\r\n cat(\"Normal distribution (red):\\n\")\r\n cat(\" mean =\",xmean,\"\\n\")\r\n cat(\" standard deviation =\",xsd,\"\\n\")\r\n cat(\" tolerance limit =\",upper_tolerance_limit_norm,\"\\n\")\r\n cat(\"\\n\")\r\n cat(\"Weibull distribution (blue):\\n\")\r\n cat(\" shape =\",shape,\"\\n\")\r\n cat(\" scale =\",scale,\"\\n\")\r\n cat(\" tolerance limit =\",upper_tolerance_limit_weib,\"\\n\")\r\n cat(\"\\n\")\r\n cat(\"Johnson distribution (black):\\n\")\r\n cat(\" gamma =\",jparms$gamma ,\"\\n\")\r\n cat(\" delta =\",jparms$delta ,\"\\n\")\r\n cat(\" xi =\",jparms$xi ,\"\\n\")\r\n cat(\" lambda =\",jparms$lambda,\"\\n\")\r\n cat(\" type =\",jparms$type ,\"\\n\")\r\n cat(\" tolerance limit =\",upper_tolerance_limit_john,\"\\n\")\r\n } \r\n\r\n return(list(tol_out_norm=tol_out_norm,\r\n tol_out_weib=tol_out_weib,\r\n tol_out_john=tol_out_john))\r\n\r\n}\r\n## out <- hist_nwj(mtcars$mpg)\r\n## gamma <- out$tol_out_john$jparms$gamma\r\n", "meta": {"hexsha": "c191cc48a78f23a0d2a82abb7d89dd9e130d3fe4", "size": 4496, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/hist_nwj.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/hist_nwj.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/hist_nwj.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "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.247706422, "max_line_length": 87, "alphanum_fraction": 0.5527135231, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6889259500838764}} {"text": "> x\n[1] 3 6 8\n> y\n[1] 2 9 0\n> x + y\n[1] 5 15 8\n> x + 1 # 1 is recycled to (1,1,1)\n[1] 4 7 9\n> x + c(1,4) # (1,4) is recycled to (1,4,1) but warning issued\n[1] 4 10 9\nWarning message:\nIn x + c(1, 4) :\nlonger object length is not a multiple of shorter object length", "meta": {"hexsha": "1fdb7de33c1712b1c608f4a9459a1a6ea8402fad", "size": 273, "ext": "r", "lang": "R", "max_stars_repo_path": "add_two_vectors.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "add_two_vectors.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "add_two_vectors.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": 21.0, "max_line_length": 65, "alphanum_fraction": 0.5641025641, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695627, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.6889192778062366}} {"text": "beta <- c(9.9029, -3.3733, 4.3080, 1.2049, -0.4126, 0.4739, -0.0366)\n\nstartDate <- as.Date(\"2020-3-2\")\n\nlogistic <- function (x) 1 / (1 + exp(-x))\nlogit <- function (x) log(x / (1 - x))\n\npred <- function (case_ir, death_r, log_gdp_ppp, date, pop) {\n death_r <- death_r + 1e-5\n logistic(beta[1] +\n beta[2]*logit(case_ir) + beta[3]*logit(death_r) +\n (beta[4] + beta[5]*logit(case_ir) + beta[6]*logit(death_r)) * log_gdp_ppp +\n beta[7] * date/30)\n}\n\nprediction_df <- read.csv(\"source-data/cases_deaths_gdp.csv\")\nprediction_df$date <- as.Date(prediction_df$date)\nprediction_df <- prediction_df[order(prediction_df$date), ]\n\nprediction_df$day <- as.integer(prediction_df$date - startDate)\n\nlibrary(runner)\nmake_average <- function(x, n){\n temp <- x\n for(i in 1:length(x)){\n x[i] <- mean(temp[max(c(1, i-n)):min(c(length(x), i+n))], na.rm = T)\n }\n x\n}\n\nprediction_df$pred_ir <- pred(prediction_df$case_ir, prediction_df$death_r, prediction_df$log_gdp_ppp, prediction_df$day, prediction_df$population)\n\nprediction_df$pred_ir_low <- qbinom(0.05, 1000, prediction_df$pred_ir)/1000\nprediction_df$pred_ir_high <- qbinom(0.95, 1000, prediction_df$pred_ir)/1000\n\n# prediction_df$pred_ir <- ave(prediction_df$pred_ir, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))\n# prediction_df$pred_ir_low <- ave(prediction_df$pred_ir_low, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))\n# prediction_df$pred_ir_high <- ave(prediction_df$pred_ir_high, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))\n\n# From predicted sero-prevalence rates, we extract implied case counts\nprediction_df$pred_cases <- prediction_df$pred_ir*prediction_df$population\nprediction_df$pred_cases_low <- prediction_df$pred_ir_low*prediction_df$population\nprediction_df$pred_cases_high <- prediction_df$pred_ir_high*prediction_df$population\n\n# The following five lines creates world totals:\nprediction_df$world_cases <- ave(prediction_df$cases, prediction_df$date, FUN = sum)\nprediction_df$pred_world_cases <- ave(prediction_df$pred_cases, prediction_df$date, FUN = sum)\nprediction_df$pred_world_cases_low <- ave(prediction_df$pred_cases_low, prediction_df$date, FUN = sum)\nprediction_df$pred_world_cases_high <- ave(prediction_df$pred_cases_high, prediction_df$date, FUN = sum)\n\n# This re-produces our inset plot:\nlibrary(ggplot2)\nggplot(prediction_df[!duplicated(prediction_df$date), ],\n aes(x=as.Date(date), ymin = 0))+geom_ribbon(aes(ymax=pred_world_cases, fill = \"Probably Infected, World\"))+\n theme_minimal()+geom_ribbon(aes(ymin = 0, ymax = world_cases, fill = \"Reported Cases, World\"))+\n # geom_line(aes(y=pred_world_cases_low), col = \"white\")+\n # geom_line(aes(y=pred_world_cases_high), col = \"black\")+\n scale_y_continuous(labels = scales::comma)+\n theme(legend.title = element_blank(), legend.position = \"bottom\")+xlab(\"\")+ylab(\"\")\n\nlatest <- prediction_df[prediction_df$date == max(prediction_df$date),]\n\n# ggplot(latest, aes(x=country,y=pred_ir)) + geom_bar(stat=\"identity\")\n\n# To generate the large plot, we first-differences and by continent and a select few large countries:\n\n# These lines define our groups (colors in the large plot)\nprediction_df$continents_plus <- prediction_df$continent\nprediction_df$continents_plus[prediction_df$country == \"United States\"] <- \"United States\"\nprediction_df$continents_plus[prediction_df$country == \"China\"] <- \"China\"\nprediction_df$continents_plus[prediction_df$country == \"India\"] <- \"India\"\nprediction_df$continents_plus[prediction_df$country == \"Brazil\"] <- \"Brazil\"\n\nnew_cases_fun <- function(x) {\n x <- x - c(0, x)[1:length(x)]\n # x <- make_average(x, n = 10)\n x }\n\n# This function takes first differences by country and sums countries together by day and group: \nbig_chart_data <- function(prediction_df, grouping = \"continent_plus\"){\n \n prediction_df$region <- prediction_df[, grouping]\n \n regions <- prediction_df\n \n regions$region_cases <- ave(regions$cases, paste0(regions$date, \"_\", regions$region), FUN = sum)\n regions$pred_region_cases <- ave(regions$pred_cases, paste0(regions$date, \"_\", regions$region), FUN = sum)\n regions$pred_region_cases_low <- ave(regions$pred_cases_low, paste0(regions$date, \"_\", regions$region), FUN = sum)\n regions$pred_region_cases_high <- ave(regions$pred_cases_high, paste0(regions$date, \"_\", regions$region), FUN = sum)\n \n new_cases_fun <- function(x) {\n x <- x - c(0, x)[1:length(x)]\n x <- make_average(x, n = 7)\n x <- make_average(x, n = 7)\n x }\n regions <- regions[!duplicated(paste0(regions$date, \"_\", regions$region)), ]\n \n # regions$pred_region_cases <- ave(regions$pred_region_cases, regions$region, FUN = function(x) make_average(x, n = 10))\n # regions$pred_region_cases_low <- ave(regions$pred_region_cases_low, regions$region, FUN = function(x) make_average(x, n = 10))\n # regions$pred_region_cases_high <- ave(regions$pred_region_cases_high, regions$region, FUN = function(x) make_average(x, n = 10))\n\n regions$new_cases <- ave(regions$region_cases, regions$region, FUN = new_cases_fun)\n regions$new_pred_cases <- ave(regions$pred_region_cases, regions$region, FUN = new_cases_fun)\n regions$new_pred_cases_high <- ave(regions$pred_region_cases_high, regions$region, FUN = new_cases_fun)\n regions$new_pred_cases_low <- ave(regions$pred_region_cases_low, regions$region, FUN = new_cases_fun)\n return(regions)}\ncontinents_plus <- big_chart_data(prediction_df, grouping = \"continents_plus\") # This runs the above function\n\n# This reproduces our first large plot:\nggplot(continents_plus, \n aes(x=date, ymin = 0))+geom_area(aes(y=new_pred_cases, fill = continents_plus), col = \"white\")+\n theme_minimal()+\n # geom_line(aes(y=new_pred_cases_high), col = \"white\")+\n # geom_line(aes(y=new_pred_cases_low), col = \"black\")+\n scale_y_continuous(labels = scales::comma)+ylab(\"\")+\n theme(legend.title = element_blank(), legend.position = \"bottom\")+xlab(\"\")\n", "meta": {"hexsha": "1bc76255bde3844467359d25f6c142c661f4eaf3", "size": 5973, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/bayesian.r", "max_stars_repo_name": "MikeInnes/Grim-Tallies", "max_stars_repo_head_hexsha": "791bddb09f7fa15e959ec5f238edc73f53fdfe2a", "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/bayesian.r", "max_issues_repo_name": "MikeInnes/Grim-Tallies", "max_issues_repo_head_hexsha": "791bddb09f7fa15e959ec5f238edc73f53fdfe2a", "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/bayesian.r", "max_forks_repo_name": "MikeInnes/Grim-Tallies", "max_forks_repo_head_hexsha": "791bddb09f7fa15e959ec5f238edc73f53fdfe2a", "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.0512820513, "max_line_length": 147, "alphanum_fraction": 0.7358111502, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6887970117520912}} {"text": "\r\n\r\n# Goal: Standard computations with well-studied distributions.\r\n\r\n# The normal distribution is named \"norm\". With this, we have:\r\n\r\n# Normal density\r\ndnorm(c(-1.96,0,1.96))\r\n\r\n# Cumulative normal density\r\npnorm(c(-1.96,0,1.96))\r\n\r\n# Inverse of this\r\nqnorm(c(0.025,.5,.975))\r\npnorm(qnorm(c(0.025,.5,.975)))\r\n\r\n# 1000 random numbers from the normal distribution\r\nsummary(rnorm(1000))\r\n\r\n\r\n# Here's the same ideas, for the chi-squared distribution with 10 degrees\r\n# of freedom.\r\ndchisq(c(0,5,10), df=10)\r\n\r\n# Cumulative normal density\r\npchisq(c(0,5,10), df=10)\r\n\r\n# Inverse of this\r\nqchisq(c(0.025,.5,.975), df=10)\r\n\r\n# 1000 random numbers from the normal distribution\r\nsummary(rchisq(1000, df=10))\r\n\r\n", "meta": {"hexsha": "f8f352d88f2a5d76f4b407410d3606a79e03f5a9", "size": 704, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p9.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p9.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p9.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.7058823529, "max_line_length": 74, "alphanum_fraction": 0.6803977273, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6886951491599916}} {"text": "# Example : 1 Chapter : 6.3 Page No: 313\r\n# Solve Differential equation\r\n\r\n# lambda1,lamda2,x1,x2,c,d are computed here.. for remaining details look textbook\r\nA<-matrix(c(0,1,1,0),ncol=2)\r\nlambda<-eigen(A)$values\r\nx<-eigen(A)$vectors #These are normalised eigen vectors\r\n#to get eigen vectors in textbook .. Multiply them with the scalars\r\nx[,1]<-x[,1]*(1/x[1,1])\r\nx[,2]<-x[,2]*(1/x[1,2])\r\nprint(x)\r\nu<-c(4,2)\r\ncd<-solve(x,u)\r\nC<-cd[1]\r\nD<-cd[2]\r\nprint(\"Lambda 1 and Lambda 2\")\r\nprint(lambda)\r\nprint(\"x1 and x2\")\r\nprint(x)\r\nprint(\"C and D are\")\r\nprint(C)\r\nprint(D)", "meta": {"hexsha": "72bb740f34b44cd81f22fc3208735c163a1ac4a1", "size": 570, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.3.1/Ex6.3_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.3.1/Ex6.3_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH6/EX6.3.1/Ex6.3_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 25.9090909091, "max_line_length": 83, "alphanum_fraction": 0.6438596491, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6886018005953153}} {"text": "#' crib_fun\n#' converts a vector of [0,1] values to (0,1) a la Cribari-Neto & Zeileis 2010\n#' @param x a vector of values on the interval [0,1]\n#' @param N alternative sample size. This is useful when tranforming a matrix in the dirchlet case, rather than just a vector as in the beta case.\n#'\n#' @return a vector of values on the interval (0,1)\n#' @export\n#'\n#' @examples\ncrib_fun <- function(x,N = NA){\n #default use length of vector.\n if( is.na(N)){\n out <- (x * (length(x) - 1) + 0.5) / length(x) \n }\n #custom- useful when I am in multivariate case.\n if(!is.na(N)){\n out <- (x * (N - 1) + 0.5) / N\n }\n return(out)\n}", "meta": {"hexsha": "d422841e61fd1e2277012910c1a0d10f0d77552b", "size": 634, "ext": "r", "lang": "R", "max_stars_repo_path": "NEFI_functions/crib_fun.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "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/crib_fun.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "NEFI_functions/crib_fun.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 31.7, "max_line_length": 146, "alphanum_fraction": 0.6246056782, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.688601797397977}} {"text": "#\n# Example R program\n#\n\n# example from https://github.com/jyypma/nloptr/blob/master/man/nloptr.Rd\n\nlibrary('nloptr')\n\n## Rosenbrock Banana function and gradient in separate functions\neval_f <- function(x) {\n return( 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2 )\n}\n\neval_grad_f <- function(x) {\n return( c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),\n 200 * (x[2] - x[1] * x[1])) )\n}\n\n\n# initial values\nx0 <- c( -1.2, 1 )\n\nopts <- list(\"algorithm\"=\"NLOPT_LD_LBFGS\",\n \"xtol_rel\"=1.0e-8)\n\n# solve Rosenbrock Banana function\nres <- nloptr( x0=x0,\n eval_f=eval_f,\n eval_grad_f=eval_grad_f,\n opts=opts)\nprint( res )\n\n\n## Rosenbrock Banana function and gradient in one function\n# this can be used to economize on calculations\neval_f_list <- function(x) {\n return( list( \"objective\" = 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2,\n \"gradient\" = c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),\n 200 * (x[2] - x[1] * x[1])) ) )\n}\n\n# solve Rosenbrock Banana function using an objective function that\n# returns a list with the objective value and its gradient\nres <- nloptr( x0=x0,\n eval_f=eval_f_list,\n opts=opts)\nprint( res )\n\n\n\n# Example showing how to solve the problem from the NLopt tutorial.\n#\n# min sqrt( x2 )\n# s.t. x2 >= 0\n# x2 >= ( a1*x1 + b1 )^3\n# x2 >= ( a2*x1 + b2 )^3\n# where\n# a1 = 2, b1 = 0, a2 = -1, b2 = 1\n#\n# re-formulate constraints to be of form g(x) <= 0\n# ( a1*x1 + b1 )^3 - x2 <= 0\n# ( a2*x1 + b2 )^3 - x2 <= 0\n\nlibrary('nloptr')\n\n\n# objective function\neval_f0 <- function( x, a, b ){\n return( sqrt(x[2]) )\n}\n\n# constraint function\neval_g0 <- function( x, a, b ) {\n return( (a*x[1] + b)^3 - x[2] )\n}\n\n# gradient of objective function\neval_grad_f0 <- function( x, a, b ){\n return( c( 0, .5/sqrt(x[2]) ) )\n}\n\n# jacobian of constraint\neval_jac_g0 <- function( x, a, b ) {\n return( rbind( c( 3*a[1]*(a[1]*x[1] + b[1])^2, -1.0 ),\n c( 3*a[2]*(a[2]*x[1] + b[2])^2, -1.0 ) ) )\n}\n\n\n# functions with gradients in objective and constraint function\n# this can be useful if the same calculations are needed for\n# the function value and the gradient\neval_f1 <- function( x, a, b ){\n return( list(\"objective\"=sqrt(x[2]),\n \"gradient\"=c(0,.5/sqrt(x[2])) ) )\n}\n\neval_g1 <- function( x, a, b ) {\n return( list( \"constraints\"=(a*x[1] + b)^3 - x[2],\n \"jacobian\"=rbind( c( 3*a[1]*(a[1]*x[1] + b[1])^2, -1.0 ),\n c( 3*a[2]*(a[2]*x[1] + b[2])^2, -1.0 ) ) ) )\n}\n\n\n# define parameters\na <- c(2,-1)\nb <- c(0, 1)\n\n# Solve using NLOPT_LD_MMA with gradient information supplied in separate function\nres0 <- nloptr( x0=c(1.234,5.678),\n eval_f=eval_f0,\n eval_grad_f=eval_grad_f0,\n lb = c(-Inf,0),\n ub = c(Inf,Inf),\n eval_g_ineq = eval_g0,\n eval_jac_g_ineq = eval_jac_g0,\n opts = list(\"algorithm\"=\"NLOPT_LD_MMA\"),\n a = a,\n b = b )\nprint( res0 )\n\n# Solve using NLOPT_LN_COBYLA without gradient information\nres1 <- nloptr( x0=c(1.234,5.678),\n eval_f=eval_f0,\n lb = c(-Inf,0),\n ub = c(Inf,Inf),\n eval_g_ineq = eval_g0,\n opts = list(\"algorithm\"=\"NLOPT_LN_COBYLA\"),\n a = a,\n b = b )\nprint( res1 )\n\n\n# Solve using NLOPT_LD_MMA with gradient information in objective function\nres2 <- nloptr( x0=c(1.234,5.678),\n eval_f=eval_f1,\n lb = c(-Inf,0),\n ub = c(Inf,Inf),\n eval_g_ineq = eval_g1,\n opts = list(\"algorithm\"=\"NLOPT_LD_MMA\", \"check_derivatives\"=TRUE),\n a = a,\n b = b )\nprint( res2 )\n\n", "meta": {"hexsha": "fc499c2fac2e0abbe8f62353d50abcb29574df61", "size": 3904, "ext": "r", "lang": "R", "max_stars_repo_path": "test/nloptr/prog.r", "max_stars_repo_name": "plasalvia/r.for.IPx", "max_stars_repo_head_hexsha": "dee8d96f0468bf912fdff5a0dcdf5f01e1fa6249", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-02T14:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-31T16:52:24.000Z", "max_issues_repo_path": "test/nloptr/prog.r", "max_issues_repo_name": "plasalvia/r.for.IPx", "max_issues_repo_head_hexsha": "dee8d96f0468bf912fdff5a0dcdf5f01e1fa6249", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-19T22:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-28T22:33:36.000Z", "max_forks_repo_path": "test/nloptr/prog.r", "max_forks_repo_name": "plasalvia/r.for.IPx", "max_forks_repo_head_hexsha": "dee8d96f0468bf912fdff5a0dcdf5f01e1fa6249", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:09:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T20:38:44.000Z", "avg_line_length": 27.1111111111, "max_line_length": 87, "alphanum_fraction": 0.5130635246, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6884351298024811}} {"text": "# confidence interval for the ratio of the two variances\r\n\r\ny1bar=38.48\r\ns1=16.37\r\nn1=40\r\ny2bar=26.93\r\ns2=9.88\r\nn2=40\r\nalpha=0.05\r\nFU=qf(1-alpha/2,39,39)\r\nFL=1/FU\r\n \r\n# confidence interval for sigma1^2/sigma2^2\r\nleft_i=(s1^2/s2^2)*FL\r\nright_i=(s1^2/s2^2)*FU\r\nprint(left_i)\r\nprint(right_i)", "meta": {"hexsha": "6c6dd3b2a6a6841e72c2c463aaf4e2ea33763e27", "size": 289, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.6/Ex7_6.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.6/Ex7_6.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.6/Ex7_6.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 17.0, "max_line_length": 58, "alphanum_fraction": 0.6851211073, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6883993038820078}} {"text": "#' Expected number of ENC given GC3 content\r\n#' \r\n#' Calculates the expected ENC based on Wright's formula given GC3 percentage\r\n#' @param gc3 a number of GC3 content\r\n#' @return a number of the expected ENC given the GC3 content\r\n#' \r\n#' @export\r\n\r\nenc_exp <- function(gc3=0){\r\n return(2+gc3+29/(gc3^2+(1-gc3)^2))\r\n}", "meta": {"hexsha": "cf1c5fec690f399a9248b65ae31feeb3b3ceda95", "size": 318, "ext": "r", "lang": "R", "max_stars_repo_path": "R/enc_exp.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_exp.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_exp.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": 28.9090909091, "max_line_length": 78, "alphanum_fraction": 0.6823899371, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6883992872959491}} {"text": "# Binomial logistic regression with moderation simulation code\n\n# Raymond Viviano\n# rayviviano@gmail.com\n# March 27th, 2020\n\n# TODO: Implement checks to make sure that all models converge\n\nlibrary(ggplot2)\n\n########################### User Definition Section ############################\n\n# Specify Intercept and Beta Terms \nB0 <- logit(0.1) # Intercept. \nB1 <- .2 # Variable 1 Beta\nB2 <- .1 # Variable 2 Beta\nB3.Odds.Seq <- seq(1.05, 2.55, by=.1) # Loop through ORs for interaction term\n\n# Ensure reproducible results\nset.seed(10000)\n\n# Define sample size\nn <- 16000\n\n# Define number of simulations per B3 Odds Ratio\nnsims <- 100\n\n######################## End of User Definition Section ########################\n\n############################# Function Definitions #############################\n\n#' Logit function\nlogit <- function(p){\n return(log(as.double(p)/(1.0-as.double(p))))\n}\n\n\n#' Inverse Logit Function\ninv.logit <- function(p){\n return(exp(p)/(1+exp(p)))\n}\n\n\n#' Coverage Probability, i.e., the probability that the confidence interval (ci)\n#' for a parameter will contain the true value\n#' Inputs:\n#' b - Estimate\n#' se - Standard Error of the Estimate\n#' true - True value of parameter for data-generating process\n#' cl - Confidence level\n#' dof - Degrees of Freedom\n#' Output:\n#' List containing coverage probability, vect\ncoverage.prob <- function(b, se, true, cl=.95, dof=Inf){\n # Compute quantile based on confidence level\n coverage.quantile <- cl + (1-cl)/2\n\n # Compute confidence interval upper and lower bounds\n ci.lower <- b - qt(coverage.quantile, df=dof)*se\n ci.upper <- b + qt(coverage.quantile, df=dof)*se\n\n # For each ci generated for each b/se pair, eval if true param is in ci\n ci.contain.true <- ifelse(true>=ci.lower & true<=ci.upper, 1, 0)\n\n # Calculate coverage probability\n cp <- mean(ci.contain.true)\n\n # Calculate Monte Carlo Error\n mc.err.lower <- cp - 1.96*sqrt((cp*(1-cp))/length(b))\n mc.err.upper <- cp + 1.96*sqrt((cp*(1-cp))/length(b))\n\n # Return coverage probability and error\n return(list(cp=cp, ci=cbind(mc.err.lower, mc.err.upper)))\n}\n\n\n#' Power to detect any effect at various alpha levels\n#' Takes a vector of p-values and calculates the proportion of models where the \n#' p-val for the effect of interest was < .5, .01, and .001.\npower.detect.effect <- function(p.val.vec){\n less.than.05 <- ifelse(p.val.vec < .05, 1, 0)\n prop.05 <- sum(less.than.05)/length(less.than.05)\n\n less.than.01 <- ifelse(p.val.vec < .01, 1, 0)\n prop.01 <- sum(less.than.01)/length(less.than.01)\n\n less.than.001 <- ifelse(p.val.vec < .001, 1, 0)\n prop.001 <- sum(less.than.001)/length(less.than.001)\n\n cat(paste0('Power to detect effect at .05: ', prop.05, '\\n'))\n cat(paste0('Power to detect effect at .01: ', prop.01, '\\n'))\n cat(paste0('Power to detect effect at .001: ', prop.001, '\\n'))\n}\n\n\n#' Power to detect effect at .05 level based on simulations\npower.at.05 <- function(p.val.vec){\n less.than.05 <- ifelse(p.val.vec < .05, 1, 0)\n return(sum(less.than.05)/length(less.than.05))\n}\n\n\n#' plotLines\n#' \n#' Lineplots comparing continuous variable scores across levels of another var\n#' \n#' Inputs: \n#' df: Dataframe with vars of interest.\n#' title: Title above chart \n#' outDir: Directory to save plot to\nplotLines <- function(df, title, outDir){\n # Create plot\n p <- ggplot(data=df, aes(x=B3.Odds.Seq, y=B3.Powr.Seq)) \n\n # Add lines for each group\n p <- p + geom_line(stat='identity', size=.85, alpha=0.9) \n \n # Unique shape for each group placed at each data point\n p <- p + geom_point(size=2.5, alpha=.45) \n\n # Pad the distance between the x-axis and smallest plotted value slightly\n p <- p + scale_y_continuous(limits=c(0,1))\n\n # Pad/add extra space to the ends of the x-axis\n p <- p + scale_x_continuous(expand=c(0.05, 0.05)) \n\n # Remove gray background, format x-axis text, format legend \n p <- p + theme(panel.grid.major=element_blank(), \n panel.grid.minor=element_blank(), \n panel.background=element_blank(), \n axis.line=element_line(colour=\"black\"), \n axis.text.x=element_text(angle=0, size=14),\n axis.text.y=element_text(angle=0, size=14), \n legend.key=element_rect(color=NA, fill=NA),\n legend.background=element_blank(),\n legend.key.width=unit(3, \"line\"),\n legend.justification=c(1, 1),\n legend.position=c(.2, 1)) \n \n # Add axis labels\n p <- p + labs(y='Proportion of Simulations with Significant Interaction Term at p < .05', \n x='Odds Ratio of the Interaction') \n\n # Remove any components to the legend that could relate to alpha or size\n p <- p + scale_alpha(guide='none') \n p <- p + scale_size(guide='none') \n\n # Add a title to the plot\n p <- p + ggtitle(title) \n\n # Save Plots\n pngOut <- paste(outDir, \"/moderatedLogitInteractionPower.png\", sep=\"\") \n svgOut <- paste(outDir, \"/moderatedLogitInteractionPower.svg\", sep=\"\") \n \n ggsave(pngOut, p)\n ggsave(svgOut, p)\n}\n\n# Check power at varying values for B3 (Interaction Beta)\nB3.Powr.Seq <- rep(0, length(B3.Odds.Seq)) # Hold power for ORs, init all to 0\n\nfor(j in 1:length(B3.Odds.Seq)){\n # Take the natural log of the expected odds ratio to get interaction beta\n B3.Odds.Ratio <- B3.Odds.Seq[j]\n B3 <- log(B3.Odds.Ratio)\n\n # Define matrix to hold simulation data (estimates, std.errors, and pvals)\n sim.prms <- matrix(NA, nrow=nsims, ncol=12)\n\n # Print statements to track script progress\n cat(paste0(\"Calculating power for B3 = \", round(B3,2), \", exp(\", round(B3,2), \n \") = Odds Ratio of \", B3.Odds.Ratio, \"\\n\\nIteration: \"))\n\n # Loop through simulations\n for(i in 1:nsims){\n # Print statements to observe progress\n if ((i-1)%%10==0){\n cat(paste0(i,\", \"))\n }\n\n # Generate independant variable data, uniform random between -1 and 1\n x <- runif(n, -1, 1)\n\n # Generate normal dist data for the moderating variable\n m <- rnorm(n, 0, 1)\n\n # Element-wise multiply x and m for interaction\n xm <- x*m\n\n # Data-generation-process for Bernoulli trials\n y <- rbinom(n, 1, inv.logit(B0 + B1*x + B2*m + B3*xm))\n\n # Estimate logit model\n model <- glm(y ~ x + m + xm, family=binomial(link=logit))\n\n # TODO: Implement checks to make sure that models converge\n \n # Put model paramters in simulation matrix\n sim.prms[i, 1] <- model$coef[1] # Estimate for B0\n sim.prms[i, 2] <- model$coef[2] # Estimate for B1\n sim.prms[i, 3] <- model$coef[3] # Estimate for B2\n sim.prms[i, 4] <- model$coef[4] # Estimate for B3\n sim.prms[i, 5] <- summary(model)$coefficients[,2][1] # StdError for B0\n sim.prms[i, 6] <- summary(model)$coefficients[,2][2] # StdError for B1\n sim.prms[i, 7] <- summary(model)$coefficients[,2][3] # StdError for B2\n sim.prms[i, 8] <- summary(model)$coefficients[,2][4] # StdError for B3\n sim.prms[i, 9] <- summary(model)$coefficients[,4][1] # P-Value for B0\n sim.prms[i,10] <- summary(model)$coefficients[,4][2] # P-Value for B1\n sim.prms[i,11] <- summary(model)$coefficients[,4][3] # P-Value for B2\n sim.prms[i,12] <- summary(model)$coefficients[,4][4] # P-Value for B3\n\n }\n\n # Newline for prettier prints\n cat(\"\\n\")\n\n # Get Covarage probabilities for the interaction\n B3.coverage <- coverage.prob(sim.prms[,4], sim.prms[,8], B3, .95, n-model$rank)\n\n # Intercept coverage probabilities\n cat(\"Coverage Probability for B3 (Interaction Beta)\\n\")\n cat(paste0(B3.coverage$cp, \" [\", B3.coverage$ci[1,1], \",\", \n B3.coverage$ci[1,2], \"]\\n\"))\n\n # Power to detect moderation\n print(\"Power to detect interaction term:\")\n power.detect.effect(sim.prms[,12])\n\n # Update B3.Powr.Seq\n B3.Powr.Seq[j] <- power.at.05(sim.prms[,12])\n\n # Newline for prettier prints\n cat(\"\\n\")\n}\n\n# Create dataframe for plotting power at various B3s\ndf.plot <- data.frame(B3.Odds.Seq, B3.Powr.Seq)\n\n# Plot Power Analysis\nplotLines(df.plot, 'Moderated Logistic Regression Power', './')\n\n", "meta": {"hexsha": "55add96ecdd0f0ad28ed0adf184e77d141695879", "size": 8520, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/moderated-logistic-regress-simulations.r", "max_stars_repo_name": "rviviano/data-tools", "max_stars_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "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/moderated-logistic-regress-simulations.r", "max_issues_repo_name": "rviviano/data-tools", "max_issues_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "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/moderated-logistic-regress-simulations.r", "max_forks_repo_name": "rviviano/data-tools", "max_forks_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "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.2066115702, "max_line_length": 94, "alphanum_fraction": 0.6025821596, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385702803464}} {"text": "#######################\r\n## Section 6, Part 2 ##\r\n#######################\r\n\r\n#install.packages(\"mlogit\")\r\n#install.packages(\"randtoolbox\")\r\n\r\nlibrary(mlogit)\r\nlibrary(randtoolbox)\r\nlibrary(MASS)\r\n\r\nsetwd(\"C:\\\\dc_book\\\\Replication_Files_Element\")\r\n\r\ncb.data <- read.csv(\"cb_data.csv\")\r\n\r\ncb.data <- mlogit.data(cb.data, choice=\"choice\", shape=\"long\", chid.var=\"choiceid\", alt.var=\"region\", id.var=\"id\")\r\n\r\n###############\r\n## Table 6.5 ##\r\n###############\r\n\r\ncb.data$n.travelcost <- cb.data$travelcost * -1\r\n\r\ncosco.busan.mxl <- mlogit(choice ~ n.travelcost + bridge + marin + eastbay + bayshore + peninsula | 0, data=cb.data, rpar=c(n.travelcost=\"ln\", bridge=\"n\", marin=\"n\", eastbay=\"n\", bayshore=\"n\", peninsula=\"n\"), panel=TRUE, R=500, halton=NA)\r\ncosco.busan.mxl.results <- cbind(cosco.busan.mxl$coefficients, sqrt(diag(vcov(cosco.busan.mxl))), confint.default(cosco.busan.mxl, level=0.95))\r\nN <- length(unique(cb.data$id))\r\nC <- length(unique(cb.data$choiceid))\r\nA <- nrow(cb.data)\r\ncolnames(cosco.busan.mxl.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(cosco.busan.mxl.results, digits=3))) # interpret negative standard deviations as if they were positive\r\nprint(N)\r\nprint(C)\r\nprint(A)\r\n\r\n\r\n###############\r\n## Table 6.6 ## \r\n###############\r\n\r\ncoeffs <- cosco.busan.mxl$coefficients\r\ncovmat <- vcov(cosco.busan.mxl)\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, coeffs, covmat)\r\nR <- 500\r\nhalton.seq <- qnorm(halton(R, dim=6))\r\n\r\n## observed\r\n\r\nobserved.x <- with(cb.data, data.frame(\r\ntravelcost = travelcost,\r\nbridge = bridge,\r\nmarin = marin,\r\neastbay = eastbay, \r\nbayshore = bayshore,\r\npeninsula = peninsula,\r\nid = idx, \r\nweights = wts\r\n))\r\n\r\nid.weights <- observed.x$weights[observed.x$id.alt==1]\r\n\r\nshares <- matrix(0, ndraws, 15)\r\n\r\nmarin.o <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==1)))\r\neastbay.o <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==2)))\r\nbayshore.o <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==3)))\r\npeninsula.o <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==4)))\r\nnotrip.o <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==5)))\r\nmarin.c <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==1)))\r\neastbay.c <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==2)))\r\nbayshore.c <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==3)))\r\npeninsula.c <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==4)))\r\nnotrip.c <- matrix(0, ndraws, nrow(subset(observed.x, id.alt==5)))\r\n\r\nfor (i in 1:R) {\r\n\r\n\ttravelcost <- -1 * exp(betadraw[,\"n.travelcost\"] + (halton.seq[i,1] * abs(betadraw[,\"sd.n.travelcost\"])))\r\n\tbridge <- betadraw[,\"bridge\"] + (halton.seq[i,2] * abs(betadraw[,\"sd.bridge\"]))\r\n\tmarin <- betadraw[,\"marin\"] + (halton.seq[i,3] * abs(betadraw[,\"sd.marin\"]))\r\n\teastbay <- betadraw[,\"eastbay\"] + (halton.seq[i,4] * abs(betadraw[,\"sd.eastbay\"]))\r\n\tbayshore <- betadraw[,\"bayshore\"] + (halton.seq[i,5] * abs(betadraw[,\"sd.bayshore\"]))\r\n\tpeninsula <- betadraw[,\"peninsula\"] + (halton.seq[i,6] * abs(betadraw[,\"sd.peninsula\"]))\r\n\r\n\tbeta.R <- cbind(travelcost, bridge, marin, eastbay, bayshore, peninsula)\r\n\t\r\n\texb.region1.o <- exp(beta.R %*% t(subset(observed.x, id.alt==1, select=c(1:6))))\r\n\texb.region2.o <- exp(beta.R %*% t(subset(observed.x, id.alt==2, select=c(1:6))))\r\n\texb.region3.o <- exp(beta.R %*% t(subset(observed.x, id.alt==3, select=c(1:6))))\r\n\texb.region4.o <- exp(beta.R %*% t(subset(observed.x, id.alt==4, select=c(1:6))))\r\n\texb.region5.o <- exp(beta.R %*% t(subset(observed.x, id.alt==5, select=c(1:6))))\r\n\texb.all.o <- exb.region1.o + exb.region2.o + exb.region3.o + exb.region4.o + exb.region5.o\r\n\t\r\n\tprobs.region1.o <- exb.region1.o/exb.all.o\r\n\tprobs.region2.o <- exb.region2.o/exb.all.o\r\n\tprobs.region3.o <- exb.region3.o/exb.all.o\r\n\tprobs.region4.o <- exb.region4.o/exb.all.o\r\n\tprobs.region5.o <- exb.region5.o/exb.all.o\r\n\r\n\tmarin.o <- marin.o + (probs.region1.o * (1/R))\r\n\teastbay.o <- eastbay.o + (probs.region2.o * (1/R)) \r\n\tbayshore.o <- bayshore.o + (probs.region3.o * (1/R)) \r\n\tpeninsula.o <- peninsula.o + (probs.region4.o * (1/R)) \r\n\tnotrip.o <- notrip.o + (probs.region5.o * (1/R)) \r\n\t\r\n\t# counterfactual -- set alternative specific constant to drive probability of East Bay to zero\r\n\t\r\n\tbeta.R.c <- beta.R\r\n\tbeta.R.c[,\"eastbay\"] <- -25\r\n\r\n\texb.region1.c <- exp(beta.R.c %*% t(subset(observed.x, id.alt==1, select=c(1:6))))\r\n\texb.region2.c <- exp(beta.R.c %*% t(subset(observed.x, id.alt==2, select=c(1:6))))\r\n\texb.region3.c <- exp(beta.R.c %*% t(subset(observed.x, id.alt==3, select=c(1:6))))\r\n\texb.region4.c <- exp(beta.R.c %*% t(subset(observed.x, id.alt==4, select=c(1:6))))\r\n\texb.region5.c <- exp(beta.R.c %*% t(subset(observed.x, id.alt==5, select=c(1:6))))\r\n\texb.all.c <- exb.region1.c + exb.region2.c + exb.region3.c + exb.region4.c + exb.region5.c\r\n\t\r\n\tprobs.region1.c <- exb.region1.c/exb.all.c\r\n\tprobs.region2.c <- exb.region2.c/exb.all.c\r\n\tprobs.region3.c <- exb.region3.c/exb.all.c\r\n\tprobs.region4.c <- exb.region4.c/exb.all.c\r\n\tprobs.region5.c <- exb.region5.c/exb.all.c\r\n\t\r\n\tmarin.c <- marin.c + (probs.region1.c * (1/R))\r\n\teastbay.c <- eastbay.c + (probs.region2.c * (1/R)) \r\n\tbayshore.c <- bayshore.c + (probs.region3.c * (1/R)) \r\n\tpeninsula.c <- peninsula.c + (probs.region4.c * (1/R)) \r\n\tnotrip.c <- notrip.c + (probs.region5.c * (1/R)) \r\n\t\r\n\r\n}\r\n\r\n# apply sample enumeration\r\n\r\nmarin.so <- (colSums(apply(marin.o, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\neastbay.so <- (colSums(apply(eastbay.o, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\nbayshore.so <- (colSums(apply(bayshore.o, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\npeninsula.so <- (colSums(apply(peninsula.o, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\nnotrip.so <- (colSums(apply(notrip.o, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\n\r\nmarin.sc <- (colSums(apply(marin.c, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\neastbay.sc <- (colSums(apply(eastbay.c, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\nbayshore.sc <- (colSums(apply(bayshore.c, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\npeninsula.sc <- (colSums(apply(peninsula.c, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\nnotrip.sc <- (colSums(apply(notrip.c, 1, function(x) {x * id.weights}))/sum(id.weights)) * 100\r\n\r\nmarin.s.diff <- marin.sc - marin.so\r\neastbay.s.diff <- eastbay.sc - eastbay.so\r\nbayshore.s.diff <- bayshore.sc - bayshore.so\r\npeninsula.s.diff <- peninsula.sc - peninsula.so\r\nnotrip.s.diff <- notrip.sc - notrip.so\r\n\r\nshares[,1] <- marin.so\r\nshares[,2] <- eastbay.so\r\nshares[,3] <- bayshore.so\r\nshares[,4] <- peninsula.so\r\nshares[,5] <- notrip.so\r\nshares[,6] <- marin.sc\r\nshares[,7] <- eastbay.sc\r\nshares[,8] <- bayshore.sc\r\nshares[,9] <- peninsula.sc\r\nshares[,10] <- notrip.sc\r\nshares[,11] <- marin.s.diff \r\nshares[,12] <- eastbay.s.diff \r\nshares[,13] <- bayshore.s.diff\r\nshares[,14] <- peninsula.s.diff\r\nshares[,15] <- notrip.s.diff\r\n\t\r\nquantiles <- apply(shares, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(shares, 2, sd)\r\nfirst.differences <- cbind(t(quantiles), sds)\r\ncolnames(first.differences) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(first.differences) <- c(\"Baseline: Marin\", \"Baseline: East Bay\", \"Baseline: Bayshore\", \"Baseline: Peninsula\", \"Baseline: No Trip\", \"Counterfactual: Marin\", \"Counterfactual: East Bay\", \"Counterfactual: Bayshore\", \"Counterfactual: Peninsula\", \"Counterfactual: No Trip\", \"Difference: Marin\", \"Difference: East Bay\", \"Difference: Bayshore\", \"Difference: Peninsula\", \"Difference: No Trip\")\r\nprint(round(first.differences, digits=3))\r\n\r\n\r\n###############\r\n## Table 6.7 ##\r\n###############\r\n\r\ncoeffs <- cosco.busan.mxl$coefficients\r\ncovmat <- vcov(cosco.busan.mxl)\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, coeffs, covmat)\r\nR <- 500\r\nhalton.seq <- qnorm(halton(R, dim=6))\r\n\r\n## observed\r\n\r\nobserved.x <- with(cb.data, data.frame(\r\ntravelcost = travelcost,\r\nbridge = bridge,\r\nmarin = marin,\r\neastbay = eastbay, \r\nbayshore = bayshore,\r\npeninsula = peninsula,\r\nid = idx,\r\nweights = wts\r\n))\r\n\r\nid.weights <- observed.x$weights[observed.x$id.alt==1]\r\n\r\nme.MEM.travelcost <- matrix(0, nrow(betadraw), 1)\r\ncme.MEM.travelcost21 <- matrix(0, nrow(betadraw), 1)\r\ncme.MEM.travelcost23 <- matrix(0, nrow(betadraw), 1)\r\ncme.MEM.travelcost24 <- matrix(0, nrow(betadraw), 1)\r\ncme.MEM.travelcost25 <- matrix(0, nrow(betadraw), 1)\r\n\r\nme.AME.travelcost.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==4,]))\r\ncme.AME.travelcost21.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==1,]))\r\ncme.AME.travelcost23.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==2,]))\r\ncme.AME.travelcost24.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==3,]))\r\ncme.AME.travelcost25.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==5,]))\r\n\r\nprobs.region1.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==1,]))\r\nprobs.region2.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==2,]))\r\nprobs.region3.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==3,]))\r\nprobs.region4.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==4,]))\r\nprobs.region5.all <- matrix(0, nrow(betadraw), nrow(observed.x[observed.x$id.alt==5,]))\r\n\r\nprobs.region1.all.m <- matrix(0, nrow(betadraw), 1)\r\nprobs.region2.all.m <- matrix(0, nrow(betadraw), 1)\r\nprobs.region3.all.m <- matrix(0, nrow(betadraw), 1)\r\nprobs.region4.all.m <- matrix(0, nrow(betadraw), 1)\r\nprobs.region5.all.m <- matrix(0, nrow(betadraw), 1)\r\n\r\nfor (i in 1:R) {\r\n\r\n\ttravelcost <- -1 * exp(betadraw[,\"n.travelcost\"] + (halton.seq[i,1] * abs(betadraw[,\"sd.n.travelcost\"])))\r\n\tbridge <- betadraw[,\"bridge\"] + (halton.seq[i,2] * abs(betadraw[,\"sd.bridge\"]))\r\n\tmarin <- betadraw[,\"marin\"] + (halton.seq[i,3] * abs(betadraw[,\"sd.marin\"]))\r\n\teastbay <- betadraw[,\"eastbay\"] + (halton.seq[i,4] * abs(betadraw[,\"sd.eastbay\"]))\r\n\tbayshore <- betadraw[,\"bayshore\"] + (halton.seq[i,5] * abs(betadraw[,\"sd.bayshore\"]))\r\n\tpeninsula <- betadraw[,\"peninsula\"] + (halton.seq[i,6] * abs(betadraw[,\"sd.peninsula\"]))\r\n\r\n\tbeta.R <- cbind(travelcost, bridge, marin, eastbay, bayshore, peninsula)\r\n\t\r\n\t# MEM\r\n\t\r\n\texb.region1.m <- exp(beta.R %*% colMeans(subset(observed.x, id.alt==1, select=c(1:6))))\r\n\texb.region2.m <- exp(beta.R %*% colMeans(subset(observed.x, id.alt==2, select=c(1:6))))\r\n\texb.region3.m <- exp(beta.R %*% colMeans(subset(observed.x, id.alt==3, select=c(1:6))))\r\n\texb.region4.m <- exp(beta.R %*% colMeans(subset(observed.x, id.alt==4, select=c(1:6))))\r\n\texb.region5.m <- exp(beta.R %*% colMeans(subset(observed.x, id.alt==5, select=c(1:6))))\r\n\texb.all.m <- exb.region1.m + exb.region2.m + exb.region3.m + exb.region4.m + exb.region5.m\r\n\t\r\n\tprobs.region1.m <- exb.region1.m/exb.all.m \r\n\tprobs.region2.m <- exb.region2.m/exb.all.m\r\n\tprobs.region3.m <- exb.region3.m/exb.all.m\r\n\tprobs.region4.m <- exb.region4.m/exb.all.m\r\n\tprobs.region5.m <- exb.region5.m/exb.all.m\r\n\t\r\n\tprobs.region1.all.m <- probs.region1.all.m + (probs.region1.m * (1/R))\r\n\tprobs.region2.all.m <- probs.region2.all.m + (probs.region2.m * (1/R))\r\n\tprobs.region3.all.m <- probs.region3.all.m + (probs.region3.m * (1/R))\r\n\tprobs.region4.all.m <- probs.region4.all.m + (probs.region4.m * (1/R))\r\n\tprobs.region5.all.m <- probs.region5.all.m + (probs.region5.m * (1/R))\r\n\t\r\n\t## marginal effects for East Bay\r\n\tme.MEM.travelcost <- me.MEM.travelcost + (travelcost * (probs.region2.m * (1 - probs.region2.m)) * (1/R)) \r\n\r\n\t## cross-marginal effects\r\n\tcme.MEM.travelcost21 <- cme.MEM.travelcost21 + ((-1 * travelcost * (probs.region1.m * probs.region2.m)) * (1/R)) \r\n\tcme.MEM.travelcost23 <- cme.MEM.travelcost23 + ((-1 * travelcost * (probs.region3.m * probs.region2.m)) * (1/R))\r\n\tcme.MEM.travelcost24 <- cme.MEM.travelcost24 + ((-1 * travelcost * (probs.region4.m * probs.region2.m)) * (1/R))\r\n\tcme.MEM.travelcost25 <- cme.MEM.travelcost25 + ((-1 * travelcost * (probs.region5.m * probs.region2.m)) * (1/R))\r\n\t\r\n\t\r\n\t# AME\r\n\t\r\n\texb.region1 <- exp(beta.R %*% t(subset(observed.x, id.alt==1, select=c(1:6))))\r\n\texb.region2 <- exp(beta.R %*% t(subset(observed.x, id.alt==2, select=c(1:6))))\r\n\texb.region3 <- exp(beta.R %*% t(subset(observed.x, id.alt==3, select=c(1:6))))\r\n\texb.region4 <- exp(beta.R %*% t(subset(observed.x, id.alt==4, select=c(1:6))))\r\n\texb.region5 <- exp(beta.R %*% t(subset(observed.x, id.alt==5, select=c(1:6))))\r\n\texb.all <- exb.region1 + exb.region2 + exb.region3 + exb.region4 + exb.region5\r\n\t\r\n\tprobs.region1 <- exb.region1/exb.all \r\n\tprobs.region2 <- exb.region2/exb.all\r\n\tprobs.region3 <- exb.region3/exb.all\r\n\tprobs.region4 <- exb.region4/exb.all\r\n\tprobs.region5 <- exb.region5/exb.all\r\n\t\r\n\tprobs.region1.all <- probs.region1.all + (probs.region1 * (1/R))\r\n\tprobs.region2.all <- probs.region2.all + (probs.region2 * (1/R))\r\n\tprobs.region3.all <- probs.region3.all + (probs.region3 * (1/R))\r\n\tprobs.region4.all <- probs.region4.all + (probs.region4 * (1/R))\r\n\tprobs.region5.all <- probs.region5.all + (probs.region5 * (1/R))\r\n\t\r\n\t## marginal effects for Bayshore\r\n\tme.AME.travelcost.all <- me.AME.travelcost.all + ((travelcost * (probs.region2 * (1 - probs.region2))) * (1/R)) \r\n\r\n\t## cross-marginal effects\r\n\tcme.AME.travelcost21.all <- cme.AME.travelcost21.all + ((-1 * travelcost * (probs.region1 * probs.region2)) * (1/R)) \r\n\tcme.AME.travelcost23.all <- cme.AME.travelcost23.all + ((-1 * travelcost * (probs.region3 * probs.region2)) * (1/R))\r\n\tcme.AME.travelcost24.all <- cme.AME.travelcost24.all + ((-1 * travelcost * (probs.region4 * probs.region2)) * (1/R))\r\n\tcme.AME.travelcost25.all <- cme.AME.travelcost25.all + ((-1 * travelcost * (probs.region5 * probs.region2)) * (1/R))\r\n\t\r\n}\r\n\r\nme.AME.travelcost <- colSums(apply(me.AME.travelcost.all, 1, function(x) {x * id.weights}))/sum(id.weights)\r\ncme.AME.travelcost21 <- colSums(apply(cme.AME.travelcost21.all, 1, function(x) {x * id.weights}))/sum(id.weights) \r\ncme.AME.travelcost23 <- colSums(apply(cme.AME.travelcost23.all, 1, function(x) {x * id.weights}))/sum(id.weights) \r\ncme.AME.travelcost24 <- colSums(apply(cme.AME.travelcost24.all, 1, function(x) {x * id.weights}))/sum(id.weights) \r\ncme.AME.travelcost25 <- colSums(apply(cme.AME.travelcost25.all, 1, function(x) {x * id.weights}))/sum(id.weights) \r\n\r\n## Elasticities\r\n\r\ntravelcost.2 <- observed.x[observed.x$id.alt==2, grep(\"travelcost\", colnames(observed.x))]\r\ntravelcost.2.m <- mean(observed.x[observed.x$id.alt==2, grep(\"travelcost\", colnames(observed.x))])\r\n\r\n## elasticities for East Bay -- MEM\r\ne.MEM.travelcost <- me.MEM.travelcost * (travelcost.2.m / probs.region2.all.m)\r\n\r\n\r\n## elasticities for East Bay -- AME\r\ne.travelcost <- me.AME.travelcost.all * t(travelcost.2 / t(probs.region2.all))\r\ne.AME.travelcost <- colSums(apply(e.travelcost, 1, function(x) {x * id.weights}))/sum(id.weights)\r\n\r\n## cross-elasticities -- MEM\r\nce.MEM.travelcost21 <- cme.MEM.travelcost21 * (travelcost.2.m/probs.region1.all.m)\r\nce.MEM.travelcost23 <- cme.MEM.travelcost23 * (travelcost.2.m/probs.region3.all.m)\r\nce.MEM.travelcost24 <- cme.MEM.travelcost24 * (travelcost.2.m/probs.region4.all.m)\r\nce.MEM.travelcost25 <- cme.MEM.travelcost25 * (travelcost.2.m/probs.region5.all.m)\r\n\r\n## cross-elasticities -- AME\r\nce.travelcost21 <- cme.AME.travelcost21.all * t(apply(probs.region1.all, 1, function(x){travelcost.2/x}))\r\nce.travelcost23 <- cme.AME.travelcost23.all * t(apply(probs.region3.all, 1, function(x){travelcost.2/x}))\r\nce.travelcost24 <- cme.AME.travelcost24.all * t(apply(probs.region4.all, 1, function(x){travelcost.2/x}))\r\nce.travelcost25 <- cme.AME.travelcost25.all * t(apply(probs.region5.all, 1, function(x){travelcost.2/x}))\r\n\r\nce.AME.travelcost21 <- colSums(apply(ce.travelcost21, 1, function(x) {x * id.weights}))/sum(id.weights) \r\nce.AME.travelcost23 <- colSums(apply(ce.travelcost23, 1, function(x) {x * id.weights}))/sum(id.weights) \r\nce.AME.travelcost24 <- colSums(apply(ce.travelcost24, 1, function(x) {x * id.weights}))/sum(id.weights) \r\nce.AME.travelcost25 <- colSums(apply(ce.travelcost25, 1, function(x) {x * id.weights}))/sum(id.weights) \r\n\r\n# note marginal effects are multiplied by 100 for ease of interpretation\r\nmargins <- cbind(\r\nme.AME.travelcost, me.MEM.travelcost, \r\ncme.AME.travelcost21, cme.AME.travelcost23, cme.AME.travelcost24, cme.AME.travelcost25, \r\ncme.MEM.travelcost21, cme.MEM.travelcost23, cme.MEM.travelcost24, cme.MEM.travelcost25\r\n) * 100\r\n\r\nelasticities <- cbind(\r\ne.AME.travelcost, e.MEM.travelcost,\r\nce.AME.travelcost21, ce.AME.travelcost23, ce.AME.travelcost24, ce.AME.travelcost25,\r\nce.MEM.travelcost21, ce.MEM.travelcost23, ce.MEM.travelcost24, ce.MEM.travelcost25\r\n)\r\n\r\nall.results <- cbind(margins, elasticities)\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nmarginal.effects <- cbind(t(quantiles), sds) \r\ncolnames(marginal.effects) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(marginal.effects) <- c(\"East Bay: AME\", \"East Bay: MEM\", \"Marin: Average CME\", \"Bayshore: Average CME\", \"Peninsula: Average CME\", \"No Trip: Average CME\", \"Marin: CME at Mean\", \"Bayshore: CME at Mean\", \"Peninsula: CME at Mean\", \"No Trip: CME at Mean\", \"East Bay: Average Elasticity\", \"East Bay: Elasticity at the Mean\", \"Marin: Average CE\", \"Bayshore: Average CE\", \"Peninsula: Average CE\", \"No Trip: Average CE\", \"Marin: CE at Mean\", \"Bayshore: CE at Mean\", \"Peninsula: CE at Mean\", \"No Trip: CE at Mean\")\r\nprint(round(marginal.effects, digits=3))\r\n\r\n\r\n## WTP calculation ##\r\n\r\nwtp.summary <- matrix(NA, ndraws, 2)\r\n\r\nfor (i in 1:ndraws) {\r\n\r\n\ttravelcost <- -1 * exp(betadraw[i,\"n.travelcost\"] + (halton.seq[,1] * abs(betadraw[i,\"sd.n.travelcost\"])))\r\n\tbridge <- betadraw[i,\"bridge\"] + (halton.seq[,2] * abs(betadraw[i,\"sd.bridge\"]))\r\n\t\r\n\tall.bridge <- expand.grid(bridge, travelcost)\r\n\twtp.bridge <- all.bridge[,1]/(-1 * all.bridge[,2])\r\n\twtp.summary[i,1] <- median(wtp.bridge)\r\n\twtp.summary[i,2] <- mean(wtp.bridge)\r\n\t\r\n}\r\n\r\nquantiles <- apply(wtp.summary, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(wtp.summary, 2, sd)\r\nwtp.all <- cbind(t(quantiles), sds) \r\ncolnames(wtp.all ) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(wtp.all ) <- c(\"Median WTP\", \"Mean WTP\")\r\nprint(round(wtp.all , digits=3))\r\n\r\n\r\n\r\n###############\r\n## Table 6.8 ##\r\n###############\r\n\r\ncoeffs <- cosco.busan.mxl$coefficients\r\ncovmat <- vcov(cosco.busan.mxl)\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, coeffs, covmat)\r\nintdraws <- 500\r\nhalton.seq <- qnorm(halton(intdraws, dim=6))\r\n\r\n## observed\r\n\r\nobserved.x <- with(cb.data, data.frame(\r\ntravelcost = travelcost,\r\nbridge = bridge,\r\nmarin = marin,\r\neastbay = eastbay, \r\nbayshore = bayshore,\r\npeninsula = peninsula,\r\nid = idx,\r\nweights = wts\r\n))\r\n\r\np.01 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.02 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.03 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.04 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.05 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\np.tr1 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.tr2 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.tr3 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.tr4 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.tr5 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\np.b1 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.b2 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.b3 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.b4 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\np.b5 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\n# travelcost\r\nobserved.x.tr <- observed.x\r\nobserved.x.tr[,\"travelcost\"][observed.x.tr[,\"id.alt\"] != 5] <- observed.x.tr[,\"travelcost\"][observed.x.tr[,\"id.alt\"] != 5] + 1\r\n\r\n# bridge\r\nobserved.x.b <- observed.x\r\nobserved.x.b[,\"bridge\"][observed.x.b[\"id.alt\"] != 5] <- observed.x.b[\"bridge\"][observed.x.b[\"id.alt\"] != 5] + 1\r\n\r\nfor (i in 1:ndraws){\r\n\r\n\ttravelcost <- -1 * exp(betadraw[i,\"n.travelcost\"] + (halton.seq[,1] * abs(betadraw[i,\"sd.n.travelcost\"])))\r\n\tbridge <- betadraw[i,\"bridge\"] + (halton.seq[,2] * abs(betadraw[i,\"sd.bridge\"]))\r\n\tmarin <- betadraw[i,\"marin\"] + (halton.seq[,3] * abs(betadraw[i,\"sd.marin\"]))\r\n\teastbay <- betadraw[i,\"eastbay\"] + (halton.seq[,4] * abs(betadraw[i,\"sd.eastbay\"]))\r\n\tbayshore <- betadraw[i,\"bayshore\"] + (halton.seq[,5] * abs(betadraw[i,\"sd.bayshore\"]))\r\n\tpeninsula <- betadraw[i,\"peninsula\"] + (halton.seq[,6] * abs(betadraw[i,\"sd.peninsula\"]))\r\n\r\n\tbeta.R <- cbind(travelcost, bridge, marin, eastbay, bayshore, peninsula)\r\n\t\r\n\texb.region1.0 <- exp(beta.R %*% t(subset(observed.x, id.alt==1, select=c(1:6))))\r\n\texb.region2.0 <- exp(beta.R %*% t(subset(observed.x, id.alt==2, select=c(1:6))))\r\n\texb.region3.0 <- exp(beta.R %*% t(subset(observed.x, id.alt==3, select=c(1:6))))\r\n\texb.region4.0 <- exp(beta.R %*% t(subset(observed.x, id.alt==4, select=c(1:6))))\r\n\texb.region5.0 <- exp(beta.R %*% t(subset(observed.x, id.alt==5, select=c(1:6))))\r\n\texb.all.0 <- exb.region1.0 + exb.region2.0 + exb.region3.0 + exb.region4.0 + exb.region5.0\r\n\t\r\n\tp.01[i,] <- colMeans(exb.region1.0/exb.all.0)\r\n\tp.02[i,] <- colMeans(exb.region2.0/exb.all.0)\r\n\tp.03[i,] <- colMeans(exb.region3.0/exb.all.0)\r\n\tp.04[i,] <- colMeans(exb.region4.0/exb.all.0)\r\n\tp.05[i,] <- colMeans(exb.region5.0/exb.all.0)\r\n\r\n\texb.region1.tr <- exp(beta.R %*% t(subset(observed.x.tr, id.alt==1, select=c(1:6))))\r\n\texb.region2.tr <- exp(beta.R %*% t(subset(observed.x.tr, id.alt==2, select=c(1:6))))\r\n\texb.region3.tr <- exp(beta.R %*% t(subset(observed.x.tr, id.alt==3, select=c(1:6))))\r\n\texb.region4.tr <- exp(beta.R %*% t(subset(observed.x.tr, id.alt==4, select=c(1:6))))\r\n\texb.region5.tr <- exp(beta.R %*% t(subset(observed.x.tr, id.alt==5, select=c(1:6))))\r\n\texb.all.tr <- exb.region1.tr + exb.region2.tr + exb.region3.tr + exb.region4.tr + exb.region5.tr\r\n\t\r\n\tp.tr1[i,] <- colMeans(exb.region1.tr/exb.all.tr)\r\n\tp.tr2[i,] <- colMeans(exb.region2.tr/exb.all.tr)\r\n\tp.tr3[i,] <- colMeans(exb.region3.tr/exb.all.tr)\r\n\tp.tr4[i,] <- colMeans(exb.region4.tr/exb.all.tr)\r\n\tp.tr5[i,] <- colMeans(exb.region5.tr/exb.all.tr)\r\n\t\r\n\texb.region1.b <- exp(beta.R %*% t(subset(observed.x.b, id.alt==1, select=c(1:6))))\r\n\texb.region2.b <- exp(beta.R %*% t(subset(observed.x.b, id.alt==2, select=c(1:6))))\r\n\texb.region3.b <- exp(beta.R %*% t(subset(observed.x.b, id.alt==3, select=c(1:6))))\r\n\texb.region4.b <- exp(beta.R %*% t(subset(observed.x.b, id.alt==4, select=c(1:6))))\r\n\texb.region5.b <- exp(beta.R %*% t(subset(observed.x.b, id.alt==5, select=c(1:6))))\r\n\texb.all.b <- exb.region1.b + exb.region2.b + exb.region3.b + exb.region4.b + exb.region5.b\r\n\t\r\n\tp.b1[i,] <- colMeans(exb.region1.b/exb.all.b)\r\n\tp.b2[i,] <- colMeans(exb.region2.b/exb.all.b)\r\n\tp.b3[i,] <- colMeans(exb.region3.b/exb.all.b)\r\n\tp.b4[i,] <- colMeans(exb.region4.b/exb.all.b)\r\n\tp.b5[i,] <- colMeans(exb.region5.b/exb.all.b)\r\n\t\r\n\t\r\n}\r\n\r\nid.weights <- cb.data$wts\r\n\r\nt1 <- (p.tr1 / p.tr5) / (p.01 / p.05)\r\nt2 <- (p.tr2 / p.tr5) / (p.02 / p.05)\r\nt3 <- (p.tr3 / p.tr5) / (p.03 / p.05)\r\nt4 <- (p.tr4 / p.tr5) / (p.04 / p.05)\r\n\r\nb1 <- (p.b1 / p.b5) / (p.01 / p.05)\r\nb2 <- (p.b2 / p.b5) / (p.02 / p.05)\r\nb3 <- (p.b3 / p.b5) / (p.03 / p.05)\r\nb4 <- (p.b4 / p.b5) / (p.04 / p.05)\r\n\r\nOR.tr.1.w <- colSums(apply(t1, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.tr.2.w <- colSums(apply(t2, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.tr.3.w <- colSums(apply(t3, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.tr.4.w <- colSums(apply(t4, 1, function(x) {x * id.weights}))/sum(id.weights)\r\n\r\nOR.b.1.w <- colSums(apply(b1, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.b.2.w <- colSums(apply(b2, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.b.3.w <- colSums(apply(b3, 1, function(x) {x * id.weights}))/sum(id.weights)\r\nOR.b.4.w <- colSums(apply(b4, 1, function(x) {x * id.weights}))/sum(id.weights)\r\n\r\nOR <- cbind(OR.tr.1.w, OR.tr.2.w, OR.tr.3.w, OR.tr.4.w, OR.b.1.w, OR.b.2.w, OR.b.3.w, OR.b.4.w)\r\nquantiles <- apply(OR, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(OR, 2, sd)\r\npop.odds <- cbind(t(quantiles), sds)\r\ncolnames(pop.odds) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(pop.odds) <- c(\"Travel Cost: Marin\", \"Travel Cost: East Bay\", \"Travel Cost: Bayshore\", \"Travel Cost: Peninsula\", \"Bridge Crossing: Marin\", \"Bridge Crossing: East Bay\", \"Bridge Crossing: Bayshore\", \"Bridge Crossing: Peninsula\")\r\nprint(round(pop.odds, digits=3))\r\n\r\n\r\n", "meta": {"hexsha": "a8d19738f7beaad83f800f3c2a0414b46edd6493", "size": 24420, "ext": "r", "lang": "R", "max_stars_repo_path": "R Code/Section6_Part2.r", "max_stars_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_stars_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "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 Code/Section6_Part2.r", "max_issues_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_issues_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "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 Code/Section6_Part2.r", "max_forks_repo_name": "GarrettGlasgow/interpreting-discrete-choice-models", "max_forks_repo_head_hexsha": "918a5cc6ee3b291c8ae849f7caa474849b451b22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-21T12:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T12:26:06.000Z", "avg_line_length": 46.8714011516, "max_line_length": 514, "alphanum_fraction": 0.644963145, "num_tokens": 8614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385680609488}} {"text": "# Master Thesis Project - Extreme Value Theory\n# For each sample, ordering the data and comparing\n# the ordered sample to the quantiles of the \n# extreme law fitting the tail of the original\n# sample\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"loadStockData_plain.r\")\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Loading the original data for the five stocks then\n# getting the LVMH and the Total data\ndf_plain <- loadStockData_plain(CHOICE)\n\n# Computing the 95 % - quantiles for each of the stocks\nquantiles <- c(quantile(df_plain[[1]],0.95), quantile(df_plain[[2]],0.95), quantile(df_plain[[3]],0.975),\n\t\t\t\t\tquantile(df_plain[[4]],0.95), quantile(df_plain[[5]],0.95))\n\t\t\t\t\t\n# Getting the data above the threshold\ndata_bnp <- df_plain[[1]]\ndata_bnp <- data_bnp[data_bnp > quantiles[1]]\n\ndata_carrefour <- df_plain[[2]]\ndata_carrefour <- data_carrefour[data_carrefour > quantiles[2]]\n\ndata_lvmh <- df_plain[[3]]\ndata_lvmh <- data_lvmh[data_lvmh > quantiles[3]]\n\ndata_sanofi <- df_plain[[4]]\ndata_sanofi <- data_sanofi[data_sanofi > quantiles[4]]\n\ndata_total <- df_plain[[5]]\ndata_total <- data_total[data_total > quantiles[5]]\n\nstr(gev.fit(data_total))\n# Fitting the data, and getting the corresponding location, scale and \n# shape parameters respectively, for each stock\nbnp_fit <- (gev.fit(data_bnp))\ncarrefour_fit <- gev.fit(data_carrefour)\nlvmh_fit <- gev.fit(data_lvmh)\nsanofi_fit <- gev.fit(data_sanofi)\ntotal_fit <- gev.fit(data_total)\n\nparams_bnp <- bnp_fit$mle\nparams_carrefour <- carrefour_fit$mle\nparams_lvmh <- lvmh_fit$mle\nparams_sanofi <- sanofi_fit$mle\nparams_total <- total_fit$mle\n\n# Ordering the samples (increasing sort)\ndata_bnp <- sort(df_plain[[1]])\ndata_carrefour <- sort(df_plain[[2]])\ndata_lvmh <- sort(df_plain[[3]])\ndata_sanofi <- sort(df_plain[[4]])\ndata_total <- sort(df_plain[[5]])\n\n# Vector of the quantiles we want to plot\nq <- seq(0.99/800,0.99,0.99/800)\n\nplot(data_bnp, col = 'grey', type = 'l')\ngev_bnp <- qgev(q,params_bnp[3],params_bnp[1],params_bnp[2])\nlines(gev_bnp, col = 'red')\nprint(bnp_fit$mle)\nprint(carrefour_fit$mle)\nprint(lvmh_fit$mle)\nprint(sanofi_fit$mle)\nprint(total_fit$mle)\n\nquartz()\npng(file = \"DataVSQuantiles_BNP.png\")\nplot(data_bnp, col = 'green', type = 'l', main = \"Sorted BNP Paribas stock prices and quantiles of the extreme law\")\ngev_bnp <- qgev(q,params_bnp[3],params_bnp[1],params_bnp[2])\nlines(gev_bnp, col = 'black')\ndev.off()\ngraphics.off()\n\nquartz()\npng(file = \"DataVSQuantiles_Carrefour.png\")\nplot(data_carrefour, col = 'red', type = 'l', main = \"Sorted Carrefour stock prices and quantiles of the extreme law\")\ngev_carrefour <- qgev(q,params_carrefour[3],params_carrefour[1],params_carrefour[2])\nlines(gev_carrefour, col = 'black')\ndev.off()\ngraphics.off()\n\nquartz()\npng(file = \"DataVSQuantiles_LVMH.png\")\nplot(data_lvmh, col = 'yellow', type = 'l', main = \"Sorted LVMH stock prices and quantiles of the extreme law\")\ngev_lvmh <- qgev(q,params_lvmh[3],params_lvmh[1],params_lvmh[2])\nlines(gev_lvmh, col = 'black')\ndev.off()\ngraphics.off()\n\nquartz()\npng(file = \"DataVSQuantiles_Sanofi.png\")\nplot(data_sanofi, col = 'grey', type = 'l', main = \"Sorted Sanofi stock prices and quantiles of the extreme law\")\ngev_sanofi <- qgev(q,params_sanofi[3],params_sanofi[1],params_sanofi[2])\nlines(gev_sanofi, col = 'black')\ndev.off()\ngraphics.off()\n\nquartz()\npng(file = \"DataVSQuantiles_Total.png\")\nplot(data_total, col = 'blue', type = 'l', main = \"Sorted Total stock prices and quantiles of the extreme law\")\ngev_total <- qgev(q,params_total[3],params_total[1],params_total[2])\nlines(gev_total, col = 'black')\ndev.off()\ngraphics.off()\n\n\n\n\n\n", "meta": {"hexsha": "1c134c3e5c0e0e158809a50ccb47bb729da261aa", "size": 3995, "ext": "r", "lang": "R", "max_stars_repo_path": "r_final_task/DataVSQuantiles.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_final_task/DataVSQuantiles.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_final_task/DataVSQuantiles.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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.7307692308, "max_line_length": 118, "alphanum_fraction": 0.714893617, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6881649063481133}} {"text": "Forward <- function(Obs, Ini, A, E){\n # Takes a sequence of observations, calculate forward probability matrix\n #\n # Args: \n # Obs: a numeric vector\n # Ini: q_start to q_1 prob distribution\n # A: Trans matrix\n # E: Emission matrix, e_q\\sigma\n #\n # Output: Forward matrix: F_qi, row is state, column is time index\n nQ <- dim(A)[1]\n n <- length(Obs)\n a <- matrix(Ini * E[, Obs[1]], nQ, 1)\n for (i in 2:n){\n temp <- a[, i-1] * A * (rep(1, nQ) %*% t(E[, Obs[i]]))\n a <- cbind(a, colSums(temp))\n }\n return(a)\n}\n\nBackward <- function(Obs, A, E){\n # Takes a sequence of observations, calculate backward probability matrix\n #\n # Args: \n # Obs: a numeric vector\n # A: Trans matrix\n # E: Emission matrix, e_q\\sigma\n #\n # Output: Backward matrix: F_qi, row is state, column is time index\n nQ <- dim(A)[1]\n n <- length(Obs)\n b <- matrix(rep(1, nQ), nQ, 1)\n for (i in (n - 1):1){\n temp <- A * (rep(1, nQ) %*% t(E[, Obs[i + 1]])) * (rep(1, nQ) %*% t(b[, 1]))\n b <- cbind(rowSums(temp), b)\n }\n return(b)\n}\n\nSoftCoding <- function(Obs, Ini, A, E){\n # Takes a sequence of observations, calculate posterior distribution\n #\n # Args: \n # Obs: a numeric vector\n # Ini: q_start to q_1 prob distribution\n # A: Trans matrix\n # E: Emission matrix, e_q\\sigma\n #\n # Output:\n # Probability matrix of posterior distribution at each index(time)\n #\n b <- Backward(Obs, A, E)\n f <- Forward(Obs, Ini, A, E)\n fb <- f * b\n output <- apply(fb, 2, function(x) x / sum(x))\n return(t(output))\n}\n\nBW <- function(nQ, nS, Obs, Ini = NULL, epsilon = 1e-09, maxIter = 100, IniA = NULL, IniE = NULL){\n # Take a list of observations, return HMM parameters\n #\n # Args:\n # nQ: number of states\n # nS: number of alphabet\n #\n # Output:\n # Ini: q_start to q_1 distribution \n # A: transition matrix\n # E: emission matrix\n #\n # Initialization\n n <- length(Obs)\n if(is.null(IniA)){\n A <- matrix(abs(runif(nQ * nQ)), nQ, nQ)\n A <- t(apply(A, 1, function(x) x / sum(x)))\n } else {\n A <- IniA\n }\n if(is.null(IniE)){\n E <- matrix(abs(runif(nQ * nS)), nQ, nS)\n E <- t(apply(E, 1, function(x) x / sum(x)))\n } else {\n E <- IniE\n }\n \n if(is.null(Ini)){\n Ini <- abs(runif(nQ)) \n Ini <- Ini / sum(Ini)\n }\n iter <- 1\n diff <- 1\n # EM algorithm\n while (diff > epsilon && iter <= maxIter){\n alpha <- Forward(Obs, Ini, A, E)\n beta <- Backward(Obs, A, E)\n alphabeta <- alpha * beta\n gamma <- apply(alphabeta, 2, function(x) x / sum(x))\n A.nu <- 0\n for (i in 1:(n - 1)){\n A.nu <- A.nu + alpha[, i] * A * (rep(1, nQ) %*% t(E[, Obs[i+1]])) * (rep(1, nQ) %*% t(beta[, i+1]))\n }\n newA <- t(apply(A.nu, 1, function(x) x / sum(x))) \n E.nu <- NULL\n for (i in 1:nS){\n E.nu <- cbind(E.nu, rowSums(alphabeta[, which(Obs == i)]))\n }\n newE <- t(apply(E.nu, 1, function(x) x / sum(x)))\n diff <- sqrt(sum((newA - A) ^ 2)) + sqrt(sum((newE - E) ^ 2))\n A <- newA\n E <- newE\n Ini <- gamma[, 1]\n iter <- iter + 1\n }\n if(iter == maxIter) print(\"Maximum iteration reached, algorithm didn't converge.\")\n output <- list(Ini = Ini, A = A, E = E, Difference = diff)\n return(output)\n}\n\nlibrary(HMM)\n\nObstest <- c(\"1\", \"2\", \"1\", \"1\", \"2\", \"3\", \"2\", \"3\", \"3\", \"3\")\nIniA <- matrix(c(.75, .25, .25, .75), 2, 2)\nIniE <- matrix(rep(1/3, 6), 2, 3)\nIni <- rep(1/2, 2)\nObs <- as.numeric(Obstest)\nhmm <- initHMM(c(\"1\", \"2\"), c(\"1\", \"2\", \"3\"))\n\nlibrary(microbenchmark)\nmicrobenchmark(BW(2, 3, Obs, Ini, IniA = IniA, IniE = IniE), baumWelch(hmm, Obstest))\n", "meta": {"hexsha": "c5f7421892b8a4f9f0b66cd2ddd5f25e9186d0ab", "size": 3557, "ext": "r", "lang": "R", "max_stars_repo_path": "BaumWelch.r", "max_stars_repo_name": "DeltaMethod721/HMM", "max_stars_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "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": "BaumWelch.r", "max_issues_repo_name": "DeltaMethod721/HMM", "max_issues_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "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": "BaumWelch.r", "max_forks_repo_name": "DeltaMethod721/HMM", "max_forks_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "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.3615384615, "max_line_length": 105, "alphanum_fraction": 0.5499016025, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6881648942981277}} {"text": "#' unlogit\n#'\n#' This function allows you to unlogit (back transform)\n#' @param logit numeric value\n#' @return y unlogit value\n#' @keywords logit\n#' @export\n#' @examples\n#' un_logit(1)\n\nun_logit <- function(logit){\n y = exp(logit)/(1 + exp(logit))\n return(y)\n}\n", "meta": {"hexsha": "f4cbfa802d063dca1ad4be9d8b49f90040673cea", "size": 263, "ext": "r", "lang": "R", "max_stars_repo_path": "R/un_logit.r", "max_stars_repo_name": "kcsamir/mdpop", "max_stars_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-09T11:50:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T11:50:05.000Z", "max_issues_repo_path": "R/un_logit.r", "max_issues_repo_name": "kcsamir/mdpop", "max_issues_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-20T10:32:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-20T10:53:29.000Z", "max_forks_repo_path": "R/un_logit.r", "max_forks_repo_name": "kcsamir/mdpop", "max_forks_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "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.5333333333, "max_line_length": 55, "alphanum_fraction": 0.6577946768, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.688123028788636}} {"text": "# ......................................................................................\n# ..............................Cvičení 4 - Náhodný vektor..............................\n# ..................Martina Litschmannová, Adéla Vrtková, Michal Béreš..................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Příklad ze sbírky ####\n# Náhodný vektor $Z =(Y;X)^T$ má pravděpodobnostní funkci zadanou tabulkou\n# Obrázek viz sbírka úloh.\n# * a) Určete chybějící hodnotu sdružené pravděpodobnostní funkce, ####\n\n\ndata = c(0.01, 0.04, 0.12, \n 0.02, 0.16, 0.07, \n 0.03, 0, 0.06, \n 0.25, 0.05, 0.01)\nP = matrix(data , nrow=3, ncol=4) #případně byrow = ...\nX = c(3, 5, 7)\nY = c(1, 2, 3, 4)\ndimnames(P) = list(X,Y)\nP\n\nsum(P)\n\n# nespoštějte tuto buňku 2krát, jinak si hodnotu zase nastavíte na 0, \n# víte proč?\np_5_3 = 1 - sum(P)\nP[\"5\",\"3\"] = p_5_3\nP\n\n# * b) Určete distribuční funkci ####\n# **Pozor! Vektor Z je $(Y,X)^T$ tedy první parametr je hodnota Y a druhý hodnota X.**\n\n\n# F(2.8; 7.1)\n# = P(Y<2.8,X<7.1)\nP[X<7.1, Y<2.8]\nsum(P[X<7.1, Y<2.8])\n\nF = matrix(rep(0,4*5), nrow=4, ncol=5)\ndimnames(F) = list(c('(-inf,3>', '(3,5>', '(5,7>', '(7,inf)'),\n c('(-inf,1>', '(1,2>', '(2,3>', '(3,4>', '(4,inf)'))\nF\n\n# projdeme řádky a sloupce, vždy si vezmeme jednu hodnotu\n# z příslušného řádku nebo sloupce\nx_vals = c(3,5,7,8)\ny_vals = c(1,2,3,4,5)\nfor(i in 1:4){\n for(j in 1:5){\n x = x_vals[i]\n y = y_vals[j]\n F[i,j] = sum(P[X 2.1 | X < 5.3)\n# = P(Y > 2.1 ∧ X < 5.3) / P(X < 5.3)\nsum(P[X<5.3, Y>2.1])\nsum(P[X<5.3,])\nsum(P[X<5.3, Y>2.1])/sum(P[X<5.3,])\n\n# P(X = 5|Y = 1)\n# = P(X = 5 ∧ Y = 1) / P(Y = 1)\nP['5','1']/sum(P[,'1'])\nP['5','1']/sum(P_y['1'])\n\n# **$P(x|y)=\\frac{P(X=x,Y=y)}{P_Y(y)}$**\n\n\nP_xy = P # má to stejnou velikost, tak si ukradneme formátování\nX_lab = c('3', '5', '7')\nY_lab = c('1', '2', '3', '4')\nfor(x in X_lab){\n for(y in Y_lab){\n P_xy[x, y] = P[x, y]/P_y[y]\n }\n}\nP_xy\ncolSums(P_xy)\n\n# **$P(y|x)$**\n\n\nP_yx = P # má to stejnou velikost, tak si ukradneme formátování\nfor(x in X_lab){\n for(y in Y_lab){\n P_yx[x, y] = P[x, y]/P_x[x]\n }\n}\nP_yx\nrowSums(P_yx)\n\n# * e) zákládní charakteristiky náhodných veličin X a Y ####\n\n\nE_X = sum(X*P_x)\nE_X\nE_XX = sum(X*X*P_x)\nD_X = E_XX - E_X^2\nD_X\n\nE_Y = sum(Y*P_y)\nE_Y\nE_YY = sum(Y*Y*P_y)\nD_Y = E_YY - E_Y^2\nD_Y\n\n# * f) podmíněná střední hodnota E(X|Y = 2) ####\n\n\n# P(x|Y=2)\nP_xy[,'2']\nE_X_Y2 = sum(X*P_xy[,'2'])\nE_X_Y2\n\n# * g) kovariance a korelace ####\n\n\nX_Y = P # matice kde v každé kolonce je hodnota x*y\nfor(x in X){\n for(y in Y){\n X_Y[x==X, y==Y] = x*y \n }\n}\nX_Y\n\n# střední hodnota E(X*Y)\nE_XY = sum(X_Y*P)\nE_XY\n\n# kovariance\ncov_XY = E_XY-E_X*E_Y\ncov_XY\n\n# korelace\ncov_XY/sqrt(D_X*D_Y)\n\n\n\n", "meta": {"hexsha": "b02ce551f1cacb381702b2281de9e606027f3f38", "size": 3291, "ext": "r", "lang": "R", "max_stars_repo_path": "CV4/cv4_NV.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV4/cv4_NV.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV4/cv4_NV.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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.1901840491, "max_line_length": 92, "alphanum_fraction": 0.516560316, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6880751814874497}} {"text": "# Function 'NormMax'\n# Killian Martin--Horgassan\n# 19-02-2015\n\n# Generates the list of maxima [M_1, ..., M_n] of the list of\n# i.i.d random variables [X_1,...,X_n]. Plots the M_i against \n# the i.\n\n# Arguments :\n# - N : number of r.v. X_i\n# - DIST : a vector of N pseudo-random numbers from a certain \n#\t\t\tdistribution.\n# (by default it is a Gaussian of size 10000)\n# RETURNS the list of maxima\n\nNormMax2 <- function(N = 10000, DIST = rnorm(10000,0,1), DIST_name = \"gaussian\") {\n \tListX <- DIST\n \tListMax <- rep(0,N)\n \t\n \tprint(DIST_name)\n \t\n \t# Computes the list of the M_i\n \tfor (i in 1:length(ListMax)) {\n \t\tListMax[i] <- max(ListX[1:i])\n \t}\n \t\n \t# Plots the 1-D scatter plot of the M_i\n \ttitle_1 <- \"1-D scatter plot of the maxima\"\n \txlabel_1 <- expression(M[i])\n \tstripchart(ListMax, xlab = xlabel_1, main = title_1)\n \t\n \t# Opens a new graphic window\n \tquartz()\n \t\n \t# Plots the M_i against the i\n \ttitle_2 <- \"Maxima as a function of the time steps\"\n \txlabel_2 <- \"Time step\"\n \tylabel_2 <- \"Maximum\"\n \tplot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =\n \t\t\ttitle_2)\n \t\n \t# Opens a new graphic windows\n \tquartz()\n \t\n \t# Plot the 1-D scatter plot of the M_i and the M_i against the\n \t# i together in a grid.\n \tpar(mfrow = c(1,2))\n \n \tstripchart(ListMax, xlab = xlabel_1, main = title_1)\n plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =\n \t\t\ttitle_2, pch = 4)\n \tpoints(1:N,sqrt(2*log(1:N)),col=\"cyan\", pch = 3)\n \tlegend(x=\"bottomright\",y=NULL,c(\"Maxima\",\n \t\texpression(\"sqrt(log(n))\")), col = c(\"black\",\"cyan\"),\n \t\tbty=\"o\", pch = c(4,3))\n \t\t\n \t# Exports the plots to a PDF file\n \tpdf(file = \"graphIntroTask2.pdf\", width = 10, height = 8)\n\tpar(mfrow = c(1,2))\n \tstripchart(ListMax, xlab = xlabel_1, main = title_1)\n plot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =\n \t\t\ttitle_2, pch = 4)\n \tpoints(1:N,sqrt(2*log(1:N)),col=\"cyan\", pch = 3)\n \tlegend(x=\"bottomright\",y=NULL,c(\"Maxima\",\n \t\texpression(\"sqrt(log(n))\")), col = c(\"black\",\"cyan\"),\n \t\tbty=\"o\", pch = c(4,3))\n \t#dev.off()\n \t\n \t# Exports the plots to jpeg files for use in the LaTex report\n \t\n \tif (DIST_name == \"gaussian\") {\n \t\tfileName1 <- \"gaussianScatterMaxima2.jpeg\"\n \t\tfileName2 <- \"gaussianMaximaAgainstSteps2.jpeg\"\n \t} else if (DIST_name == \"exponential\") {\n \t\tfileName1 <- \"exponentialScatterMaxima2.jpeg\"\n \t\tfileName2 <- \"exponentialMaximaAgainstSteps2.jpeg\" \t\t\n \t} else {\n \t\tfileName1 <- \"cauchyScatterMaxima2.jpeg\"\n \t\tfileName2 <- \"cauchyMaximaAgainstSteps2.jpeg\" \t \t\t\n \t}\n \t\n \tjpeg(file = fileName1)\n \tstripchart(ListMax, xlab = xlabel_1, main = title_1)\n \t\n \tjpeg(file = fileName2)\n \tplot(ListMax, xlab = xlabel_2, ylab = ylabel_2, main =\n \t\t\ttitle_2)\n \t\t\t\n \tdev.off()\n \t\n\n \t\n \treturn(ListMax)\n }", "meta": {"hexsha": "205eb24ad7b9cfbfd6534878f86ffa11a0b7a965", "size": 2706, "ext": "r", "lang": "R", "max_stars_repo_path": "report/main/R_Files_1/NormMax2.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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": "report/main/R_Files_1/NormMax2.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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": "report/main/R_Files_1/NormMax2.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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.7872340426, "max_line_length": 82, "alphanum_fraction": 0.6393200296, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.6879707121964505}} {"text": " \r\ny1bar=38.48\r\ns1=16.37\r\nn1=40\r\ny2bar=26.93\r\ns2=9.88\r\nn2=40\r\n# test statistic\r\nF=s1^2/s2^2\r\nprint(F)\r\n#critical value\r\nalpha=0.05\r\nf.alpha=qf(1-alpha/2,39,39)\r\n# we reject H0 if F>=f.alpha\r\n \r\n", "meta": {"hexsha": "a40a780bf94ad3a07d232b9311d391d5534012a6", "size": 194, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.5/Ex7_5.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.5/Ex7_5.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH7/EX7.5/Ex7_5.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 12.125, "max_line_length": 29, "alphanum_fraction": 0.6288659794, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6878818367190723}} {"text": "# Master Thesis Project - Extreme Value Theory\n# We assume that the stock prices follow a geometric\n# Brownian motion (Black-Scholes model). We plot the\n# empirical stock price data as well as the simulated\n# geometric Brownian motions associated to them.\n# HERE WE WILL RUN A LARGE NUMBER OF SIMULATIONS\n# AND TAKE THE AVERAGE (for instance 100 simulations)\n# Killian Martin--Horgassan\n# 02-06-2015\n\n# Clear the environment\nrm(list=ls())\n\n# Close all already open graphic windows\ngraphics.off()\n\n# Sourcing the auxiliary files\nsource(\"logGrossReturns.r\")\nsource(\"loadStockData.r\")\nsource(\"loadStockData_plain.r\")\nsource(\"meanAndVarianceDF.r\")\n\n\n# Remark : the csv uses the metastock data format \n# 7 columns : - Ticker (identifier of the stock\n# and stockmarket on which it is listed)\n#\t\t\t\t\t - Date (yyyymmdd)\n#\t\t\t\t\t - Open\n#\t\t\t\t\t - High\n#\t\t\t\t\t - Low\n#\t\t\t\t\t - Close\n#\t\t\t\t\t - Volume\n# By default, the highest price is used i.e. column 3.\nCHOICE <- 3\n\n# Number of simulations\nnb_sim <- 100\n\n# Loading the original data for the five stocks\ndf_plain <- loadStockData_plain(CHOICE)\n\n# Loading the log-gross returns for the five stocks\ndf <- loadStockData(CHOICE)\n\n# Computing the mean and Variances of the stock\nmeanAndVarDF <- meanAndVarianceDF(df)\n\n# Building the Geometric Brownian motion\n\tN = dim(df)[1]\n\tM = dim(df)[2]\n\tc <- rep(0,N)\n\tgeomBMs <- data.frame(c,c,c,c,c)\n\t\n\tmeans <- meanAndVarDF[1]\n\tvars <- meanAndVarDF[2]\n\t\n\t# Time component\n\ttimeSteps = 0:(N-1)\n\nfor (j in 1:nb_sim)\t {\n\t# Brownian motion component\n dis = rnorm(N,0,1)\n dis = cumsum(dis)\n \n\tfor (i in 1:M) {\n\t\tcoeff1 = (means[[1]])[i] - 0.5*(vars[[1]])[i]\n\t\tgeomBMs[i] <- geomBMs[i] + (df_plain[[i]])[1]*exp(coeff1*timeSteps + sqrt((vars[[1]])[i])*dis)\n\t}\t\n} \n\nfor (i in 1:M) {\n\tgeomBMs[i] <- geomBMs[i]/nb_sim \n}\t\n\n\n\n# Plotting the actual stock prices and the corresponding simulations\nx_label <- \"Weekly measurements\"\ny_label <- \"Prices and simulation\"\ntitle1 <- \"BNP Stock\"\ntitle2 <- \"Carrefour Stock\"\ntitle3 <- \"LVMH Stock\"\ntitle4 <- \"Sanofi Stock\"\ntitle5 <- \"Total Stock\"\n\nquartz()\npng(file = \"actualAndSimulated-Averaged.png\")\npar(mfrow = c(3,2))\nplot(df_plain[[1]], pch = 1, col = \"black\", type = 'l', xlab = x_label, ylab = y_label, main = title1)\nlines(geomBMs[[1]], col = 'yellow')\nplot(df_plain[[2]], pch = 1, col = \"blue\", type = 'l', xlab = x_label, ylab = y_label, main = title2)\nlines(geomBMs[[2]], col = \"yellow\")\nplot(df_plain[[3]], pch = 1, col = \"green\", type = 'l', xlab = x_label, ylab = y_label, main = title3)\nlines(geomBMs[[3]], col = \"yellow\")\nplot(df_plain[[4]], pch = 1, col = \"purple\", type = 'l', xlab = x_label, ylab = y_label, main = title4)\nlines(geomBMs[[4]], col = \"yellow\")\nplot(df_plain[[5]], pch = 1, col = \"red\", type = 'l', xlab = x_label, ylab = y_label, main = title5)\nlines(geomBMs[[5]], col = \"yellow\")\ndev.off()\ngraphics.off()\n\n\n\n\n", "meta": {"hexsha": "c58b8b5acfef1c089ed4085a413d7035564361ce", "size": 2894, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_logGrossReturns/simulationFittingGeomBMManySimulations.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_logGrossReturns/simulationFittingGeomBMManySimulations.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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_files_logGrossReturns/simulationFittingGeomBMManySimulations.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "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.5619047619, "max_line_length": 103, "alphanum_fraction": 0.6572218383, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6878632206384325}} {"text": "euclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\ngaussKernel <- function(dist, h) exp(sqrt(h / pi * 0.5) * -0.5 * (dist * h) ^ 2)\n\nparzen <- function(dset, labels, point, h, kernel, dist = euclidean) {\n dsetLength <- length(dset[,1])\n \n uLabels <- unique(labels)\n classScores <- array(0L, dim = c(length(uLabels)))\n names(classScores) = uLabels;\n # classScores[\"undefined\"] <- 0.000001 # not needed for gaussian kernel\n \n for (i in 1:dsetLength) {\n classScores[paste(labels[i])] <- classScores[paste(labels[i])] + kernel(dist(point, dset[i,]), h)\n }\n \n return(classScores)\n}\n\ncomputeMargins <- function(dset, labels) {\n dsetLen <- dim(dset)[1]\n margins <- array(0L, dim = dsetLen)\n for (i in 1:dsetLen) {\n cat(\"\\rProcessing\", i, \"of\", dsetLen)\n classScores <- parzen(dset[-i,], labels[-i], dset[i,], 1.6, gaussKernel)\n \n margins[i] <- classScores[labels[i]] - max(classScores[-as.integer(labels[i])])\n }\n cat(\"\\n\")\n \n return (margins)\n}\n\nremoveNoise <- function(dset, margins) { # returns indices of entries that we should get rid of\n negativeMarginIndices <- which(margins < 0)\n negativeMargins <- margins[negativeMarginIndices]\n negativeMargins <- sort(negativeMargins)\n \n dsetLen <- length(margins)\n diff <- abs(negativeMargins[1:(dsetLen - 1)] - negativeMargins[2:dsetLen])\n \n boundary <- negativeMargins[which.max(diff) + 1]\n \n return (which(margins < boundary))\n}\n\nstolp <- function(dset, labels, maxErrors, reduceNoise = TRUE) {\n margins <- computeMargins(dset, labels)\n \n # selecting one element with max margin from each class\n result <- data.frame()\n resultLabels <- c()\n indexesToExclude <- c()\n if (reduceNoise) {\n indexesToExclude <- removeNoise(dset, margins)\n }\n for (label in unique(labels)) {\n margins <- computeMargins(dset, labels)\n currentBest <- -1\n for (i in 1:length(margins)) {\n if (labels[i] == label && (currentBest == -1 || margins[currentBest] < margins[i])) {\n currentBest <- i\n }\n }\n \n result <- rbind(result, dset[currentBest,])\n resultLabels <- c(resultLabels, paste(labels[currentBest]))\n indexesToExclude <- c(indexesToExclude, currentBest)\n }\n \n n = length(labels)\n # iteratively reducing the error rate\n while (TRUE) {\n minIndex <- 1\n minValue <- 0\n negativeCount <- 0\n for (i in 1:n) {\n scores <- parzen(result, resultLabels, dset[i,], 1.6, gaussKernel)\n \n margin <- scores[paste(labels[i])] - max(scores[names(scores) != paste(labels[i])])\n if (margin < 0) {\n negativeCount <- negativeCount + 1\n }\n if (!(i %in% indexesToExclude) && margin < minValue) {\n minValue <- margin\n minIndex <- i\n }\n }\n \n cat(\"Errors: \", negativeCount, \"\\n\")\n \n if (negativeCount <= maxErrors) break\n \n indexesToExclude <- c(indexesToExclude, minIndex)\n result <- rbind(result, dset[minIndex,])\n resultLabels <- c(resultLabels, paste(labels[minIndex]))\n }\n \n return (list(\"dataset\" = result, \"labels\" = resultLabels))\n}\n\ndrawPlots <- function() {\n colors <- c(\"setosa\" = \"blue\", \"virginica\" = \"red\", \"versicolor\" = \"green\", \"undefined\" = \"grey\")\n opd <- stolp(iris[3:4], iris$Species, 6)\n \n png(sprintf(\"stolp.png\"), width = 1024, height = 700, unit = \"px\", pointsize = 20)\n \n plot(iris[3:4], col = colors[paste(iris$Species)])\n points(opd[['dataset']], pch = 21, bg = colors[opd[['labels']]], col = colors[opd[['labels']]])\n \n dev.off()\n \n xs <- seq(from = 0.5, to = 7.5, by = 0.1)\n ys <- seq(from = -1, to = 3.5, by = 0.1)\n \n kernel <- gaussKernel\n png(sprintf(\"stolp-map.png\"), width = 1024, height = 700, unit = \"px\", pointsize = 20)\n plot(iris[, 3:4], col = colors[paste(iris$Species)], pch=10, asp=1)\n points(opd[['dataset']], pch = 16, col = colors[opd[['labels']]])\n \n all <- length(xs) * length(ys)\n progress = 1\n for (i in xs) {\n for (j in ys) {\n cat(\"\\rProcessing point\", progress, \"of\", all)\n progress <- progress + 1\n result <- parzen(opd[['dataset']], opd[['labels']], c(i, j), 1.6, kernel)\n result <- names(result)[which.max(result)]\n points(i, j, col = colors[result], pch = 21)\n }\n }\n cat(\"\\rDone. \\n\")\n dev.off()\n}\n\ntimeMeasurements <- function () {\n opd <- stolp(iris[3:4], iris$Species, 6)\n startTime <- Sys.time()\n n <- dim(iris)[1]\n for (i in 1:n) {\n parzen(opd[['dataset']], opd[['labels']], iris[i, 3:4], 1.6, gaussKernel)\n }\n finishTime <- Sys.time()\n print(paste(\"Source dataset time: \", finishTime - startTime))\n}\n\n# num <- 56\n# tt <- parzen(iris[-num,3:4], iris$Species[-num], iris[num,3:4], 1.6, gaussKernel)\n\n# print(tt)\n# print(iris$Species[num])\n# opd <- stolp(iris[3:4], iris$Species, 5)\n\n# plot(iris[3:4], col = colors[paste(iris$Species)])\n# points(opd[['dataset']], pch = 21, bg = colors[opd[['labels']]], col = colors[opd[['labels']]])\n\n# drawPlots()\n# timeMeasurements()\n\n\n\n\n", "meta": {"hexsha": "54e32cf6693fcdd02b6bdf7a7542e07abfbb12ef", "size": 4930, "ext": "r", "lang": "R", "max_stars_repo_path": "4 - Selection of reference objects/stolp.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "4 - Selection of reference objects/stolp.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "4 - Selection of reference objects/stolp.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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.8787878788, "max_line_length": 101, "alphanum_fraction": 0.6058823529, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.687863211972591}} {"text": "###FOR CI's log-log transformation_Chourdhury (2002) Non-parametric confidence interval estimation for competing risks analysis: application to contraceptive data\r\n#Run this code first\r\n######CIF ESTIMATES############################################################################################################\r\n\r\n###Heisey and Patterson CIF estimator\r\n\"cause.survival\" = function(table, p)\r\n{\r\n\tassign(\"p\", p)\r\n\t\r\n\t# create tables to hold the results of GKM survival estimates for all events and for cause specific event\r\n\ttemp.all <- summary(survfit(Surv(enter, exit, event) ~ 1, conf.type=\"log-log\",data = table))\r\n\ttemp.s <- summary(survfit(Surv(enter, exit, cause == p) ~ 1, conf.type=\"log-log\",data = table))\r\n\t\r\n\t#combine the two tables so survival of all events can be combined with those of the cause specific events\r\n\ts.df <- data.frame(time = temp.s$time, n.event = temp.s$n.event, n.risk = temp.s$n.risk, survival = temp.s$surv)\r\n\tall.df <- data.frame(time = temp.all$time, n.event = temp.all$n.event, n.risk = temp.all$n.risk, survival = temp.all$surv)\r\n\tall.s.df <- merge(all.df, s.df, by.x = \"time\", by.y = \"time\", all.x = T, suffixes = c(\".all\", \".s\"))\r\n\tassign(\"n\", all.s.df)\r\n\tx <- length(n[,1])\r\n\t\r\n\t#create temporary placeholders for the calculation of the mortality rate and the cause-specific cumulative incidence func.\r\n\ttmp.string <- numeric(x)\r\n\ttmp.string2 <- numeric(x)\r\n\tt <- 1\r\n\r\n\t#cycle through the records of the table, including all events to calculate mortality rate and CIF\r\n\twhile(t <= x) {\r\n\t\ttmp.string[1] <- n$n.event.s[1]/n$n.risk.s[1]\r\n\t\tif (t == 1) tmp.string[t] <- NA else tmp.string[t] <- (n$survival.all[t-1] * n$n.event.s[t])/n$n.risk.s[t]\r\n\t\tif(is.na(tmp.string[t])) tmp.string2[t] <- NA else tmp.string2[t] <- sum(tmp.string[1:t], na.rm = T)\r\n\t\tt = t + 1\r\n\t}\r\n\t\r\n\tMORT <- data.frame(mort.rate = tmp.string)\r\n\tCIF2 <- data.frame(CIF = tmp.string2)\r\n\tCIF.s.all <- cbind(all.s.df, MORT, CIF2)\r\n\r\n# Calculate the variance, standard error and the Confidence Intervals around CIF\r\n\r\nSE <- numeric(x)\r\ntotvar.t <- numeric(x)\r\n\r\n#Reset all temporary variables\r\nt <- 1\r\nj <- 1\r\nIj <- 0\r\ncumvar.p1 <- 0\r\ncumvar.p2 <- 0\r\ncumvar.p3 <- 0\r\n\r\n#loop for the total number of records\r\nwhile (t <= x) \r\n{\r\n It <- CIF.s.all$CIF[t]\r\n if(is.na(It)) {\t\t\r\n\t\tCIF.s.all$cumvar[t] <- \"NA\"\r\n\t\tCIF.s.all$StdErr[t] <- \"NA\"\r\n\t\tCIF.s.all$CI.l[t] <- \"NA\"\r\n\t\tCIF.s.all$CI.u[t] <- \"NA\" \r\n\t\t\r\n\t\tt = t + 1\r\n\t}\r\n else \r\n\t{\r\n\t\twhile (j < t) \r\n\t\t{\r\n\t\tif(is.na(CIF.s.all$CIF[j]))\r\n\t\t\tIj <- Ij\t\t\t\r\n\t else\t\r\n\t\t\tIj <- CIF.s.all$CIF[j]\t\t\r\n cumvar.p1 <- cumvar.p1 + (It - Ij)^2 * (CIF.s.all$n.event.all[j]/(CIF.s.all$n.risk.all[j] * (CIF.s.all$n.risk.all[j] - CIF.s.all$n.event.all[j])))\r\n\r\n\t\tif(!is.na(CIF.s.all$CIF[j]))\r\n\t\t{\r\n\t\t\tif(j == 1)\r\n\t\t\t\tSj3 <- 1\r\n\t\t\telse\r\n\t\t\tSj3 <- CIF.s.all$survival.all[j-1]\t\t\r\n\t\t\tIjc <- CIF.s.all$CIF[j]\r\n\t\t\tcumvar.p3 <- cumvar.p3 + (It - Ijc)*(Sj3)*(CIF.s.all$n.event.all[j] / (CIF.s.all$n.risk.all[j])^2)\r\n\t\t}\r\n\t\tj <- j + 1\r\n \t\t}\r\n\r\n\t\tif (t == 1) \r\n\t\t\tSj2 <- 1 \r\n\t\telse\r\n\t\t\tSj2 <- CIF.s.all$survival.all[t-1] \r\n\t\t\t\t\t\r\n \t\tcumvar.p2 <- (Sj2)^2 * (((CIF.s.all$n.event.all[t])*(CIF.s.all$n.risk.all[t] - CIF.s.all$n.event.all[t]))/(CIF.s.all$n.risk.all[t])^3) + cumvar.p2\r\n\r\n\t\t#total all three components of the variance equation to get the final variance, generate std. err and confidence intervals using log-log transformation\r\n\t\t#Assign all results to the output table\r\n\t\ttotvar.t[t] <- cumvar.p1 + cumvar.p2 - (2 * cumvar.p3)\r\n\t\tCIF.s.all$cumvar[t] <- totvar.t[t] \r\n\t\tSE[t] <- sqrt(totvar.t[t])\r\n\t\tCIF.s.all$StdErr[t] <- SE[t]\r\n\t\tCIF.s.all$CI.l[t] <- CIF.s.all$CIF[t]^(exp((-1.96 * SE[t])/(CIF.s.all$CIF[t]*log(CIF.s.all$CIF[t]))))\r\n\t\tCIF.s.all$CI.u[t] <- CIF.s.all$CIF[t]^(exp((1.96 * SE[t])/(CIF.s.all$CIF[t]*log(CIF.s.all$CIF[t]))))\r\n\t\t \r\n\t\tt = t + 1\r\n\t\tj <- 1\r\n }\r\n\r\ncumvar.p1 <- 0\r\ncumvar.p3 <- 0\r\nIj <- 0\r\nIt <- 0\r\n}\r\n\r\n#Variance calculations end here ----------\r\n\r\n\r\n\r\n\t\r\n\treturn(CIF.s.all)\r\n}\r\n#####End of Heisey and Patterson estimator\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "93b898ef05168c03c49f22ba7edaf1df13b5e7fb", "size": 4014, "ext": "r", "lang": "R", "max_stars_repo_path": "functions/cause_survival.r", "max_stars_repo_name": "heblab/pronghornsurvival", "max_stars_repo_head_hexsha": "03c5e109bcb1d328632584bd56c416af5eceaf09", "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": "functions/cause_survival.r", "max_issues_repo_name": "heblab/pronghornsurvival", "max_issues_repo_head_hexsha": "03c5e109bcb1d328632584bd56c416af5eceaf09", "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": "functions/cause_survival.r", "max_forks_repo_name": "heblab/pronghornsurvival", "max_forks_repo_head_hexsha": "03c5e109bcb1d328632584bd56c416af5eceaf09", "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.6341463415, "max_line_length": 163, "alphanum_fraction": 0.581963129, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6878632046893547}} {"text": "# Group members (Name, Student ID, E-Mail):\n# 1. Baldomero Valdez, Valenzuela, 2905175, baldmer.w@gmail.com\n# 2. Omar Trinidad Gutierrez Mendez, 2850441, omar.vpa@gmail.com\n# 3. Shinho Kang, 2890169, wis.shinho.kang@gmail.com\n\n# size for testing: default 150\nsize = 150\n\n# -----------------------------------------------------------------------------\n# assignment a\n# Implemented in two ways - using dist(), and using self-created function\n# RESULT: results of both ways are exactly same.\n\n# function for calculating Euclidean Distance\neuclidean_distance <- function(p, q) {\n ed = 0\n for (i in 1:4) {\n ed <- ed + (p[,i] - q[,i]) ^ 2\n }\n ed <- sqrt(ed)\n return(ed)\n}\n\ndata(iris) #load iris data\niris2 <- iris[-5] # delete column 5 with string\n# compute distances using dist() function\ndistances <- as.matrix(dist(head(iris2, size)))\n# print(distances)\n\n# compute distances using self-created function\ndistances2 <- matrix(nrow=size, ncol=size)\nfor (p in 1:size) {\n for (q in 1:size) {\n row_p = iris2[p,]\n row_q = iris2[q,]\n distances2[p, q] <- euclidean_distance(row_p, row_q)\n }\n}\n# print(distances2)\n\n# -----------------------------------------------------------------------------\n# assignment b\n# data frame\n\nFlower = c()\nSpecies = c()\nNearest.neighbor = c()\nNN.species = c()\n\nfor (i in 1:size) {\n Flower[i] <- i\n Species[i] <- levels(iris$Species)[iris[i, 5]] # convert the factor to string\n\n # find the nearest neighbor using sort\n line = distances2[i,]\n index_nn = order(line[-i])[1]\n print (order(line))\n # nn = sort(line)[2] # first one is itself, so choose 2\n # index_nn = which(line == nn)\n Nearest.neighbor[i] <- index_nn\n NN.species[i] <- levels(iris$Species)[iris[index_nn, 5]]\n}\n\ndata_frame = data.frame(Flower, Species, Nearest.neighbor, NN.species)\n#print(data_frame)\nwrite.csv(data_frame, file = \"EX_B_distance.csv\")\n\n# -----------------------------------------------------------------------------\n# assignment c\npercent.matrix.x <- table(data_frame$Species, data_frame$NN.species)\n\ncc = table ( data_frame$Species, data_frame$NN.species ) [,]\nwrite.csv(cc, file = \"EX_C_distance_3x3.csv\")\n\n# -----------------------------------------------------------------------------\n# assignment d\n# print (cc)\npar(mfrow=c())\nbarplot(cc, main=\"Number of Nearest Neighbors\", xlab=\"Species\", ylab=\"Numbers\", col=c(\"darkblue\", \"red\", \"gray\"), legend = rownames(cc), beside=TRUE)\n\n\n\n# -----------------------------------------------------------------------------\n# assignment e. histograms\n\npar(mfrow=c(3, 4))\n\n# setosa\n\nsetosa <- iris[iris$Species == 'setosa',]\n\nhist(setosa$Sepal.Length, col=\"Tomato\", main=\"Setosa Sepal.Length\", xlab=\"Sepal Length\")\nhist(setosa$Sepal.Width, col=\"Tomato\", main=\"Setosa Sepal.Width\", xlab=\"Sepal Width\")\nhist(setosa$Petal.Length, col=\"Tomato\", main=\"Setosa Petal.Length\", xlab=\"Petal Length\")\nhist(setosa$Petal.Width, col=\"Tomato\", main=\"Setosa Petal.Width\", xlab=\"Petal Width\")\n\n# versicolor\n\nversicolor <- iris[iris$Species == 'versicolor',]\n\nhist(versicolor$Sepal.Length, col=\"Violet\", main=\"Versicolor Sepal.Length\", xlab=\"Sepal Length\")\nhist(versicolor$Sepal.Width, col=\"Violet\", main=\"Versicolor Sepal.Width\", xlab=\"Sepal Width\")\nhist(versicolor$Petal.Length, col=\"Violet\", main=\"Versicolor Petal.Length\", xlab=\"Petal Length\")\nhist(versicolor$Petal.Width, col=\"Violet\", main=\"Versicolor Petal.Width\", xlab=\"Petal Width\")\n\n# virginica\n\nvirginica <- iris[iris$Species == 'virginica',]\n\nhist(virginica$Sepal.Length, col=\"Turquoise\", main=\"Virginica Sepal.Length\", xlab=\"Sepal Length\")\nhist(virginica$Sepal.Width, col=\"Turquoise\", main=\"Virginica Sepal.Width\", xlab=\"Sepal Width\")\nhist(virginica$Petal.Length, col=\"Turquoise\", main=\"Virginica Petal.Length\", xlab=\"Petal Length\")\nhist(virginica$Petal.Width, col=\"Turquoise\", main=\"Virginica Petal.Width\", xlab=\"Petal Width\")\n\n# -----------------------------------------------------------------------------\n# assignment f.\n\n# A histogram visualizes a distribution of numerical data. The y-axis shows how\n# frequently the values on the x-axis occur in the data, the bars represent\n# ranges of values on the x-axis.\n#\n# ---\n#\n# Figures description\n#\n# ---\n#\n# Setosa Sepal.Length\n#\n# It is observed that the higher frequencies are defined between the range of 4.5 - 5.5,\n# having a maximum frequency approximately of 15 units.\n#\n# Versicolor Sepal.Length\n#\n# This figure shows a maximum frequency of approximately 20 units for Sepal lengths between\n# the range 5.5. and 6.0.\n#\n# Virginica Sepal.Length\n#\n# Higher frequencies are defined between the range of 6.0 - 6.5, with a frequency of approximately\n# of 20 units. There is an evenly distribution for values between the range of 7.0 - 8.0,\n# furthermore there are no Sepals with lengths in a range of 5.0 - 5.5.\n#\n# ---\n#\n# Setosa Sepal.Width\n#\n# The frequency reach its maximum of approximately 25 units for values defined between the range 3.0 - 3.5\n# and its minimum between 2.0 - 2.5.\n#\n# Versicolor Sepal.Width\n#\n# Increasing distribution of frequencies is observed between the range 2.0 - 3.0, reaching a maximum\n# of approximately 15 units between the range 2.8 - 3.0.\n#\n# Virginica Sepal.Width\n#\n# This figure shows a maximum frequencies of approximately 15 units for widths between 2.5 and 3.0.\n#\n# ----\n#\n# Setosa Petal.Length\n#\n# An evenly minimal distribution of frequencies is observed for lengths between the range 1.0 - 1.2\n# and greater than 1.8, the frequencies reach its maximum at a length of around\n# 1.4 with approximately 15 units.\n#\n# Versicolor Petal.Length\n#\n# It is observed that the maximum frequency is reached between the range of 4.0 - 4.5 with a frequency\n# of a approximately 20 units, whereas the minimum length is between 5.0 - 5.5 with a a frequency of 1 unit.\n#\n# Virginica Petal.Length\n#\n# One can observe that the maximum frequency is evenly distributed for ranges 5.0 - 5.5 and 5.5 - 6.0 with\n# a maximum frequency of approximately 15 units.\n#\n# ---\n#\n# Setosa Petal.Width\n#\n# Most of the values of petal width are defined at its very minimum between the range 0.1 - 0.2 with\n# a frequency of approximately 35 units, the minimum is defined between the range 0.4 - 0.6.\n#\n# Versicolor Petal.Width\n#\n# The minimum frequency is defined between the range 1.6 - 1.8, whereas the maximum is defined\n# for widths of 1.2 or 1.3 with a frequency of approximately 15 units.\n#\n# Virginica Petal.Width\n#\n# Most of the frequencies are almost evenly distributed between the range 1.6 - 2.4, reaching their\n# maximum between the range 1.6 - 1.8.\n#\n# ---\n#\n# General Comparison\n#\n# Among the three groups of species, Virginica has the higher Sepal lengths frequency for values\n# between 6.0 ??? 6.5 and Satosa has the maximum Sepal widths for values between 3.0 and 3.5.\n#\n# On the other side, Setosa specie presents the minimum Petal lengths with values between 1.0 - 1.8,\n# on the contrary, Virginica has the maximum petal lengths between the range 5.0 - 6.0. It is clear\n# to notice that species of type Setosa have the minimum widths of Petals.\n", "meta": {"hexsha": "6f599f2f585a606ed7a9fcbf3ea7262c06d30883", "size": 7101, "ext": "r", "lang": "R", "max_stars_repo_path": "Ex1/ex1.r", "max_stars_repo_name": "omartrinidad/ml_bioinformatics", "max_stars_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "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": "Ex1/ex1.r", "max_issues_repo_name": "omartrinidad/ml_bioinformatics", "max_issues_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "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": "Ex1/ex1.r", "max_forks_repo_name": "omartrinidad/ml_bioinformatics", "max_forks_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-15T02:23:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-15T02:23:47.000Z", "avg_line_length": 34.6390243902, "max_line_length": 149, "alphanum_fraction": 0.6652584143, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6876684003116857}} {"text": "#' Principal Components Analysis\n#'\n#' @param data.mat Input data matrix\n#'\n#' @return Object of class tomPCA with rotation and x data\n#' @export\n#'\n#' @examples\n#' test.matrix = matrix(\n#' c(2, 4, 3, 1, 5, 7),\n#' nrow=3,\n#' ncol=2)\n#'\n#' pca.obj = PCA(test.matrix)\nPCA = function(data.mat)\n{\n # Scale data\n scaled.mat = scale(data.mat, scale = FALSE)\n\n # Run SVD on scaled data\n sm.svd = base::svd(scaled.mat)\n\n # Get x mat\n x.mat = sm.svd$u %*% diag(sm.svd$d)\n rot.mat = sm.svd$v\n\n # Return rotation and x\n return(structure(list(rotation = rot.mat, x = x.mat), class = \"tomPCA\"))\n}\n", "meta": {"hexsha": "a1e0d98749d87a9f109b56e4ac718e9ccce56758", "size": 602, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PCA.r", "max_stars_repo_name": "tan92327/nempack2", "max_stars_repo_head_hexsha": "03e8d6d271e7a3d969f4f52829a7cd1690a0ae03", "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/PCA.r", "max_issues_repo_name": "tan92327/nempack2", "max_issues_repo_head_hexsha": "03e8d6d271e7a3d969f4f52829a7cd1690a0ae03", "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/PCA.r", "max_forks_repo_name": "tan92327/nempack2", "max_forks_repo_head_hexsha": "03e8d6d271e7a3d969f4f52829a7cd1690a0ae03", "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.0666666667, "max_line_length": 74, "alphanum_fraction": 0.6112956811, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6876012941946398}} {"text": "n<-100\nw<-1; a1<-runif(n, min = w*0.5, max = w*1.5)\nw<-2; a2<-runif(n, min = w*0.5, max = w*1.5)\nw<-3; a3<-runif(n, min = w*0.5, max = w*1.5)\n\nif (T) {\n sd2<-0.2\n w<-1; a1<-rnorm(n, mean = w, sd =sd2)\n w<-2; a2<-rnorm(n, mean = w, sd = sd2)\n w<-3; a3<-rnorm(n, mean = w, sd = sd2)\n}\n\nww<-c(a1,a2,a3)\na<-1.2\nb<-0.66\nh<-data.frame(w=rep(1:3,each=n),wobs=ww,cons=a*ww^b)\ncleanup()\nplot(x=h$w,y=h$cons)\nlines(x=h$wobs,y=h$cons,type='p',col='red')\n\nplot(x=log(h$wobs),y=log(h$cons))\n\naa<-lm(log(cons)~log(wobs),data=h)\n\nh$predict<-predict(aa)\nplot(x=log(h$wobs),y=log(h$cons))\nlines(x=log(h$w),y=log(h$cons),col='red',type='p')\nabline(aa)\n\n\n\nplot(x=h$wobs,y=(h$cons))\n\nco<-coef(aa)\nh$pred2<-exp(co[1])*h$wobs^co[2]\nlines(x=h$wobs,y=h$pred2,col='red',type='p')\nsummary(aa)\ncat(\"a:\",a,\" b:\",b,\"\\n\")\ncat(\"estimated a:\",exp(co[1]),\" b:\",co[2],\"\\n\")", "meta": {"hexsha": "04ffb61821a968b080497d79edeb0336ec7a55f0", "size": 843, "ext": "r", "lang": "R", "max_stars_repo_path": "SMS_R_prog/r_prog_less_frequently_used/test_consum_ab.r", "max_stars_repo_name": "ices-eg/wg_WGSAM", "max_stars_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-28T11:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:40:03.000Z", "max_issues_repo_path": "SMS_R_prog/r_prog_less_frequently_used/test_consum_ab.r", "max_issues_repo_name": "ices-eg/wg_WGSAM", "max_issues_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "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": "SMS_R_prog/r_prog_less_frequently_used/test_consum_ab.r", "max_forks_repo_name": "ices-eg/wg_WGSAM", "max_forks_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "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": 21.6153846154, "max_line_length": 52, "alphanum_fraction": 0.5622775801, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7577943712746404, "lm_q1q2_score": 0.6875560905372837}} {"text": "# this is the modelfile for separate meta-analysis \n# for humerus and femur data \n# the two meta-analyses are run in the same file to allow easy \n# construction of results \n#\n\nmodel {\n \n#### Humerus data\n for(k1 in 1:K.hum) {\n \n # observational part of the model\n x.down.1dot[k1] ~ dbin(p.down.1dot[k1], N.down.hum[k1])\n x.nodown.1dot[k1] ~ dbin(p.nodown.1dot[k1], N.nodown.hum[k1])\n \n p.down.1dot[k1] <- ilogit(eta.xi.hum[k1, 1]) \n p.nodown.1dot[k1] <- ilogit(eta.xi.hum[k1, 2]) \n \n # structural part of the model \n eta.xi.hum[k1, 1:2] ~dmnorm(Eta.Xi.hum[1:2], Omega.hum)\n \n }\n \n # prior for mean -- independent vague priors suffice \n # -- otherwise, mvnormal with vague Wishart \n Eta.Xi.hum[1] ~ dnorm(mu0.hum[1], prec.mu0.hum[1])\n Eta.Xi.hum[2] ~ dnorm(mu0.hum[2], prec.mu0.hum[2])\n\n\n # S.hum is a diagonal matrix of sd's\n S.hum[1,1] ~ dunif(s.lower.hum[1], s.upper.hum[1]) # or use inverse gamma\n S.hum[2,2] ~ dunif(s.lower.hum[2], s.upper.hum[2])\n S.hum[1,2] <- 0\n S.hum[2,1] <- S.hum[1,2]\n \n # R.hum is a correlation matrix\n R.hum[1,1] <- 1\n R.hum[2,2] <- 1\n R.hum[1,2] ~ dunif(r.lower.hum[1], r.upper.hum[1]) # or use atanh\n R.hum[2,1] <- R.hum[1,2]\n \n # Factorize\n Tau.hum <- S.hum %*% R.hum %*% S.hum\n Omega.hum <- inverse(Tau.hum) \n\n\n\n#### Femur data\n for(k2 in 1:K.fem) {\n \n # observational part of the model\n x.down.dot1[k2] ~ dbin(p.down.dot1[k2], N.down.fem[k2])\n x.nodown.dot1[k2] ~ dbin(p.nodown.dot1[k2], N.nodown.fem[k2])\n \n p.down.dot1[k2] <- ilogit(eta.xi.fem[k2, 1]) \n p.nodown.dot1[k2] <- ilogit(eta.xi.fem[k2, 2]) \n\n # structural part of the model \n eta.xi.fem[k2, 1:2] ~dmnorm(Eta.Xi.fem[1:2], Omega.fem)\n \n }\n\n # prior for mean -- independent vague priors suffice \n # -- otherwise, mvnormal with vague Wishart \n Eta.Xi.fem[1] ~ dnorm(mu0.fem[1], prec.mu0.fem[1])\n Eta.Xi.fem[2] ~ dnorm(mu0.fem[2], prec.mu0.fem[2])\n\n\n # S.fem is a diagonal matrix of sd's\n S.fem[1,1] ~ dunif(s.lower.fem[1], s.upper.fem[1]) # or use inverse gamma\n S.fem[2,2] ~ dunif(s.lower.fem[2], s.upper.fem[2])\n S.fem[1,2] <- 0\n S.fem[2,1] <- S.fem[1,2]\n\n # R.fem is a correlation matrix\n R.fem[1,1] <- 1\n R.fem[2,2] <- 1\n R.fem[1,2] ~ dunif(r.lower.fem[1], r.upper.fem[1]) # or use atanh\n R.fem[2,1] <- R.fem[1,2]\n\n # Factorize\n Tau.fem <- S.fem %*% R.fem %*% S.fem\n Omega.fem <- inverse(Tau.fem) \n \n \n # Data to report \n tpr.hum <- ilogit(Eta.Xi.hum[1])\n fpr.hum <- ilogit(Eta.Xi.hum[2])\n\n tpr.fem <- ilogit(Eta.Xi.fem[1])\n fpr.fem <- ilogit(Eta.Xi.fem[2])\n \n diff.tpr <- tpr.hum - tpr.fem\n diff.fpr <- fpr.hum - fpr.fem\n \n or.tpr <- exp(Eta.Xi.hum[1]-Eta.Xi.fem[1])\n or.fpr <- exp(Eta.Xi.hum[2]-Eta.Xi.fem[2])\n\n diff.eta <- Eta.Xi.hum[1]-Eta.Xi.fem[1]\n diff.xi <- Eta.Xi.hum[2]-Eta.Xi.fem[2]\n\n}\n", "meta": {"hexsha": "316719b4c10130b70a3e1e379b59c8cca89cd23d", "size": 3042, "ext": "r", "lang": "R", "max_stars_repo_path": "model_separate.r", "max_stars_repo_name": "ttrikalin/meta-analysis-multiple-tests", "max_stars_repo_head_hexsha": "fdb283d0d3d0ee2c1806caf9eeea73328e8367a6", "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_separate.r", "max_issues_repo_name": "ttrikalin/meta-analysis-multiple-tests", "max_issues_repo_head_hexsha": "fdb283d0d3d0ee2c1806caf9eeea73328e8367a6", "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_separate.r", "max_forks_repo_name": "ttrikalin/meta-analysis-multiple-tests", "max_forks_repo_head_hexsha": "fdb283d0d3d0ee2c1806caf9eeea73328e8367a6", "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.5339805825, "max_line_length": 78, "alphanum_fraction": 0.547008547, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6875139055006906}} {"text": "#'@title calcAbt\n#'\n#'@description Estimate transverse bulb area (\\code{Abt}) (m^2) using method in\n#'Rakke (2016).\n#'\n#'@param Cm Midship area coefficient (dimensionless) (see \\code{\\link{calcCm}})\n#'@param breadth Moulded breadth (m)\n#'@param actualDraft Actual draft (m)\n#'\n#'@details\n#'Transverse sectional area of the bulb at the position where the still-water\n#'surface intersects the stem (m^2) using actual draft. Actual draft is\n#'typically obtained from sources such as AIS messages or ship records.\n#'\n#'@return \\code{Abt} (vector of numericals, m^2)\n#'\n#'@references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29. p. 166-170\n#'\n#'\\href{http://hdl.handle.net/11250/2410741}{Rakke, S. G. 2016. \"Ship\n#'Emissions Calculation from AIS.\" NTNU}\n#'\n#'@seealso \\code{\\link{calcCm}}\n#'\n#'@examples\n#'calcAbt(0.98, 32, 10)\n#'calcAbt(c(0.98,0.99), c(32,45.5), c(10,15.5))\n#'\n#'@export\n\ncalcAbt <-function(Cm, breadth, actualDraft){\n\n Abt<-0.08*Cm*breadth*actualDraft\n\n return(Abt)\n}\n", "meta": {"hexsha": "fb1bdb5cf1f7359ed3605ff92222b381bda3dae2", "size": 1064, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcAbt.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/calcAbt.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/calcAbt.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": 28.0, "max_line_length": 79, "alphanum_fraction": 0.6983082707, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6873451109099057}} {"text": "## Dale W.R. Rosenthal, 2018\n## You are free to distribute and use this code so long as you attribute\n## it to me or cite the text.\n## The legal disclaimer in _A Quantitative Primer on Investments with R_\n## applies to this code. Use or distribution without these comment lines\n## is forbidden.\nlibrary(MASS)\n\n## simulation for PE exercise\n## Values are from Harte (2017)\nn.years <- 12\nperiods.per.year <- 4\ndtime <- 1/periods.per.year\ntimes <- seq(dtime, n.years, by=dtime)\nmgmt.fee <- 0.02\ninvest.time.end <- max(times)\ncapital0 <- 100\nfees <- capital0*mgmt.fee*dtime\ninvestment0 <- capital0 - fees\n\nrf <- 0.05\n\n## drift/OU reversion parameters\n#pe.alpha <- 0.04\nmu.mkt <- 0.11\nmu.delta <- 0.41\nmu.nu <- 0.08\ntheta.pi <- 0.16; kappa.pi <- 0.42\npi0 <- theta.pi\n\n## covariance parameters; some correlations differ from Harte (2017)\npe.beta <- 1.3\nvol.delta <- 0.21*sqrt(dtime); vol.nu <- 0.11*sqrt(dtime); vol.pi <- 0.16*sqrt(dtime)\nvol.mkt.sys <- 0.15*sqrt(dtime); vol.mkt.idio <- 0.35*sqrt(dtime)\ncorr.delta <- -0.3; corr.nu <- 0.8; corr.pi <- -0.3\n\ncov.delta <- corr.delta*vol.delta*vol.mkt.sys\ncov.nu <- corr.nu*vol.nu*vol.mkt.sys\ncov.pi <- corr.pi*vol.pi*vol.mkt.sys\ncov.mtx <- matrix(c(vol.delta^2, 0, 0, cov.delta, 0,\n 0, vol.nu^2, 0, cov.nu, 0,\n 0, 0, vol.pi^2, cov.pi, 0,\n cov.delta, cov.nu, cov.pi, vol.mkt.sys^2, 0,\n 0, 0, 0, 0, vol.mkt.idio^2),\n nrow=5)\n\n## generate random variates\nB.rvs <- mvrnorm(mu=rep(0, 5), Sigma=cov.mtx, n=n.years*periods.per.year)\ncolnames(B.rvs) <- c(\"B.delta\", \"B.nu\", \"B.pi\", \"B.mkt\", \"B.epsilon\")\n\ndelta <- pmin(pmax(mu.delta*dtime + B.rvs[,\"B.delta\"], 0), 1)\nnu <- pmin(pmax(mu.nu*times + B.rvs[,\"B.nu\"], 0), 1)\npi.ou <- c(pi0)\nfor (i in 2:length(times)) {\n pi.ou[i] <- pi.ou[i-1] + kappa.pi*(theta.pi - pi.ou[i-1])*dtime + B.rvs[i-1,\"B.pi\"]\n}\ndmkt <- mu.mkt*dtime + pe.beta*B.rvs[,\"B.mkt\"] + B.rvs[,\"B.epsilon\"]\n\n## simulate the cashflows and value\ndrawdowns <- c(delta[1]*investment0)\nrcvd.distn <- c(0)\nvalue <- c(0)\nfor (i in 2:length(times)) {\n d.drawdowns <- delta[i]*(investment0 - drawdowns[i-1])*(times[i] < invest.time.end)\n drawdowns[i] <- drawdowns[i-1] + d.drawdowns\n d.rcvd.distn <- nu[i]*value[i-1]\n if (i < length(times)) {\n rcvd.distn[i] <- rcvd.distn[i-1] + d.rcvd.distn\n dvalue <- value[i-1]*dmkt[i-1] + d.drawdowns - d.rcvd.distn\n } else {\n rcvd.distn[i] <- rcvd.distn[i-1] + value[i-1]\n dvalue <- -value[i-1]\n }\n value[i] <- value[i-1] + dvalue\n}\n", "meta": {"hexsha": "17557ff3d5b9e151140fe23b5591cd6380803dc6", "size": 2695, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch23-exercises.r", "max_stars_repo_name": "bmoretz/Quantitative-Investments", "max_stars_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-03-26T05:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T21:50:54.000Z", "max_issues_repo_path": "Quantitative Primer/samples/ch23-exercises.r", "max_issues_repo_name": "bmoretz/Quantitative-Investments", "max_issues_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "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": "Quantitative Primer/samples/ch23-exercises.r", "max_forks_repo_name": "bmoretz/Quantitative-Investments", "max_forks_repo_head_hexsha": "25d9a7199f212787dd9ae05f7af9e7407591c5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-03T09:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:50:55.000Z", "avg_line_length": 35.4605263158, "max_line_length": 87, "alphanum_fraction": 0.573283859, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6871396843842654}} {"text": "\n# Harmonic Series\n\n# How We Got From There To Here:\n# A Story of Real Analysis\n# rate of convergence: page 130 - 132, \n# Harmonic Series also appears on pages 56 and 150.\nn <- 10^9\na <- 0\nfor (i in 1:n) {\na <- (a + (1/i))\n}\n\na\n\n\nn2 <- 10^4\na2 <- 0\nfor( i in 1:n2)\n{\n\ta2 <- (a2 + (1/i))\n}\n\na2\n\nn3 <- 10 ^ 7\na3 <- 0 \nfor(i in 1:n3)\n{\n\ta3 <- (a3 + (1/i))\n}\n\na3\n\n\nn4 <- 100\na4 <- 0\nfor(i in 1:n4)\n{\n\ta4 <- (a4 + (1/i))\n}\n\nprint(a4)\n", "meta": {"hexsha": "3537bbe9f39f1ad369d42a98d27e0306a4faee4e", "size": 429, "ext": "r", "lang": "R", "max_stars_repo_path": "harmonicSeries.r", "max_stars_repo_name": "DU-ds/MiscRScripts", "max_stars_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "harmonicSeries.r", "max_issues_repo_name": "DU-ds/MiscRScripts", "max_issues_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": "harmonicSeries.r", "max_forks_repo_name": "DU-ds/MiscRScripts", "max_forks_repo_head_hexsha": "012fb6ecb60414f8952e3884271dba7add9f4d33", "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": 9.75, "max_line_length": 51, "alphanum_fraction": 0.5198135198, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6871317169735881}} {"text": " DSYGV Example Program Results\n\n Eigenvalues\n -2.2254 -0.4548 0.1001 1.1270\n\n Eigenvectors\n 1 2 3 4\n 1 0.0690 -0.3080 -0.4469 0.5528\n 2 0.5740 -0.5329 -0.0371 0.6766\n 3 1.5428 0.3496 0.0505 0.9276\n 4 -1.4004 0.6211 0.4743 -0.2510\n\n Estimate of reciprocal condition number for B\n 5.8E-03\n\n Error estimates for the eigenvalues\n 9.3E-14 2.5E-14 1.1E-14 5.1E-14\n\n Error estimates for the eigenvectors\n 1.0E-13 2.1E-13 1.8E-13 1.4E-13\n", "meta": {"hexsha": "52ed56b6e3b72e8df9aaa6809707571f5dec9b31", "size": 587, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dsygv_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/dsygv_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/dsygv_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": 27.9523809524, "max_line_length": 48, "alphanum_fraction": 0.5178875639, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6870370818947188}} {"text": "#Regresion lineal\n\n\n#se cargan los datos colocando como parametros que los decimales seran separados por un \",\"\ndata <- read.table(\"muestra_estudiantes.txt\",header=TRUE)\ndata\n#Nombre de columnas a ignorar para este experimento, calclulo de ignora pues es la salida deseada\ndrops <- c(\"cant_mat\",\"escuela\",\"gestion_plantel\",\"tipo_plantel\",\"nivel_socioeco\",\"nivel_estudios_padres\",\"genero\",\"opsu\")\n#se descarta Cant_cats por tener correlacion poco significativa\ndata <- data[ , !(names(data) %in% drops)]\ndata\npairs(data)\ncor(data)\n\ny <- data[,6]\ny\nx <- data[,1:5]\nx\n\nx11()\npar(mfrow=c(1,2))\nplot(y,x[,1])\nplot(y,x[,2])\nx11()\npar(mfrow=c(1,2))\nplot(y,x[,3])\nplot(y,x[,4])\nx11()\npar(mfrow=c(1,1))\nplot(y,x[,5])\n#\nmod1 <- lm(y ~ x[,1] + x[,2] + x[,3] + x[,4] + x[,5])\n#Analsis de Modelo\nsummary(mod1)\n\n# Other useful functions \ncoefficients(mod1) # model coefficients\nconfint(mod1, level=0.95) # CIs for model parameters \nfitted(mod1) # predicted values\nresiduals(mod1) # residuals\nanova(mod1) # anova table \nvcov(mod1) # covariance matrix for model parameters \ninfluence(mod1) # regression diagnostics\n\nresi = residuals(mod1)\n\n#para la prueba de No normalidad\nshapiro.test(residuals(mod1))\n\n#para la prueba de Homogenidad de los datos\n#crear un factor \nlibrary(Rcmdr)\nfac=NULL\nfor(i in 1:6){\nfac=c(fac,rep(i,21))}\nfac\nlevene.test(resi, fac)\n\n#Prueba de Aletoridad de los datos\nsecu=c(seq(1,126))\n\nx11()\nplot(secu,resi,col=\"red\",type=\"l\")\nabline(h = 0, v = 0, lty = 2, col = 4)\n# diagnostic plots \nlayout(matrix(c(1,2,3,4),2,2)) # optional 4 graphs/page \nplot(mod1)\n\nECM <- mean(resi^2)\nECM\n", "meta": {"hexsha": "6778df8fabae5eb48d07ea233855e4f1288e454f", "size": 1587, "ext": "r", "lang": "R", "max_stars_repo_path": "src/AppBundle/R/Modelo_1_RL.r", "max_stars_repo_name": "1211agarcia/SistemaPrediccion", "max_stars_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "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/AppBundle/R/Modelo_1_RL.r", "max_issues_repo_name": "1211agarcia/SistemaPrediccion", "max_issues_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "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/AppBundle/R/Modelo_1_RL.r", "max_forks_repo_name": "1211agarcia/SistemaPrediccion", "max_forks_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "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.3521126761, "max_line_length": 122, "alphanum_fraction": 0.7019533711, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6870266236109261}} {"text": "cal.rate <- function(N.lim, r.lim) {\n rate <- function(N, r) {\n p <- (1 + r) ^ N\n 0.5*(1+N)*r /(p*N*r / (p-1) - 1)\n }\n N <- seq(N.lim[1], N.lim[2])\n r <- seq(r.lim[1], r.lim[2], length.out=diff(N.lim)+1)\n z <- outer(N, r, rate)\n list(N=N, r=r, z=z)\n}\n\nplot.rate <- function(d, col=\"lightblue\",\n theta=30, phi=20,\n r=50,\n expand=0.5,\n ltheta=90, lphi=180,\n shade=0.75,\n nticks=5) {\n \n # sub=expression(italic(f)~(bold(x))==frac(1,2~pi~sqrt(sigma[11]~\n # sigma[22]~(1-rho^2)))~phantom(0)^bold(.)~exp~bgroup(\"{\",\n # list(-frac(1,2(1-rho^2)),\n # bgroup(\"[\", frac((x[1]~-~mu[1])^2, sigma[11])~-~2~rho~frac(x[1]~-~mu[1],\n # sqrt(sigma[11]))~ frac(x[2]~-~mu[2],sqrt(sigma[22]))~+~\n # frac((x[2]~-~mu[2])^2, sigma[22]),\"]\")),\"}\"))\n\n persp(d$N, d$r, d$z,\n xlab=\"N\", ylab=\"r\", zlab=\"z\",\n main=\"Plot the rate \",\n # sub=sub,\n col=\"lightblue\",\n theta=theta, phi=phi,\n r=r,\n expand=expand,\n ltheta=ltheta, lphi=lphi,\n shade=shade,\n ticktype=\"detailed\",\n nticks=nticks) # produces the 3-D plot\n\n # mtext(expression(list(mu[1]==0,mu[2]==0,sigma[11]==10,sigma[22]==10,sigma[12]==15,rho==0.5)), side=3) # adding a text line to the graph\n}\n\nif (FALSE) {\n source(\"./src/cal.rate.r\")\n d <- cal.rate(N.lim=c(1,120), r.lim=c(0, 0.01))\n plot.rate(d=d)\n \n \n}\n", "meta": {"hexsha": "210c9ddc603f874fc1ee1295182e91ba513b58d0", "size": 1359, "ext": "r", "lang": "R", "max_stars_repo_path": "src/cal.rate.r", "max_stars_repo_name": "kekincai/cal.rate", "max_stars_repo_head_hexsha": "760b1d74a700a1bc3a416168e4e3a8eaee771eca", "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/cal.rate.r", "max_issues_repo_name": "kekincai/cal.rate", "max_issues_repo_head_hexsha": "760b1d74a700a1bc3a416168e4e3a8eaee771eca", "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/cal.rate.r", "max_forks_repo_name": "kekincai/cal.rate", "max_forks_repo_head_hexsha": "760b1d74a700a1bc3a416168e4e3a8eaee771eca", "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.18, "max_line_length": 141, "alphanum_fraction": 0.5084621045, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6870154743325199}} {"text": "## Plotting Sierpinski triangle. aev 4/1/17\n## ord - order, fn - file name, ttl - plot title, clr - color\npSierpinskiT <- function(ord, fn=\"\", ttl=\"\", clr=\"navy\") {\n m=640; abbr=\"STR\"; dftt=\"Sierpinski triangle\";\n n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);\n cat(\" *** START\", abbr, date(), \"\\n\");\n if(fn==\"\") {pf=paste0(abbr,\"o\", ord)} else {pf=paste0(fn, \".png\")};\n if(ttl!=\"\") {dftt=ttl}; ttl=paste0(dftt,\", order \", ord);\n cat(\" *** Plot file:\", pf,\".png\", \"title:\", ttl, \"\\n\");\n for(y in 1:n) {\n for(x in 1:n) {\n if(bitwAnd(x, y)==0) {M[x,y]=1}\n ##if(bitwAnd(x, y)>0) {M[x,y]=1} ## Try this for \"reversed\" ST\n }}\n plotmat(M, pf, clr, ttl);\n cat(\" *** END\", abbr, date(), \"\\n\");\n}\n## Executing:\npSierpinskiT(6,,,\"red\");\npSierpinskiT(8);\n", "meta": {"hexsha": "f3fb3b3eb42540584cba46e855efbfb38126a70b", "size": 776, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "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/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.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/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.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": 36.9523809524, "max_line_length": 69, "alphanum_fraction": 0.5425257732, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.68701546982795}} {"text": "# Dati\r\ntotale <- 12\r\nmonetevincenti <- 4\r\nmoneteperdenti <- 8\r\n\r\nestratte <- 4\r\n\r\n# Y = AX + B(C + DX)\r\nA <- 2\r\nB <- 1\r\nC <- 4\r\nD <- -1\r\n\r\n# Domande\r\n\r\ndomanda1 <- 0\r\ndomanda2 <- 5\r\ndomanda3_a <- 8\r\ndomanda3_b <- 0\r\n\r\n# Svolgimento\r\nd_f <- dhyper(m = monetevincenti, n = moneteperdenti, k = estratte, x = c(0:estratte))\r\np_f <- phyper(m = monetevincenti, n = moneteperdenti, k = estratte, q = c(0:estratte))\r\n\r\nprX <- function(k){\r\n n <- totale\r\n h <- monetevincenti\r\n r <- moneteperdenti\r\n \r\n if(k >= 0) {\r\n choose(h,k) * choose(n-h, r-k)/choose(n,r)\r\n }\r\n else {\r\n 0\r\n }\r\n}\r\n\r\nprimadomanda <- 1\r\nif (domanda1 != 0) {\r\n for(i in 0:(domanda1 - 1)){\r\n primadomanda <- primadomanda - prX(i)\r\n }\r\n}\r\n\r\ny <- function(x) {\r\n (B*D+A)*x + B*C\r\n}\r\n\r\ny_invert <- function(y) {\r\n (y - B*C)/(A + B*D)\r\n}\r\n\r\ny_list <- sort(c(y(0:estratte)))\r\nsecondadomanda <- d_f[y_invert(y_list[domanda2])+1]\r\n\r\nTRENTA <- 30\r\n\r\nif(domanda3_a <= y_list[estratte+1]) {\r\n d3_primointervallo <- seq(y_invert(domanda3_a), TRENTA)\r\n} else {\r\n d3_primointervallo <- seq(-TRENTA, y_invert(domanda3_a))\r\n}\r\n\r\nif(domanda3_b <= y_list[estratte+1]) {\r\n d3_secondointervallo <- seq(domanda3_b, TRENTA)\r\n} else {\r\n d3_secondointervallo <- seq(-TRENTA, domanda3_b)\r\n}\r\n\r\ntmp <- intersect(d3_primointervallo, d3_secondointervallo)+1\r\ntmp <- tmp[!is.na(tmp)]\r\nif (length(tmp) > 1) {\r\n numeratore <- d_f[tmp]\r\n numeratore <- numeratore[!is.na(numeratore)]\r\n denominatore <- d_f[d3_secondointervallo+1]\r\n denominatore <- denominatore[!is.na(denominatore)]\r\n terzadomanda <- sum(numeratore)/sum(denominatore)\r\n} else {\r\n terzadomanda <- p_f[tmp]/sum(d_f[d3_secondointervallo+1])\r\n}\r\n\r\nif(length(terzadomanda) == 0) {\r\n terzadomanda <- 0\r\n}\r\n\r\n# Output\r\nprint(primadomanda)\r\nprint(secondadomanda)\r\nprint(terzadomanda)\r\n", "meta": {"hexsha": "7722a93fcd8754c6f56bb74dc78101e94dc5faa2", "size": 1804, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 29.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 29.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 29.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.0444444444, "max_line_length": 87, "alphanum_fraction": 0.6186252772, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6870154673873112}} {"text": "# Guía del fichero: https://rpubs.com/probestaunal/taller01\n\n###################################################################################################\n# INTRODUCCIÓN A LA ESTADÍSTICA #\n###################################################################################################\n# 1. Clasificar según su naturaleza (cualitativa, cuantitativa discreta, cuantitativa continua) #\n# y establecer la escala de medición de las siguientes variables. #\n###################################################################################################\n# Estrato socio-económico. # Cualitativa, ordinal. # \n# Sexo. # Cualitativa, nominal. #\n# Número de unidades defectuosas. # Cuantitativa discreta, razón. #\n# Calificación de un examen (valores: aprobado, no aprobado). # Cualitativa, nominal. #\n# Nivel educativo (valores: básica, pregrado, posgrado). # Cualitativa, ordinal. #\n# Estatura (en metros). # Cuantitativa continua, razón. #\n# Temperatura (en grados centigrados). # Cuantitativa continua, intervalo. #\n# Edad (en años cumplidos). # Cuantitativa discreta, razón. #\n# Opinión (valores: a favor, en contra, no sabe/no responde). # Cualitativa, nominal. #\n# Raza. # Cualitativa, nominal. #\n# Número de hermanos. # Cuantitativa discreta, razón #\n# Utilidades anuales (en millones pesos). # Cuantitativa continua, razón. #\n# Tiempo requerido para ejecutar una tarea (en minutos). # Cuantitativa continua, razón. #\n# Índice de masa corporal (en kg/m2). # Cuantitativa continua, razón. #\n# Concentración de dióxido de carbono (CO2, en ppm). # Cuantitativa continua, razón. #\n# pH (valores: básico, neutro, ácido). # Cualitativa, ordinal. #\n# Resistencia eléctrica (en ohm). # Cuantitativa continua, razón. #\n# Presión (en pa). # Cuantitativa continua, razón. #\n# Densidad (en kg/m3). # Cuantitativa continua, razón. #\n# Latitud/longitud (en grados, minutos y segundos). # Cuantitativa continua, intervalo. #\n###################################################################################################", "meta": {"hexsha": "191f6468bdb65b5f1a6cad83c7511e1b93f63457", "size": 2767, "ext": "r", "lang": "R", "max_stars_repo_path": "02.tablas/taller1.r", "max_stars_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_stars_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "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": "02.tablas/taller1.r", "max_issues_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_issues_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "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": "02.tablas/taller1.r", "max_forks_repo_name": "devHectorGa/UNALProbabilidadEstadistica", "max_forks_repo_head_hexsha": "1cd472cc1b39daa8a9b81d40ec128d3d168af0a5", "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": 95.4137931034, "max_line_length": 106, "alphanum_fraction": 0.4304300687, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6869254777484317}} {"text": "#install.packages(\"GA\")\nlibrary(GA)\n\n# https://cran.r-project.org/web/packages/GA/vignettes/GA.html#constrained-optimisation\nfunc3d <- function(x)\n{\n 100*(x[1]^2-x[2]^2)+(1-x[1])^2\n}\n\nc1 <- function(x)\n{\n x[1]*x[2] + x[1] - x[2] + 1.5\n}\n\nc2 <- function(x)\n{\n 10 - x[1]*x[2]\n}\n\nx1LBound <- 0\nx1RBound <- 1\nx2LBound <- 0\nx2RBound <- 13\n\nngrid <- 250\nx1 <- seq(x1LBound, x1RBound, length = ngrid)\nx2 <- seq(x2LBound, x2RBound, length = ngrid)\nx12 <- expand.grid(x1, x2)\ncol <- adjustcolor(bl2gr.colors(4)[2:3], alpha = 0.2)\nplot(x1, x2, type = \"n\", xaxs = \"i\", yaxs = \"i\")\nimage(x1, x2, matrix(ifelse(apply(x12, 1, c1) <= 0, 0, NA), ngrid, ngrid), col = col[1], add = TRUE)\nimage(x1, x2, matrix(ifelse(apply(x12, 1, c2) <= 0, 0, NA), ngrid, ngrid), col = col[2], add = TRUE)\ncontour(x1, x2, matrix(apply(x12, 1, func3d), ngrid, ngrid), nlevels = 21, add = TRUE)\n\nfitness <- function(x) \n{ r\n f <- -func3d(x) # we need to maximise -func3d(x)\n pen <- sqrt(.Machine$double.xmax) # penalty term\n penalty1 <- max(c1(x),0)*pen # penalisation for 1st inequality constraint\n penalty2 <- max(c2(x),0)*pen # penalisation for 2nd inequality constraint\n f - penalty1 - penalty2 # fitness function value\n}\n\nGA <- ga(\"real-valued\", fitness = fitness, \n lower = c(x1LBound, x2LBound), upper = c(x1RBound, x2RBound), \n # selection = GA:::gareal_lsSelection_R,\n maxiter = 1000, run = 200, seed = 123)\nsummary(GA)\n\nfitness(GA@solution)\nfunc3d(GA@solution)\nc1(GA@solution)\nc2(GA@solution)\n\nplot(x1, x2, type = \"n\", xaxs = \"i\", yaxs = \"i\")\nimage(x1, x2, matrix(ifelse(apply(x12, 1, c1) <= 0, 0, NA), ngrid, ngrid), col = col[1], add = TRUE)\nimage(x1, x2, matrix(ifelse(apply(x12, 1, c2) <= 0, 0, NA), ngrid, ngrid), col = col[2], add = TRUE)\ncontour(x1, x2, matrix(apply(x12, 1, func3d), ngrid, ngrid), nlevels = 21, add = TRUE)\npoints(GA@solution[1], GA@solution[2], col = \"dodgerblue3\", pch = 3) # GA solution\n", "meta": {"hexsha": "56c393e4c5c57748f79e9c758e5185cf8037ada9", "size": 1965, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ga/func/3d/with_bounds_formula/ga_minimum_of_3d_func_formula_bounds.r", "max_stars_repo_name": "reyzeer/algorytmy-genetyczne", "max_stars_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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/ga/func/3d/with_bounds_formula/ga_minimum_of_3d_func_formula_bounds.r", "max_issues_repo_name": "reyzeer/algorytmy-genetyczne", "max_issues_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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/ga/func/3d/with_bounds_formula/ga_minimum_of_3d_func_formula_bounds.r", "max_forks_repo_name": "reyzeer/algorytmy-genetyczne", "max_forks_repo_head_hexsha": "c8803dd19dd5105d35b287fa13efdc130531403f", "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.75, "max_line_length": 100, "alphanum_fraction": 0.6142493639, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.686792637581793}} {"text": "efficient_frontier = function(MRet,rangeMu)\n{\n uM = dim(MRet)[1]\n pM = dim(MRet)[2]\n #compute the portfolio's expected returns\n expRet = colMeans(MRet)\n\n #use sample variance matrix (does not change anything compared to pop. so this one\n #is unbiased!)\n\n Omega = var(MRet)\n # expVar = t(weights)%*%Omega%*%weights\n \n #create a matrix of expected returns and constraints: t(E) and t(1) right and only one\n #cause its the returns of each and the weight of each that we scale to one\n unityVec = rep(1,pM)\n \n A = rbind(expRet,unityVec)\n print(A)\n\n # compute var in function of expected returns independently of the weights:\n n = length(rangeMu)\n myVar = rep(NA,n)\n myWeights = matrix(data=NA,nrow=n,ncol=pM)\n \n for(i in 1:n)\n {\n b = matrix(data=c(rangeMu[i],1),nrow=2)\n myVar[i] = t(b)%*%solve(A%*%solve(Omega)%*%t(A))%*%b\n myWeights[i,] = solve(Omega)%*%t(A)%*%solve(A%*%solve(Omega)%*%t(A))%*%b\n }\n\n # dev.new()\n mySd = myVar^0.5\n return(mySd)\n \n # plot(mySd,rangeMu,t='l')\n # Ones = matrix(data=c(1,1),nrow=2)\n # weightsMinVar = solve(Omega)%*%Ones%*%solve(t(Ones)%*%solve(Omega)%*%Ones)\n # muMinVar = t(weightsMinVar)%*%expRet\n #case where we want the sum of the weights to sum to one (less efficient and more risky\n #(we want to achieve a kind of zero investment portfolio.)\n # bMax = matrix(data=c(targetMu,1),nrow=2)\n # print(bMax)\n \n # bMax = rbind(targetMu,)\n # case where target weights sum to zero - better for us.\n # bMaxZero = matrix(data=c(targetMu,0),nrow=2)\n # bMaxZero = rbind(targetMu,0)\n # weightsMinVarTarget = solve(Omega)%*%t(A)%*%solve(A%*%solve(Omega)%*%t(A))%*%bMaxZero\n}\n\nefficient_frontier_single = function(MRet)\n{\n rangeMu = seq(0.001,0.025,0.01)\n mySd = efficient_frontier(MRet,rangeMu)\n \n dev.new()\n plot(mySd*100,rangeMu*100,xlab=\"volatility (%)\",ylab=\"expected return (%)\")\n}\n\nefficient_frontier_simul = function(MRet)\n{\n pM = dim(MRet)[2]\n rangeMu = seq(-0.01,0.05,0.001)\n mySd = efficient_frontier(MRet[,1:9],rangeMu)\n \n dev.new()\n plot(mySd*100,rangeMu*100,xlab=\"volatility (%)\",ylab=\"expected return (%)\",t='l',xlim=c(0,max(mySd*100)),ylim=c(-1,5))\n \n for(j in 10:pM)\n {\n mySd = efficient_frontier(MRet[,1:j],rangeMu)\n lines(mySd*100,rangeMu*100,col='red')\n # Sys.sleep(0.5)\n }\n}\n", "meta": {"hexsha": "8ace8fab68824b7f871313687830a8a783d2fc92", "size": 2287, "ext": "r", "lang": "R", "max_stars_repo_path": "static/files/cours_principles_of_finance 2019.r", "max_stars_repo_name": "loicym/my-personal-website", "max_stars_repo_head_hexsha": "d8d6c73289a62a2b0546fbccc13266a4b50af5e8", "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": "static/files/cours_principles_of_finance 2019.r", "max_issues_repo_name": "loicym/my-personal-website", "max_issues_repo_head_hexsha": "d8d6c73289a62a2b0546fbccc13266a4b50af5e8", "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": "static/files/cours_principles_of_finance 2019.r", "max_forks_repo_name": "loicym/my-personal-website", "max_forks_repo_head_hexsha": "d8d6c73289a62a2b0546fbccc13266a4b50af5e8", "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.3205128205, "max_line_length": 120, "alphanum_fraction": 0.6532575426, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6867926338776179}} {"text": "## calculate net and zernike fit wavefronts from any of psifit, fftfit, vortexfit\n\nwf_net <- function(wf.raw, cp, options) {\n\n nr <- nrow(wf.raw)\n nc <- ncol(wf.raw)\n prt <- pupil.rhotheta(nr, nc, cp)\n rho <- prt$rho\n theta <- prt$theta\n if (options$sgs > 1) {\n subs <- matrix(FALSE, nr, nc)\n subs[seq(1, nr, by=options$sgs), seq(1, nc, by=options$sgs)] <- TRUE\n subs[is.na(rho)] <- FALSE\n } else {\n subs <- !is.na(rho)\n }\n wf.v <- wf.raw[subs]\n rho.v <- rho[subs]\n th.v <- theta[subs]\n rho.v <- rho.v[!is.na(wf.v)]\n th.v <- th.v[!is.na(wf.v)]\n wf.v <- wf.v[!is.na(wf.v)]\n fit <- fitzernikes(wf.v, rho.v, th.v,\n eps=cp$obstruct,\n maxorder=options$maxorder, \n nthreads=options$nthreads, \n uselm=options$uselm,\n isoseq=options$isoseq)\n if (options$uselm) {\n cfit <- coef(fit)\n } else {\n cfit <- fit\n }\n if (options$isoseq) {\n ind.ptf <- c(1:3, 5)\n ind.sa4 <- 13\n ind.sa6 <- 25\n ind.astig <- c(6, 4)\n ind.coma <- 8:9\n zc.low <- numeric(28)\n } else {\n ind.ptf <- 1:4\n ind.sa4 <- 9\n ind.sa6 <- 16\n ind.astig <- 5:6\n ind.coma <- 7:8\n zc.low <- numeric(16)\n }\n if (sign(cfit[ind.sa4])*sign(options$satarget[1]) < 0) {\n cfit <- -cfit\n wf.raw <- -wf.raw\n if (!options$uselm) fit <- -fit\n }\n \n zc.low[ind.ptf] <- cfit[ind.ptf]\n zc.low[c(ind.sa4, ind.sa6)] <- zc.low[c(ind.sa4, ind.sa6)] + options$satarget\n zc.low[ind.astig] <- zc.low[ind.astig] + options$astig.bath\n if (is.element(6, options$zc0)) {\n zc.low[ind.coma] <- cfit[ind.coma]\n }\n wf.net <- wf.raw - pupil(zcoef=zc.low, maxorder=6, isoseq=options$isoseq,\n nrow=nr, ncol=nc, cp=cp)\n if (options$plots) {\n if (tolower(.Platform$OS.type) == \"windows\") {\n windows(width=18, height=6)\n } else {\n x11(width=18, height=6)\n }\n split.screen(figs=c(1,3))\n screen(1)\n plot(wf.net, cp=cp, col=options$colors, addContours=FALSE)\n mtext(paste(\"RMS = \", format(pupilrms(wf.net),digits=3)))\n }\n zcoef.net <- cfit\n zcoef.net[1:length(zc.low)] <- zcoef.net[1:length(zc.low)] - zc.low\n wf.smooth <- pupil(zcoef=zcoef.net, maxorder=options$maxorder, isoseq=options$isoseq, \n cp=cp, nrow=nr, ncol=nc)\n if (options$plots) {\n screen(2)\n plot(wf.smooth, cp=cp, col=options$colors)\n mtext(paste(\"RMS = \", format(pupilrms(wf.smooth),digits=3)))\n }\n wf.residual <- wf.net - wf.smooth\n if (options$plots) {\n screen(3)\n plot(wf.residual, cp=cp, col=grey256, addContours=FALSE)\n mtext(paste(\"RMS = \", format(pupilrms(wf.residual),digits=3)))\n close.screen(all.screens=TRUE)\n }\n list(wf.net=wf.net, wf.smooth=wf.smooth, wf.residual=wf.residual, \n fit=fit, zcoef.net=zcoef.net[-1])\n}\n\n#' Methods for class \"wf_fitted\"\n#' \n#' Summary, print, and plot methods for the returned list of values\n#' from [psifit()], [fftfit()], or [vortexfit()]\n#'\n#' @param wffit the return values from one of the fringe analysis routines\n#' @param digits number of digits to display in print and summary methods\n#' @param ... values passed to [plot.pupil()]\n#' @return print method returns data frame with Zernike coefficients\nsummary.wf_fitted <- function(wffit, digits=3) {\n cat(\"Image size(s) : \", nrow(wffit$wf.smooth), \" x \", ncol(wffit$wf.smooth), \"\\n\")\n cat(\"Unsmoothed RMS : \", format(pupilrms(wffit$wf.net), digits=digits), \"\\n\")\n cat(\"Zernike fit RMS : \", format(sqrt(crossprod(wffit$zcoef.net)), digits=digits), \"\\n\")\n cat(\"Zernike fit Strehl: \", format(strehlratio(sqrt(crossprod(wffit$zcoef.net))), digits=digits), \"\\n\")\n cat(\"Zernike fit P-V : \", format(pupilpv(wffit$wf.smooth), digits=digits), \"\\n\")\n cat(\"PVr : \", format(PVr(wffit$wf.smooth, wffit$wf.residual), digits=digits), \"\\n\")\n}\n\nprint.wf_fitted <- function(wffit, digits=3) {\n if (is.element(\"lm\", class(wffit$fit))) {\n fit <- coef(wffit$fit)\n } else {\n fit <- wffit$fit\n }\n nz <- length(wffit$zcoef.net)\n znames <- paste(\"Z\", 0:nz, sep=\"\")\n df.zernikes <- data.frame(Z = znames, Zcoef.Raw = fit, Zcoef.net = c(0, wffit$zcoef.net))\n summary.wf_fitted(wffit, digits=digits)\n cat(\"\\n\")\n print(df.zernikes, digits=digits, row.names=FALSE)\n invisible(df.zernikes)\n}\n\nplot.wf_fitted <- function(wffit, wftype=\"smooth\", ...) {\n wf <- get(paste(\"wf\", wftype, sep=\".\"), wffit)\n plot.pupil(wf, cp=wffit$cp, ...)\n}\n \n", "meta": {"hexsha": "48f5f7bbda90779cbcc3ec43420ee059a0d026cf", "size": 4444, "ext": "r", "lang": "R", "max_stars_repo_path": "R/wf_net.r", "max_stars_repo_name": "mlpeck/zernike", "max_stars_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/wf_net.r", "max_issues_repo_name": "mlpeck/zernike", "max_issues_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "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/wf_net.r", "max_forks_repo_name": "mlpeck/zernike", "max_forks_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 33.6666666667, "max_line_length": 105, "alphanum_fraction": 0.5969846985, "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6865539931979632}} {"text": "##' Estimate minimum specificity from population testing\n##'\n##' Produces an estimate of minimum specificty under the assumption that of the tests identified only negatives as positives\n##' @param positive vector of numbers; the number of positive tests in each sample\n##' @param total vector of numbres; the total number of tests (positive and negative) in each sample\n##' @param cutoff the cutoff for the estimate, i.e. the confidence level desired\n##' @param samples number of values of specificity to sample\n##' @param min_specificity minimum specificity to test\n##' @param max_specificity maximum specificity to test\n##' @param prevalence background prevalence; if >0 then it is assumed that\n##' sensitivity is 0, i.e. all positives are still false positives and some of\n##' the negatives are false negatives\n##' @return estimate of the lower bound of specificity at\n##' the desired confidence level\n##' @author Sebastian Funk\n##' @export\nestimate_min_specificity <- function(positive, total, cutoff = 0.95,\n samples = 1000,\n min_specificity = 0.997,\n max_specificity = 1,\n prevalence = 0) {\n\n true_negative <- round(pmax(positive, total * (1 - prevalence)))\n\n ## create data frame with false test positive and true test negative\n dta <- tibble(positive = positive, negative = true_negative - positive)\n spec <- dta %>%\n expand_grid(specificity =\n seq(min_specificity, max_specificity,\n length.out = samples)) %>%\n ## probability of seeing positives given specificty is at most x\n ## (where at the maximum all positives are false positives)\n mutate(p = pbeta(1 - specificity, positive + 1,\n negative + 1, lower.tail = FALSE)) %>%\n group_by(specificity) %>%\n ## overall probability that specificity is at most x\n summarise(probability = 1 - prod(p), .groups = \"drop\") %>%\n ungroup()\n\n min_spec <- spec %>%\n ## get probability that specificity is at least x\n filter(probability > cutoff) %>%\n summarise(min_spec = max(specificity)) %>%\n .$min_spec\n\n return(min_spec)\n}\n", "meta": {"hexsha": "21f27094f1b95fc20bff20f8294e03697a18529f", "size": 2216, "ext": "r", "lang": "R", "max_stars_repo_path": "R/estimate_min_specificity.r", "max_stars_repo_name": "epiforecasts/sars.cov.2.england.prevalence", "max_stars_repo_head_hexsha": "778ae332ca2d8b90d14163a4dc644f56765d310e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:43:25.000Z", "max_issues_repo_path": "R/estimate_min_specificity.r", "max_issues_repo_name": "epiforecasts/covid19.lfd.england", "max_issues_repo_head_hexsha": "9da9418a27f222019426516c4fbbb70a0bff80bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:27:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T14:19:49.000Z", "max_forks_repo_path": "R/estimate_min_specificity.r", "max_forks_repo_name": "sbfnk/covid19.lfd.education", "max_forks_repo_head_hexsha": "c75e228f23b2327aee0e7ca6479404ca48952902", "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": 46.1666666667, "max_line_length": 124, "alphanum_fraction": 0.6565884477, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6862459922041991}} {"text": "runsum <- function(v) {\n rs <- c()\n for(i in 1:length(v)) {\n rs <- c(rs, sum(v[1:i]))\n }\n rs\n}\n\ngrade <- function(v) {\n g <- vector(\"numeric\", length(v))\n for(i in 1:length(v)) {\n g[v[i]] <- i-1\n }\n g\n}\n\nmakespiral <- function(spirald) {\n series <- vector(\"numeric\", spirald^2)\n series[] <- 1\n l <- spirald-1; p <- spirald+1\n s <- 1\n while(l > 0) {\n series[p:(p+l-1)] <- series[p:(p+l-1)] * spirald*s\n series[(p+l):(p+l*2-1)] <- -s*series[(p+l):(p+l*2-1)]\n p <- p + l*2\n l <- l - 1; s <- -s\n }\n matrix(grade(runsum(series)), spirald, spirald, byrow=TRUE)\n\n}\n\nprint(makespiral(5))\n", "meta": {"hexsha": "c09c940dd491c6bbfebbbb43791256229573abb3", "size": 613, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Spiral-matrix/R/spiral-matrix-1.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Spiral-matrix/R/spiral-matrix-1.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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/Spiral-matrix/R/spiral-matrix-1.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5757575758, "max_line_length": 61, "alphanum_fraction": 0.5057096248, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6861811658306459}} {"text": "make_prior_data <- function(family, params, func) {\n list(\n family = get_family(family),\n # parameters = as.data.frame(params),\n parameters = params,\n prior_function = func\n )\n}\n\ndescribe_prior <- function(family, parameters) {\n range <- parameters[[\"range\"]]\n parameters <- parameters[!grepl(\"range\", names(parameters))]\n if (!is.null(range)) {\n range_text <- paste0(\"\\n range: \", range_as_text(range), \"\\n\")\n }\n\n if (all(range == c(-Inf, Inf))) {\n range_text <- \"\\n\"\n }\n\n if (class(family) == \"beta\") {\n range_text <- \"\\n\"\n }\n\n\n parameter_names <- names(parameters)\n parameter_values <- unname(parameters)\n return(paste0(\n \"Prior\\n\",\n \" Family\\n \", class(family), \"\\n\",\n \" Parameters\\n\",\n paste0(\" \", parameter_names, \": \", parameter_values, collapse = \"\\n\"),\n range_text\n ))\n}\n\nrange_as_text <- function(range) {\n paste0(range[1], \" to \", range[2])\n}\n\nprior_data_names <- c(\"family\", \"parameters\", \"prior_function\")\n\n#################################################################\n## DEFINITIONS OF THE PRIORS ##\n#################################################################\n\n# class definition\n\n\n#' Specify a prior\n#' @description Define priors using different different distribution families\n#' @param family the prior distribution (see details)\n#' @param ... see details\n#'\n#' @details\n#' ## Available distribution families\n#' The following distributions families can be used for the prior\n#' * \\code{normal} a normal distribution\n#' * \\code{student_t} a scaled and shifted t-distribution\n#' * \\code{cauchy} a Cauchy distribution\n#' * \\code{uniform} a uniform distribution\n#' * \\code{point} a point\n#' * \\code{beta} a beta distribution\n#' The parameters that need to be specified will be dependent on the\n#' family\n#'\n#' ## Normal distribution\n#' When \\code{family} is set to \\code{normal} then the following\n#' parameters may be be set\n#' * \\code{mean} mean of the normal prior\n#' * \\code{sd} standard deviation of the normal prior\n#' * \\code{range} (optional) a vector specifying the parameter range\n#'\n#' ## Student t distribution\n#' When \\code{family} is set to \\code{student_t} then the following\n#' parameters may be set\n#' * \\code{mean} mean of the scaled and shifted t prior\n#' * \\code{sd} standard deviation of the scaled and shifted t prior\n#' * \\code{df} degrees of freedom of the scaled and shifted t prior\n#' * \\code{range} (optional) a vector specifying the parameter range\n#'\n#' ## Cauchy distribution\n#' When \\code{family} is set to \\code{cauchy} then the following\n#' parameters may be set\n#' * \\code{location} the centre of the Cauchy distribution (default: 0)\n#' * \\code{scale} the scale of the Cauchy distribution\n#' * \\code{range} (optional) a vector specifying the parameter range\n#'\n#' ## Uniform distribution\n#' When \\code{family} is set to \\code{uniform} then the following\n#' parameters must be set\n#' * \\code{min} the lower bound\n#' * \\code{max} the upper bound\n#'\n#' ## Point\n#' When \\code{family} is set to \\code{point} then the following\n#' parameters may be set\n#' * \\code{point} the location of the point prior (default: 0)\n#'\n#' ## Beta\n#' When \\code{family} is set to \\code{beta} then the following\n#' parameters may be set\n#' * \\code{alpha} the first shape parameter\n#' * \\code{beta} the second shape parameter\n#'\n#' @md\n#' @return an object of class \\code{prior}\n#' @export\n#'\n#' @examples\n#'\n#' # specify a normal prior\n#' prior(family = \"normal\", mean = 0, sd = 13.3)\n#'\n#' # specify a half-normal (range 0 to Infinity) prior\n#' prior(family = \"normal\", mean = 0, sd = 13.3, range = c(0, Inf))\n#'\n#' # specify a student t prior\n#' prior(family = \"student_t\", mean = 0, sd = 13.3, df = 79)\n#'\n#' # specify a truncated t prior\n#' prior(family = \"student_t\", mean = 0, sd = 13.3, df = 79, range = c(-40, 40))\n#'\n#' # specify a cauchy prior\n#' prior(family = \"cauchy\", location = 0, scale = .707)\n#'\n#' # specify a half cauchy prior\n#' prior(family = \"cauchy\", location = 0, scale = 1, range = c(-Inf, 0))\n#'\n#' # specify a uniform prior\n#' prior(family = \"uniform\", min = 0, max = 20)\n#'\n#' # specify a point prior\n#' prior(family = \"point\", point = 0)\n#'\n#' # specify a beta prior\n#' prior(family = \"beta\", alpha = 2.5, beta = 3.8)\nprior <- function(family, ...) {\n if (!methods::existsMethod(signature = family, f = \"make_prior\")) {\n stop(family, \" is not a valid distribution family\")\n }\n make_prior(family = new(family), ...)\n}\n\n\nsetGeneric(\"make_prior\",\n function(family, ...) standardGeneric(\"make_prior\"),\n signature = \"family\",\n)\n\n\n\nsetMethod(\n \"make_prior\",\n signature(family = \"normal\"),\n function(family, mean, sd, ...) {\n make_prior.normal(family, mean, sd, ...)\n }\n)\n\nsetMethod(\n \"make_prior\",\n signature(family = \"point\"),\n function(family, point = 0) {\n if (missing(point)) {\n warning(\"Point value is missing. Assuming 0\", call. = FALSE)\n }\n make_prior.point(family, point)\n }\n)\n\n\nsetMethod(\n \"make_prior\",\n signature(family = \"uniform\"),\n function(family, min, max) {\n make_prior.uniform(family, min, max)\n }\n)\n\nsetMethod(\n \"make_prior\",\n signature(family = \"student_t\"),\n function(family, mean, sd, df, ...) {\n make_prior.student_t(family, mean, sd, df, ...)\n }\n)\n\n\nsetMethod(\n \"make_prior\",\n signature(family = \"cauchy\"),\n function(family, location = 0, scale, ...) {\n make_prior.cauchy(family, location, scale, ...)\n }\n)\n\n\nsetMethod(\n \"make_prior\",\n signature(family = \"beta\"),\n function(family, alpha, beta, ...) {\n make_prior.beta(family, alpha, beta, ...)\n }\n)\n\ntruncate_normalise <- function(family, range, ...) {\n unnormalised <- function(x) get_function(family)(x = x, ...) # nolint\n\n truncated_function <- function(x) {\n ifelse(in_range(x, range),\n unnormalised(x),\n 0\n )\n }\n\n constant <- 1 / integrate(\n Vectorize(truncated_function),\n range[1],\n range[2]\n )$value\n\n normalised <- function(x) truncated_function(x) * constant\n return(normalised)\n}\n\n\n#' @method prior normal\n#' @usage prior(family = \"normal\", mean, sd, range)\n#' @noRd\nmake_prior.normal <- function(family, mean, sd, range = NULL) { # nolint\n if (missing(mean) | missing(sd)) {\n stop(\"You must specify `mean` and `sd` for a normal prior\", call. = FALSE)\n }\n\n if (sd <= 0) {\n stop(\"`sd` must be greater than 0\")\n }\n\n if (missing(range)) {\n range <- get_default_range(family)\n }\n\n\n params <- list(mean = mean, sd = sd, range = range)\n\n func <- truncate_normalise(\n family = family,\n range = range,\n mean = mean,\n sd = sd\n )\n\n desc <- describe_prior(family, params)\n data <- make_prior_data(family, params, func)\n\n new(\n Class = \"prior\",\n data = data,\n theta_range = params$range,\n type = \"normal\",\n func = func,\n desc = desc,\n dist_type = \"continuous\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(mean = mean, sd = sd),\n function_text = paste0(\n \"prior(\\\"normal\\\", mean = \",\n mean, \", sd = \",\n sd, \")\"\n )\n )\n}\n\n#' @method prior point\n#' @usage prior(family = \"point\", point)\n#' @noRd\nmake_prior.point <- function(family, point = 0) {\n func <- function(x) get_function(family)(x = x, point = point)\n width <- 4\n range <- c(point - width, point + width)\n params <- list(point = point)\n # func <- make_distribution(\"point\", list(point = point)) # nolint\n desc <- describe_prior(family, params)\n\n data <- make_prior_data(family, params, func)\n new(\n Class = \"prior\",\n data = data,\n theta_range = c(point, point),\n func = func,\n type = \"point\",\n dist_type = \"point\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(point = point),\n function_text = paste0(\"prior(\\\"point\\\", point = \", point, \")\"),\n desc = desc\n )\n}\n\n\n\n#' @method prior uniform\n#' @usage prior(family = \"uniform\", min, max)\n#' @noRd\nmake_prior.uniform <- function(family, min, max) {\n if (missing(min) | missing(max)) {\n stop(\"You must specify `min` and `max` for a uniform prior\", call. = FALSE)\n }\n\n\n func <- function(x) get_function(family)(x = x, min = min, max = max)\n params <- list(min = min, max = max)\n\n desc <- describe_prior(family, params)\n\n data <- make_prior_data(family, params, func)\n\n new(\n Class = \"prior\",\n data = data,\n theta_range = c(min, max),\n func = func,\n type = \"normal\",\n desc = desc,\n dist_type = \"continuous\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(mean = mean, sd = sd),\n function_text = paste0(\n \"prior(\\\"uniform\\\", min = \",\n min, \", max = \", max, \")\"\n )\n )\n}\n\n\n\n#' @method prior student_t\n#' @usage prior(family = \"student_t\", mean, sd, df, range)\n#' @noRd\nmake_prior.student_t <- function(family, mean, sd, df, range = NULL) {\n if (missing(mean) | missing(sd) | missing(df)) {\n stop(\"You must specify `mean`, `sd`, and `df` for a student_t prior\",\n call. = FALSE\n )\n }\n\n if (missing(range)) {\n range <- get_default_range(family)\n }\n\n func <- truncate_normalise(\n family = family,\n range = range,\n mean = mean,\n sd = sd,\n df = df\n )\n\n\n\n\n params <- list(mean = mean, sd = sd, df = df, range = range)\n\n desc <- describe_prior(family, params)\n\n data <- make_prior_data(family, params, func)\n\n new(\n Class = \"prior\",\n data = data,\n theta_range = range,\n func = func,\n type = \"normal\",\n desc = desc,\n dist_type = \"continuous\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(mean = mean, sd = sd, df = df),\n function_text = paste0(\n \"prior(\\\"student_t\\\", mean = \", mean,\n \", sd = \", sd,\n \", df = \", df, \")\"\n )\n )\n}\n\n#' @method prior cauchy\n#' @usage prior(family = \"cauchy\", location, scale, range)\n#' @noRd\nmake_prior.cauchy <- function(family, location = 0, scale, range = NULL) {\n if (missing(range)) {\n range <- get_default_range(family)\n }\n\n func <- truncate_normalise(family = family, range = range, location = location, scale = scale)\n\n\n params <- list(location = location, scale = scale, range = range)\n desc <- describe_prior(family, params)\n\n data <- make_prior_data(family, params, func)\n\n\n\n new(\n Class = \"prior\",\n data = data,\n theta_range = params$range,\n func = func,\n type = \"normal\",\n desc = desc,\n dist_type = \"continuous\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(location = location, scale = scale),\n function_text = paste0(\n \"prior(\\\"cauchy\\\", location = \",\n location, \", scale = \",\n scale, \")\"\n )\n )\n}\n\n#' @method prior beta\n#' @usage prior(family = \"beta\", alpha, beta)\n#' @noRd\nmake_prior.beta <- function(family, alpha, beta, range = NULL) {\n if (missing(alpha) | missing(beta)) {\n stop(\"You must specify `alpha` and `beta` for a beta prior\", call. = FALSE)\n }\n\n if (missing(range)) {\n range <- get_default_range(family)\n }\n\n\n func <- truncate_normalise(family = family, range = range, beta = beta, alpha = alpha)\n params <- list(alpha = alpha, beta = beta, range = range)\n\n desc <- describe_prior(family, params)\n\n data <- make_prior_data(family, params, func)\n\n new(\n Class = \"prior\",\n data = data,\n theta_range = params$range,\n func = func,\n type = \"normal\",\n desc = desc,\n dist_type = \"continuous\",\n plot = list(\n range = get_plot_range(family)(params),\n labs = list(x = \"\\u03F4\", y = \"P(\\u03F4)\")\n ),\n parameters = list(alpha = alpha, beta = beta),\n function_text = paste0(\n \"prior(\\\"beta\\\", alpha = \",\n alpha, \", beta = \", beta, \")\"\n )\n )\n}\n", "meta": {"hexsha": "5cbcd23a1473e404579dc3ff3b71500adb256409", "size": 11939, "ext": "r", "lang": "R", "max_stars_repo_path": "R/priors.r", "max_stars_repo_name": "bayesplay/bayesplay", "max_stars_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-09T16:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:15:00.000Z", "max_issues_repo_path": "R/priors.r", "max_issues_repo_name": "bayesplay/bayesplay", "max_issues_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-07-07T10:39:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T18:30:26.000Z", "max_forks_repo_path": "R/priors.r", "max_forks_repo_name": "bayesplay/bayesplay", "max_forks_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-01T00:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T00:17:37.000Z", "avg_line_length": 25.0293501048, "max_line_length": 96, "alphanum_fraction": 0.6042382109, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6861722241591611}} {"text": "#' Computes the infloss on the off-diagonals of two matrices\n#'\n#' @param A Matrix\n#' @param B Matrix with the same size as A\n#' @return Maximal off-diagonal difference between A and B\n#' @export\ninfloss <- function(A, B)\n{\n dif <- abs(A - B)\n diag(dif) <- rep(0, dim(A)[1])\n return(max(dif))\n}\n\n#' Computes precision of a precision matrix estimator\n#'\n#' @param theta True precision matrix\n#' @param theta.estimate Estimator of theta\n#' @return Precision of theta.estimate with theta being the target\n#' @export\nprecision <- function(theta, theta.estimate)\n{\n adj.theta <- apply(theta, c(1,2), function(x) if (x!=0){return(1)} else {return(0)})\n diag(adj.theta) <- rep(0, dim(theta)[1])\n adj.estimate <- apply(theta.estimate, c(1,2), function(x) if (x!=0){return(1)} else {return(0)})\n diag(adj.estimate) <- rep(0, dim(theta)[1])\n num.edges.estimate <- sum(adj.estimate)/2\n num.edges.same <- sum (apply(adj.theta - adj.estimate, c(1,2), function(x) if(x!=0) {return(1)} else{return(0)}))/2\n return(num.edges.same/ num.edges.estimate)\n}\n\n#' Compute recall of a precision matrix estimator\n#'\n#' @param theta True precision matrix\n#' @param theta.estimate Estimator of theta\n#' @return Recall of theta.estimate with theta being the target\n#' @export\nrecall <- function(theta, theta.estimate)\n{\n adj.theta <- apply(theta, c(1,2), function(x) if (x!=0){return(1)} else {return(0)})\n diag(adj.theta) <- rep(0, dim(theta)[1])\n adj.estimate <- apply(theta.estimate, c(1,2), function(x) if (x!=0){return(1)} else {return(0)})\n diag(adj.estimate) <- rep(0, dim(theta)[1])\n num.edges.theta <- sum(adj.theta)/2\n num.edges.same <- sum (apply(adj.theta - adj.estimate, c(1,2), function(x) if(x!=0) {return(1)} else{return(0)}))/2\n return(num.edges.same/ num.edges.theta)\n}\n\n#' Compute performance of a precision matrix estimator\n#'\n#' @param theta True precision matrix\n#' @param theta.estimate Estimator of theta\n#' @param decimal Number of decimals such that entries of absolute size 1e-decimal are set to zero\n#' @return f1 F_1-score of theta.estimate with theta being the target\n#' @return recall Recall of theta.estimate with theta being the target\n#' @return precision Precision of theta.estimate with theta being the target\n#' @export\nf1score <- function(theta, theta.estimate, decimal=4)\n{\n #we don't want to include edges with values like e-17 which occure due to the \n #precision matrix generation algorithm. Thats why we round...\n theta <- round(theta, decimal)\n theta.estimate <- round(theta.estimate, decimal)\n \n #generate the adjacency matrices. diagonal entries are set to 0\n adj.theta <- apply(theta, c(1,2), function(x) if (x!=0){return(1)} else {return(0)})\n diag(adj.theta) <- rep(0, dim(theta)[1])\n #we use a little trick here: set values of the adjacency matrix to 2. \n #we do this so that we can count the number of same edges in an easy way:\n #if both edges are nonexistent -> adj.Theta - adj.estimate = 0 \n #if one of them is existent -> adj.Theta - adj.estimate \\in \\{ 1, -2\\}\n #if both are existent -> adj.Theta - adj.estimate = -1\n adj.estimate <- apply(theta.estimate, c(1,2), function(x) if (x!=0){return(2)} else {return(0)})\n diag(adj.estimate) <- rep(0, dim(theta)[1])\n \n # every edge occurs exactly 2 times\n num.edges.theta <- sum(adj.theta)/2\n num.edges.estimate <- sum(adj.estimate/2)/2\n \n num.edges.same <- sum(apply(adj.theta - adj.estimate, c(1,2), function(x) if(x==-1) {return(1)} else{return(0)})) / 2\n \n recall <- num.edges.same / num.edges.theta\n if( num.edges.estimate > 0)\n {\n precision <- num.edges.same / num.edges.estimate\n f1 <- 2 * (precision * recall)/ (precision + recall)\n }\n else\n {\n precision <- 0\n f1 <- 0\n }\n \n return(list(\"f1\"=f1, \"recall\"=recall, \"precision\"=precision))\n}\n", "meta": {"hexsha": "28a92fd3ebcb59a39d2b1ef56cfcbaafad557eb8", "size": 3779, "ext": "r", "lang": "R", "max_stars_repo_path": "R/metrics.r", "max_stars_repo_name": "MikeLasz/thav", "max_stars_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "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/metrics.r", "max_issues_repo_name": "MikeLasz/thav", "max_issues_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "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/metrics.r", "max_forks_repo_name": "MikeLasz/thav", "max_forks_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "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": 39.7789473684, "max_line_length": 119, "alphanum_fraction": 0.677427891, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6859826936302522}} {"text": "# Example : 1 Chapter : 8.2 Page No: 427\n# Find the currents\nA<-matrix(c(-1,-1,0,-1,0,0,1,0,-1,0,-1,0,0,1,1,0,0,-1,0,0,0,1,1,1),ncol=4)\nAT<-t(A)\nLaplacian_matrix<-AT%*%A\nLaplacian_matrix<-Laplacian_matrix[-4,-4]\nb<-c(1,0,0)\nx<-solve(Laplacian_matrix,b)\nx<-c(x,0)\nprint(\"Voltages are given by S * \")\nprint(x)\nprint(\"S is source\")\ny<--1*A%*%x\nprint(\"Currents are given by S * \")\nprint(y)", "meta": {"hexsha": "d56871389bf9f6e167d3c78ef44e8f32860942dc", "size": 391, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.2.1/Ex8.2_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.2.1/Ex8.2_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.2.1/Ex8.2_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 26.0666666667, "max_line_length": 74, "alphanum_fraction": 0.6265984655, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6859292614466607}} {"text": "\n#' The bivariate GLMGA distribution\n#'\n#' @param y1 vector of quantiles.\n#' @param y2 vector of quantiles.\n#' @param sigma vector of parameters with length = 2.\n#' @param a common parameter with length = 1.\n#' @param b vector of parameters with length = 2.\n#'\n#' @return Density function of the bivariate GLMGA distribution with parameters sigma, a and b.\n#' @export\n#'\n#' @examples\n#' n.grid <- 20\n#' sigma <- c(0.5, 0.5)\n#' a <- 20\n#' b <- c(5, 5)\n#' xgrid <- ygrid <- seq(0.01, 20, length.out = n.grid)\n#' grid <- expand.grid(\"u1\" = xgrid, \"u2\" = ygrid)\n#' mtrx3d <- matrix(0, nrow = nrow(grid), ncol = 3)\n#' mtrx3d[, 1] <- grid[, 1]\n#' mtrx3d[, 2] <- grid[, 2]\n#' for (i in 1:nrow(mtrx3d)) {\n#' mtrx3d[i, 3] <- dMGLMGA(\n#' y1 = grid[i, 1], y2 = grid[i, 2],\n#' sigma = sigma,\n#' a = a, b = b\n#' )\n#' }\n#' head(mtrx3d)\ndMGLMGA <- function(y1, y2, sigma, a, b) {\n sigma1 <- sigma[1]\n sigma2 <- sigma[2]\n b1 <- b[1]\n b2 <- b[2]\n d <- 2\n out1 <- gamma(a + d / 2) / (gamma(a) * gamma(0.5)^d * (sigma1 * y1 * sigma2 * y2)) * ((2 * b1)^sigma1 * y1)^(-1 / (2 * sigma1)) * ((2 * b2)^sigma2 * y2)^(-1 / (2 * sigma2))\n out2 <- (((2 * b1)^(sigma1) * y1)^(-1 / sigma1) + ((2 * b2)^(sigma2) * y2)^(-1 / sigma2) + 1)^(a + d / 2)\n\n z <- out1 / out2\n return(z)\n}\n", "meta": {"hexsha": "d7aef00bd6b98f2f132e5e4d2990887f0d553582", "size": 1276, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MGLMGA-distribution.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/MGLMGA-distribution.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/MGLMGA-distribution.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.6744186047, "max_line_length": 174, "alphanum_fraction": 0.5352664577, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6858948969145178}} {"text": "source('base.r')\n\n# calculate manhattan distance between vectors p, q\nmanhattan.distance <- function(p, q){\n return (sum(abs(p - q)))\n}\n\n# calculate median of input vector\nkmedians.medians.of.columns <- function(X){\n \n medians = list()\n nr_of_columns <- ncol(X)\n\n for (i in 1:nr_of_columns){\n medians[[i]] = median(X[,i], na.rm = F)\n }\n \n return(unlist(medians))\n}\n\n# initialize centroids by randomly selecting vectors from the dataset\nkmedians.init.centroids.with.random.selection <- function(X, nr_of_centroids){\n \n centroids <- list()\n nr_of_dimensions = ncol(X)\n \n random_indexes <- sample.int(nrow(X), nr_of_centroids)\n \n for (i in 1:nr_of_centroids){\n index = random_indexes[i]\n centroids[[i]] <- as.vector(X[index, ])\n }\n \n return (centroids)\n}\n\n# initialize centroids by calculating k-means clusters\nkmedians.init.centroids.with.kmeans <- function(X, nr_of_centroids){\n\n centroids <- list()\n nr_of_dimensions = ncol(X) \n kmeans_result <- kmeans(X, nr_of_centroids, nstart = 25)\n kmeans_centroids <- as.matrix(kmeans_result[\"centers\"][[1]])\n \n for (i in 1:nrow(kmeans_centroids)){\n centroids[[i]] <- as.vector(kmeans_centroids[i, ])\n }\n \n return (centroids)\n}\n\n# initialize centroids\nkmedians.init.centroids <- function(X, nr_of_centroids, type){\n \n if (type == 'k-means')\n return(kmedians.init.centroids.with.kmeans(X, nr_of_centroids))\n \n return(kmedians.init.centroids.with.random.selection(X, nr_of_centroids))\n}\n\n# calculate centroid that is nearest to data_vector\nkmedians.nearest.centroid <- function(centroids, data_vector){\n \n nr_of_centroids = length(centroids)\n distance_from_centroids = list()\n \n for (k in 1:nr_of_centroids){\n centroid = centroids[[k]]\n distance_from_centroids[[k]] = manhattan.distance(data_vector, centroid)\n }\n \n min_distance = min(unlist(distance_from_centroids))\n centroid_index = which.min(unlist(distance_from_centroids))\n \n return (list(centroid_index, min_distance))\n}\n\n# allocate data vectors to centroids\nkmedians.allocate.to.centroids <- function(X, centroids){\n \n nr_of_items = nrow(X)\n centroid_allocations = matrix(nrow = nr_of_items, ncol = 1)\n \n for (i in 1:nr_of_items){\n data_vector <- X[i,]\n nearest_centroid <- kmedians.nearest.centroid(centroids, data_vector)\n centroid_allocations[i,1] = nearest_centroid[[1]]\n }\n \n return(centroid_allocations)\n}\n\n# update centroids based on median of latest allocations\nkmedians.update.centroids <- function(X, centroids, centroid_allocations){\n \n new_centroids <- list()\n nr_of_centroids <- length(centroids)\n \n for (k in 1:nr_of_centroids){\n item_indexes_allocated_to_centroid <- which(centroid_allocations[, 1] == k)\n items_allocated_to_centroid <- as.matrix(X[item_indexes_allocated_to_centroid, ])\n\n if (nrow(items_allocated_to_centroid) == 0){\n new_centroids[[k]] <- integer(ncol(X))\n }\n else{\n items_medians <- kmedians.medians.of.columns(items_allocated_to_centroid)\n new_centroids[[k]] <- items_medians\n }\n }\n \n return(new_centroids)\n}\n\n# perform kmedians clustering on input data\nkmedians <- function(X, centers, max_iterations = 100){\n \n centroids <- kmedians.init.centroids(X, centers, 'k-means')\n\n for (i in 1:max_iterations){\n\n centroid_allocations = kmedians.allocate.to.centroids(X, centroids)\n new_centroids <- kmedians.update.centroids(X, centroids, centroid_allocations)\n print(paste('Update centroids - iteration :', i, sep = \" \"))\n\n no_change_in_centroids = vectors.are.equal(unlist(centroids), unlist(new_centroids))\n if (no_change_in_centroids) { break }\n\n centroids = new_centroids\n }\n \n rownames(centroid_allocations) <- row.names(X)\n return(centroid_allocations)\n}", "meta": {"hexsha": "a20bdb5a34c1ebbd5fb7d691161539f8b5711ce2", "size": 3734, "ext": "r", "lang": "R", "max_stars_repo_path": "down-stream-analysis/k.medians.r", "max_stars_repo_name": "tzouvanas/microbiome", "max_stars_repo_head_hexsha": "988b50f70cb481e849165ba5a77a99e4fbf265b8", "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": "down-stream-analysis/k.medians.r", "max_issues_repo_name": "tzouvanas/microbiome", "max_issues_repo_head_hexsha": "988b50f70cb481e849165ba5a77a99e4fbf265b8", "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": "down-stream-analysis/k.medians.r", "max_forks_repo_name": "tzouvanas/microbiome", "max_forks_repo_head_hexsha": "988b50f70cb481e849165ba5a77a99e4fbf265b8", "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.8656716418, "max_line_length": 88, "alphanum_fraction": 0.7134440279, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6858742366817392}} {"text": "knitr::opts_chunk$set(echo = TRUE)\nset.seed(2021)\n\nlibrary(tidyverse)\nlibrary(rBeta2009)\nlibrary(kableExtra)\nlibrary(latex2exp)\nlibrary(magrittr)\nlibrary(pwr)\n\ngx <- function(x) {\n return(0.5 * exp(-abs(x)))\n}\n\nfx <- function(x) {\n return(exp(-(abs(x) ^ 3) / 3))\n}\n\nfgx <- function(x) {\n return(fx(x) / gx(x))\n}\n\nm <- fgx(-1)\n\nm_gx <- function(x, m) {\n return(m * gx(x))\n}\n\npar(mfrow = c(2, 2))\n\ncurve(fx, -5, 5, xlab = \"x\", ylab = \"f(x)\",\n col = \"darkgrey\", lwd = 2, main = \"Gráfico de f(x)\")\n\ncurve(gx, -5, 5, xlab = \"y\", ylab = \"g(y)\",\n col = \"darkgrey\", lwd = 2, main = \"Gráfico de g(y)\")\n\ncurve(fgx, -4, 4, ylab = \"f(x)/g(x)\", main = \"Gráfico de f(x)/g(x)\")\npoints(c(-1, 1), c(m, m), pch = 20, col = \"blue\")\nabline(h = m, lty = 2, col = \"blue\")\nsegments(c(-1, 1), c(0, 0), c(-1, 1), c(m, m), lty = 2, col = \"blue\")\n\ncurve(m_gx(x, m), -5, 5, col = \"red\", ylab = \"f(x) e m*g(x)\",\n main = \"Gráfico de f(x) e mg(x)\")\ncurve(fx(x), add = TRUE)\nlegend(\"topright\", c(\"f(x)\", \"m*g(x)\"), col = c(\"black\", \"red\"),\n lty = 1, bty = \"n\")\n\ngerador <- function(n) {\n nger <- n0 <- 0\n ax <- c()\n while (n0 < n) {\n rej <- TRUE\n while (rej) {\n nger <- nger + 1\n u <- runif(1)\n y <- ifelse(u <= 0.5, log(2 * u), - log(2 * (1 - u)))\n\n if (m * runif(1) <= fgx(y)) {\n n0 <- n0 + 1\n ax[n0] <- y\n rej <- FALSE\n }\n }\n }\n\n result <- list(sample = ax, n_gerado = nger)\n return(result)\n\n}\n\namostra_gerada_50 <- gerador(50)\nax_50 <- amostra_gerada_50$sample\n\namostra_gerada_100 <- gerador(100)\nax_100 <- amostra_gerada_100$sample\n\namostra_gerada_400 <- gerador(400)\nax_400 <- amostra_gerada_400$sample\n\npar(mfrow = c(2, 2))\nhist(ax_50, freq = FALSE, main = \"Histograma da amostra n = 50\",\n xlab = \"x\", ylab = \"Densidade\",\n col = \"orange\", border = \"brown\")\nhist(ax_100, freq = FALSE, main = \"Histograma da amostra n = 100\",\n xlab = \"x\", ylab = \"Densidade\",\n col = \"orange\", border = \"brown\")\nhist(ax_400, freq = FALSE, main = \"Histograma da amostra n = 400\",\n xlab = \"x\", ylab = \"Densidade\",\n col = \"orange\", border = \"brown\")\n\namostra <- c(ax_50, ax_100, ax_400)\ntamanho <- c(rep(50, length(ax_50)),\n rep(100, length(ax_100)),\n rep(400, length(ax_400)))\n\ndf <- data.frame(amostra, tamanho)\n\nboxplot(amostra ~ tamanho,\n data = df,\n main = \"Diferentes Boxplots para\\ncada tamanho de amostra\",\n xlab = \"Tamanho da amostra\",\n ylab = \"Observações\",\n col = \"orange\",\n border = \"brown\"\n)\n\nr <- 1000\nlambda <- 2\npo_sample <- function(r, lambda, n) {\n\n pvalue <- c()\n aceptance <- c()\n medias_v <- c()\n poder_dif <- seq(2.2, 4, length.out = 5) - 2\n power_1 <- c()\n\n\n for (i in 1:r) {\n\n sample_p <- rpois(n, lambda)\n media <- mean(sample_p)\n\n p_value <- pnorm(media, mean = lambda, sd = sqrt(1 / n * lambda))\n pvalue[i] <- p_value\n\n medias_v[i] <- media\n\n if (pvalue[i] >= 0.05) {\n aceptance[i] <- 1\n }\n else {\n aceptance[i] <- 0\n }\n }\n\n poder_1 <- power.t.test(n = n, delta = poder_dif[1],\n sd = sqrt(1 / n * lambda),\n sig.level = .05,\n alternative = \"two.sided\",\n type = \"one.sample\")\n power_1[1] <- (as.numeric(unlist(poder_1[5])))\n\n poder_2 <- power.t.test(n = n, delta = poder_dif[2],\n sd = sqrt(1 / n * lambda),\n sig.level = .05,\n alternative = \"one.sided\",\n type = \"one.sample\")\n power_1[2] <- as.numeric(unlist(poder_2[5]))\n\n poder_3 <- power.t.test(n = n, delta = poder_dif[3],\n sd = sqrt(1 / n * lambda),\n sig.level = .05,\n alternative = \"one.sided\",\n type = \"one.sample\")\n power_1[3] <- as.numeric(unlist(poder_3[5]))\n\n poder_4 <- power.t.test(n = n, delta = poder_dif[4],\n sd = sqrt(1 / n * lambda),\n sig.level = .05,\n alternative = \"one.sided\",\n type = \"one.sample\")\n power_1[4] <- as.numeric(unlist(poder_4[5]))\n\n poder_5 <- power.t.test(n = n, delta = poder_dif[5],\n sd = sqrt(1 / n * lambda),\n sig.level = .05,\n alternative = \"one.sided\",\n type = \"one.sample\")\n power_1[5] <- as.numeric(unlist(poder_5[5]))\n\n results <- list(pvalor = pvalue, aceita = aceptance,\n media = medias_v, poder = power_1)\n\n return(results)\n}\n\na <- po_sample(r, lambda, 10)\nb <- po_sample(r, lambda, 30)\nc <- po_sample(r, lambda, 75)\nd <- po_sample(r, lambda, 100)\n\nfreqa <- table(a$aceita) * 100 / sum(table(a$aceita))\nfreqb <- table(b$aceita) * 100 / sum(table(b$aceita))\nfreqc <- table(c$aceita) * 100 / sum(table(c$aceita))\nfreqd <- table(d$aceita) * 100 / sum(table(d$aceita))\n\ntabela <- rbind(\"Amostra n = 10\" = freqa, \"Amostra n = 30\" = freqb,\n \"Amostra n = 75\" = freqc, \"Amostra n = 100\" = freqd)\ntabela_1 <- as.data.frame(tabela)\n\ntabela_1 %>% mutate_all(linebreak) %>%\nknitr::kable(tabela_1, align = \"c\",\n caption = \"Tabela de Erro Tipo I (em %)\",\n col.names = c(\"Rejeita Hipótese Nula\",\n \"Não Rejeita Hipótese Nula\"),\n format = \"latex\") %>%\n kable_styling(position = \"center\")\n\ntabela_2 <- rbind(\"Amostra n = 10\" = a$poder, \"Amostra n = 30\" = b$poder,\n \"Amostra n = 75\" = c$poder, \"Amostra n = 100\" = d$poder)\np <- seq(2.2, 4, length.out = 5)\ndf2 <- data.frame(round(tabela_2, 2))\n\nknitr::kable(df2, align = \"c\",\n caption = \"Tabela do Poder do Teste $\\\\lambda \\\\in[2,2;4]$\",\n col.names = c(paste(\"$\\\\lambda =$\", p[1]),\n paste(\"$\\\\lambda =$\", p[2]),\n paste(\"$\\\\lambda =$\", p[3]),\n paste(\"$\\\\lambda =$\", p[4]),\n paste(\"$\\\\lambda =$\", p[5])),\n format = \"latex\", escape = F) %>%\nkable_styling(position = \"center\")\n\nlibrary(\"rmarkdown\")\nrender(\"Trabalho1/trab1.Rmd\", \"pdf_document\")\n\nupdate.packages(ask = FALSE, checkBuilt = TRUE)\ntinytex::tlmgr_update()\n", "meta": {"hexsha": "c387d038ca4f511b8b0e19b3bbfc6b65ed4e41f4", "size": 6305, "ext": "r", "lang": "R", "max_stars_repo_path": "Trabalho1/trab1.r", "max_stars_repo_name": "vitorgt/SME0806", "max_stars_repo_head_hexsha": "ab397ef7cd5b79e3886960b7e50e7c0b0719325b", "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": "Trabalho1/trab1.r", "max_issues_repo_name": "vitorgt/SME0806", "max_issues_repo_head_hexsha": "ab397ef7cd5b79e3886960b7e50e7c0b0719325b", "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": "Trabalho1/trab1.r", "max_forks_repo_name": "vitorgt/SME0806", "max_forks_repo_head_hexsha": "ab397ef7cd5b79e3886960b7e50e7c0b0719325b", "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.7899543379, "max_line_length": 74, "alphanum_fraction": 0.5068992863, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6856262703273123}} {"text": "a <- 5.0\nl <- 8.0\n\nn <- 10000\ncentX <- a/2 * runif(n)\nalpha <- runif(n, min=0, max=pi/2)\n\nif (l < a) {\n\tifa <- (centX <= l*cos(alpha) / 2) \n\tp <- mean(ifa)\n\tprint(p)\n\tnewPi <- 2 * l / (p * a)\n\tprint(newPi)\n} else {\n\tminArr <- vector()\n\tfor (i in seq(1, n))\n\t{\n\t\tminArr <- c(minArr, min(c(l*cos(alpha[i])/2, a/2)))\n\t}\n\tifa <- (centX <= minArr)\n\tp <- mean(ifa)\n\tprint(p)\n\tnewPi <- 2 * l / ((p-1) * a) - 2 * (sqrt(l^2-a^2) + a*asin(a/l)) / ((p-1) * a)\n\tprint(newPi)\n}\n\n\n", "meta": {"hexsha": "c49b2f299a9aa57c3c5b3616854d40d1e2941af8", "size": 467, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK1/sem1/needle.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK1/sem1/needle.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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": "TASK1/sem1/needle.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "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.6785714286, "max_line_length": 79, "alphanum_fraction": 0.4817987152, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6856262703273122}} {"text": "\n\n> ## Demo from RO implementors\n> library(R0)\nLoading required package: MASS\n> \n> # Generating an epidemic with given parameters\n> mGT <- generation.time(\"gamma\", c(3,1.5))\n> mEpid <- sim.epid(epid.nb=1, GT=mGT, epid.length=30, family=\"poisson\", R0=1.67, peak.value=500)\n> mEpid <- mEpid[,1]\n> # Running estimations\n> est <- estimate.R(epid=mEpid, GT=mGT, methods=c(\"EG\",\"ML\",\"TD\"))\nWaiting for profiling to be done...\nWarning messages:\n1: In est.R0.TD(epid = c(1, 1, 1, 1, 1, 3, 1, 2, 1, 6, 2, 6, 4, 12, :\n Simulations may take several minutes.\n2: In est.R0.TD(epid = c(1, 1, 1, 1, 1, 3, 1, 2, 1, 6, 2, 6, 4, 12, :\n Using initial incidence as initial number of cases.\n> \n> # Model estimates and goodness of fit can be plotted\n> plot(est)\n> plotfit(est)\n# Sensitivity analysis for the EG estimation; influence of begin/end dates\ns.a <- sensitivity.analysis(res=est$estimates$EG, begin=1:15, end=16:30, sa.type=\"time\")\n# This sensitivity analysis can be plotted\nplot(s.a)\n\n# Set up the R environment with the necessary packages\ninstall.packages(c(\"dplyr\", \"R0\", \"magrittr\", \"RCurl\"))\n\n# RUN PATTERN DEVELOPED BY C. MOREFIELD and ABSTRACTED by J. Mallery\n# Load libraries\nlibrary(R0)\nlibrary(RCurl)\nlibrary(data.table)\n\nfetch_JHU_Data <- function() {\n\tcsv <- getURL(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\")\n\tdata <- read.csv(text = csv, check.names = F)\n\tnames(data)[1] <- \"ProvinceState\"\n\tnames(data)[2] <- \"CountryRegion\"\n\tnumberColumns <- length(names(data))\n\tdata.table(data) }\n\t\nprepare_dates <- function (date_vector)\t{as_date(mdy(date_vector))}\n\nfetch_JHU_Dates <- function() {\n\trawdat = RCurl::getURL(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\")\n\tcurdata = read.csv(text=rawdat, stringsAsFactors=FALSE, check.names=FALSE)\n\tdate_vector <- names(curdata)[-c(1:4)]\n\tprepare_dates(date_vector )\n\t}\n\t\t\ntrimLeading <- function(x, value=0) {\n\tw <- which.max(cummax(x != value))\n\tx[seq.int(w, length(x))] }\n \nextract_country_data <- function (name, data) {\n\tcdata <- data[CountryRegion == name] \n\tcdata}\n\nextract_ProvinceState_data <- function (name, data) {data[ProvinceState == name] }\n\ndiff_data <- function (cdata) {\n\tcdata <- append(cdata[1], diff(cdata))\n\tcdata <- trimLeading(cdata, value = 0)\n\tcdata}\n\nprepare_data <- function (cdata) {\n\tcdata <- cdata[,5:numberColumns] \n\tnames(cdata) <- NULL\n\tcdata <- unlist(c(cdata))\n\tcdata <- diff_data(cdata)\n\tcdata}\n\n# Fetch the data\nmy_data <- fetch_JHU_Data()\t\nnumberColumns <- length(names(my_data))\t\nmy_dates <- fetch_JHU_Dates()\n\n# SERIAL TIME INTERVAL\nGT.cov2 <- generation.time(\"gamma\", c(4.75, 3.96))\n# GT.cov2 <- generation.time(\"gamma\", c(5.8,.95)) # from DOI 10.7326/M20-0504\n\n# EUROPE\t\ndata.France <- extract_ProvinceState_data(\"France\", my_data)\ndiff.France <- prepare_data(data.France)\nR.France <- My_Estimate_R(my_dates,diff.France)\nR.France \n\nepid.count <- prepare_data(extract_country_data(\"Germany\", my_data))\nR.Germany <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Germany\n\nepid.count <- prepare_data(extract_country_data(\"Germany\", my_data))\nR.Germany <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Germany\n\nepid.count <- prepare_data(extract_country_data(\"Italy\", my_data))\nR.Italy <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Italy\n\nepid.count <- prepare_data(extract_country_data(\"Spain\", my_data))\nR.Spain <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Spain \n\nepid.count <- prepare_data(extract_ProvinceState_data(\"United Kingdom\", my_data))\nR.UK <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.UK\n\n# MIDDLE EAST\nepid.count <- prepare_data(extract_country_data(\"Iran\", my_data))\nR.Iran<- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Iran \n\n# ASIA\nepid.count <- prepare_data(extract_country_data(\"Korea, South\", my_data))\nR.SouthKorea <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.SouthKorea\n\nepid.count <- prepare_data(extract_country_data(\"Singapore\", my_data))\nR.Singapore <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Singapore\n\n# US States and Regions\n\nepid.count <- prepare_data(extract_ProvinceState_data(\"Illinois\", my_data))\nR.Illinois <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Illinois\n\nepid.count <- prepare_data(extract_ProvinceState_data(\"New York\", my_data))\nR.NewYork <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.NewYork\n\nepid.count <- prepare_data(extract_ProvinceState_data(\"Massachusetts\", my_data))\nR.Massachusetts <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Massachusetts\n\nepid.count <- prepare_data(extract_ProvinceState_data(\"California\", my_data))\nR.California <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.California\n\nepid.count <- prepare_data(extract_ProvinceState_data(\"New Hampshire\", my_data))\nR.NewHampshire <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.NewHampshire\n\n\nepid.count <- c(267, 99, 76, 126, 4, 71, 261, 172, 0, 362, 148)\nR.Washington <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Washington\n\ndata.US <- c(2, 2, 5, 5, 5, 5, 5, 7, 8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 15, 15, 15, 51, 51, 57, 58, 60, 68, 74, 98, 118, 149, 217, 262, 402, 518, 583, 959, 1281, 1663, 2179, 2727, 3499, 4632, 6421, 7783, 13677, 19100, 25489, 38757)\n\nepid.count <- diff_data(data.US)\nR.US <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.US\n\nData.Grafton.NH <- c(1,2,2,2,2,2,3,3,3,3,3,3,3,3,5,7,7,9,12,13)\nepid.count <- diff_data(Data.Grafton.NH)\nR.Grafton.NH <- estimate.R(epid.count, GT = GT.cov2, methods = c(\"EG\"))\nR.Grafton.NH \n\n# Vince Carey R Code to Estimate time dependent reproduction numbers \n# with the attached code you should be able to do\n# %vjcair> Rscript pure.R | tail -1\n# Waiting for profiling to be done...\n# 4.920046 \nsuppressMessages({\nsuppressPackageStartupMessages({\nii = rownames(installed.packages())\nif (!(\"BiocManager\" %in% ii)) install.packages(\"BiocManager\")\nlibrary(BiocManager)\nif (!(\"R0\" %in% ii)) BiocManager::install(\"R0\")\nlibrary(R0)\nif (!(\"lubridate\" %in% ii)) BiocManager::install(\"lubridate\")\nlibrary(lubridate)\n})\n})\n\n#\tc(\"1/22/20\", \"1/23/20\", \"1/24/20\", \"1/25/20\", \"1/26/20\", \"1/27/20\", \"1/28/20\", \"1/29/20\", \"1/30/20\", \"1/31/20\", \"2/1/20\", \"2/2/20\", \"2/3/20\", \"2/4/20\", \"2/5/20\", \"2/6/20\", \"2/7/20\", \"2/8/20\", \"2/9/20\", \"2/10/20\", \"2/11/20\", \"2/12/20\", \"2/13/20\", \"2/14/20\", \"2/15/20\", \"2/16/20\", \"2/17/20\", \"2/18/20\", \"2/19/20\", \"2/20/20\", \"2/21/20\", \"2/22/20\", \"2/23/20\", \"2/24/20\", \"2/25/20\", \"2/26/20\", \"2/27/20\", \"2/28/20\", \"2/29/20\", \"3/1/20\", \"3/2/20\", \"3/3/20\", \"3/4/20\", \"3/5/20\", \"3/6/20\", \"3/7/20\", \"3/8/20\", \"3/9/20\", \"3/10/20\", \"3/11/20\", \"3/12/20\", \"3/13/20\", \"3/14/20\", \"3/15/20\", \"3/16/20\", \"3/17/20\", \"3/18/20\", \"3/19/20\", \"3/20/20\", \"3/21/20\")\ndatevec <- as_date(mdy(\n\tc( \"1/24/20\", \"1/25/20\", \"1/26/20\", \"1/27/20\", \"1/28/20\", \"1/29/20\", \"1/30/20\", \"1/31/20\", \"2/1/20\", \"2/2/20\", \"2/3/20\", \"2/4/20\", \"2/5/20\", \"2/6/20\", \"2/7/20\", \"2/8/20\", \"2/9/20\", \"2/10/20\", \"2/11/20\", \"2/12/20\", \"2/13/20\", \"2/14/20\", \"2/15/20\", \"2/16/20\", \"2/17/20\", \"2/18/20\", \"2/19/20\", \"2/20/20\", \"2/21/20\", \"2/22/20\", \"2/23/20\", \"2/24/20\", \"2/25/20\", \"2/26/20\", \"2/27/20\", \"2/28/20\", \"2/29/20\", \"3/1/20\", \"3/2/20\", \"3/3/20\", \"3/4/20\", \"3/5/20\", \"3/6/20\", \"3/7/20\", \"3/8/20\", \"3/9/20\", \"3/10/20\", \"3/11/20\", \"3/12/20\", \"3/13/20\", \"3/14/20\", \"3/15/20\", \"3/16/20\", \"3/17/20\", \"3/18/20\", \"3/19/20\", \"3/20/20\", \"3/21/20\", \"3/22/20\")\n\t))\ncumevents <- data.US\nnames(cumevents) = datevec\nplot(cumevents~as_date(ymd(names(cumevents))), main=\"US as of 3/22/2020 from JHU. World-o-Meters\")\nepid.count <- (diff(cumevents))\nest1 = estimate.R(epid.count, GT = GT.cov2 , t = as_date(ymd(names(epid.count))),\n begin=1L, end=as.integer(length(epid.count)), methods=c(\"EG\"))\ncat(est1$estimates$EG$R, \"\\n\")\n\nlibrary(dplyr)\nlibrary(magrittr)\nlibrary(RCurl)\nlibrary(R0)\n\nfetch_JHU_Data = function (as.data.frame = FALSE) \n{\n csv <- getURL(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\")\n data <- read.csv(text = csv, check.names = F)\n names(data)[1] <- \"ProvinceState\"\n names(data)[2] <- \"CountryRegion\"\n numberColumns <- length(names(data))\n if (!as.data.frame) \n return(data.table(data))\n data\n}\nget_series = function (province = \"\", country, dataset = try(fetch_JHU_Data(as.data.frame = TRUE))) \n{\n if (inherits(dataset, \"try-error\")) \n stop(\"could not get data from fetch_JHU_Data()\")\n stopifnot(all(c(\"ProvinceState\", \"CountryRegion\") %in% colnames(dataset)))\n stopifnot(country %in% dataset$CountryRegion)\n ans = dataset %>% dplyr::filter(ProvinceState == province & \n CountryRegion == country)\n ans[, -c(1:4)]\n}\nplot_series = function (province = \"\", country, dataset = try(fetch_JHU_Data(as.data.frame = TRUE)), \n ...) \n{\n if (inherits(dataset, \"try-error\")) \n stop(\"could not get data from fetch_JHU_Data()\")\n ser = get_series(province = province, country = country, \n dataset = dataset)\n dates = lubridate::as_date(mdy(fix_slash_dates(names(dataset)[-c(1:4)])))\n plot(dates, ser, main = paste(province, country), ...)\n}\n\nas_vector = function(x) data.matrix(x)[1,,drop=TRUE]\n\nmy_plot <- function (title, cumulative_vector){}\n\tplot(cumulative_vector~as_date(ymd(names(cumulative_vector))), main= title)\n\n# cvec = as_vector(get_series(country=\"Italy\"))\n# ivec = diff(cvec)\n# tivec = trimLeading(ivec)\n# estimate.R(tivec, GT=generation.time(\"gamma\", c(3.5,4.8)), methods=\"EG\")\n# estimate.R(incidence_vector, GT = generation_time , t = as_date(myd(names(tivec))), begin=1L, end=as.integer(length(incidence_vector)), methods=c(\"EG\"))}\t\n# estimate.R(incidence_vector, GT=generation_time, methods=\"EG\")\n# \testimate.R(incidence_vector, GT = generation_time , t = as_date(myd(names(tivec))), begin=1L, end=as.integer(length(incidence_vector)), methods=c(\"EG\"))\n\n# pass in the time vector and diff data\t\nMy_Estimate_R <- function (generation_time, incidence_vector) {\n\t\testimate.R(incidence_vector, GT = generation_time , t = as_date(myd(names(incidence_vector))), begin=1L, end=as.integer(length(incidence_vector)), methods=c(\"EG\"))\n\t}\n\n# SCRIPTS FOR ESTIMATING VARIOUS REGIONS\n\nGT.cov2 <- generation.time(\"gamma\", c(4.75, 3.96))\n\ndata.France <- as_vector(get_series(\"France\", \"France\"))\ndiff.France <- diff_data(data.France)\nR.France <- My_Estimate_R (GT.cov2, diff.France)\nR.France\n\ndata.Germany <- as_vector(get_series(\"\", \"Germany\"))\ndiff.Germany <- diff_data(data.Germany)\nR.Germany <- My_Estimate_R (GT.cov2, diff.Germany)\nR.Germany\n\ndata.Italy <- as_vector(get_series(\"\", \"Italy\"))\ndiff.Italy <- diff_data(data.Italy)\nR.Italy <- My_Estimate_R (GT.cov2, diff.Italy)\nR.Italy\n\ndata.Spain <- as_vector(get_series(\"\", \"Spain\"))\ndiff.Spain <- diff_data(data.Spain)\nR.Spain <- My_Estimate_R (GT.cov2, diff.Spain)\nR.Spain\n\ndata.UK <- as_vector(get_series(\"United Kingdom\", \"United Kingdom\",))\ndiff.UK <- diff_data(data.UK)\nR.UK <- My_Estimate_R (GT.cov2, diff.UK)\nR.UK\n\n# Middle East\n\ndata.Iran <- as_vector(get_series(\"\", \"Iran\"))\ndiff.Iran <- diff_data(data.Iran)\nR.Iran <- My_Estimate_R (GT.cov2, diff.Iran)\nR.Iran\n\ndata.SouthKorea <- as_vector(get_series(\"\", \"Korea, South\"))\ndiff.SouthKorea <- diff_data(data.SouthKorea)\nR.SouthKorea <- My_Estimate_R (GT.cov2, diff.SouthKorea)\nR.SouthKorea\n\ndata.Singapore <- as_vector(get_series(\"\", \"Singapore\"))\ndiff.Singapore <- diff_data(data.Singapore)\nR.Singapore <- My_Estimate_R (GT.cov2, diff.Singapore)\nR.Singapore\n\n# US States and Regions\n\ndata.NewYork <- as_vector(get_series(\"New York\",\"US\"))\ndiff.NewYork <- diff_data(data.NewYork)\nR.NewYork <- My_Estimate_R (GT.cov2, diff.NewYork)\nR.NewYork\n\ndata.Illinois <- as_vector(get_series(\"Illinois\", \"US\"))\ndiff.Illinois <- diff_data(data.Illinois)\nR.Illinois <- My_Estimate_R (GT.cov2, diff.Illinois)\nR.Illinois\n\ndata.Massachusetts <- as_vector(get_series(\"Massachusetts\", \"US\"))\ndiff.Massachusetts <- diff_data(data.Massachusetts)\nR.Massachusetts <- My_Estimate_R (GT.cov2, diff.Massachusetts)\nR.Massachusetts\n\ndata.California <- as_vector(get_series(\"California\", \"US\"))\ndiff.California <- diff_data(data.California)\nR.California <- My_Estimate_R (GT.cov2, diff.California)\nR.California\n\ndata.NewHampshire <- as_vector(get_series(\"New Hampshire\", \"US\"))\ndiff.NewHampshire <- diff_data(data.NewHampshire)\nR.NewHampshire <- My_Estimate_R (GT.cov2, diff.NewHampshire)\nR.NewHampshire\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\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\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": "13fd195cb8c0dc4cea500975022639965155798c", "size": 12740, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/scripts/mallery-calculate-R0-JHU3.r", "max_stars_repo_name": "mymil/sars2pack", "max_stars_repo_head_hexsha": "2a3def3ccea4bf5565b0d06a6d40d169b11f0e53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-04T17:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T17:29:15.000Z", "max_issues_repo_path": "inst/scripts/mallery-calculate-R0-JHU3.r", "max_issues_repo_name": "mymil/sars2pack", "max_issues_repo_head_hexsha": "2a3def3ccea4bf5565b0d06a6d40d169b11f0e53", "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/scripts/mallery-calculate-R0-JHU3.r", "max_forks_repo_name": "mymil/sars2pack", "max_forks_repo_head_hexsha": "2a3def3ccea4bf5565b0d06a6d40d169b11f0e53", "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.6915422886, "max_line_length": 645, "alphanum_fraction": 0.6771585557, "num_tokens": 4440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129513, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6855390843657826}} {"text": "##### Chapter 3: Classification using Nearest Neighbors --------------------\r\n\r\n## Example: Classifying Cancer Samples ----\r\n## Step 2: Exploring and preparing the data ---- \r\n\r\n# import the CSV file\r\nwbcd <- read.csv(\"wisc_bc_data.csv\", stringsAsFactors = FALSE)\r\n\r\n# examine the structure of the wbcd data frame\r\nstr(wbcd)\r\n\r\n# drop the id feature\r\nwbcd <- wbcd[-1]\r\n\r\n# table of diagnosis\r\ntable(wbcd$diagnosis)\r\n\r\n# recode diagnosis as a factor\r\nwbcd$diagnosis <- factor(wbcd$diagnosis, levels = c(\"B\", \"M\"),\r\n labels = c(\"Benign\", \"Malignant\"))\r\n\r\n# table or proportions with more informative labels\r\nround(prop.table(table(wbcd$diagnosis)) * 100, digits = 1)\r\n\r\n# summarize three numeric features\r\nsummary(wbcd[c(\"radius_mean\", \"area_mean\", \"smoothness_mean\")])\r\n\r\n# create normalization function\r\nnormalize <- function(x) {\r\n return ((x - min(x)) / (max(x) - min(x)))\r\n}\r\n\r\n# test normalization function - result should be identical\r\nnormalize(c(1, 2, 3, 4, 5))\r\nnormalize(c(10, 20, 30, 40, 50))\r\n\r\n# normalize the wbcd data\r\nwbcd_n <- as.data.frame(lapply(wbcd[2:31], normalize))\r\n\r\n# confirm that normalization worked\r\nsummary(wbcd_n$area_mean)\r\n\r\n# create training and test data\r\nwbcd_train <- wbcd_n[1:469, ]\r\nwbcd_test <- wbcd_n[470:569, ]\r\n\r\n# create labels for training and test data\r\n\r\nwbcd_train_labels <- wbcd[1:469, 1]\r\nwbcd_test_labels <- wbcd[470:569, 1]\r\n\r\n## Step 3: Training a model on the data ----\r\n\r\n# load the \"class\" library\r\nlibrary(class)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\r\n cl = wbcd_train_labels, k=21)\r\n\r\n## Step 4: Evaluating model performance ----\r\n\r\n# load the \"gmodels\" library\r\nlibrary(gmodels)\r\n\r\n# Create the cross tabulation of predicted vs. actual\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\r\n prop.chisq=FALSE)\r\n\r\n## Step 5: Improving model performance ----\r\n\r\n# use the scale() function to z-score standardize a data frame\r\nwbcd_z <- as.data.frame(scale(wbcd[-1]))\r\n\r\n# confirm that the transformation was applied correctly\r\nsummary(wbcd_z$area_mean)\r\n\r\n# create training and test datasets\r\nwbcd_train <- wbcd_z[1:469, ]\r\nwbcd_test <- wbcd_z[470:569, ]\r\n\r\n# re-classify test cases\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\r\n cl = wbcd_train_labels, k=21)\r\n\r\n# Create the cross tabulation of predicted vs. actual\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\r\n prop.chisq=FALSE)\r\n\r\n# try several different values of k\r\nwbcd_train <- wbcd_n[1:469, ]\r\nwbcd_test <- wbcd_n[470:569, ]\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=1)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=5)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=11)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=15)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=21)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n\r\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=27)\r\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\r\n", "meta": {"hexsha": "2ff821b4f1f8b73d0b222c5b42ec421a10520a20", "size": 3566, "ext": "r", "lang": "R", "max_stars_repo_path": "Training/MachineLearning/code/chapter 3/2148_03.r", "max_stars_repo_name": "davidmeza1/NASADatanauts", "max_stars_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-10-05T16:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T16:23:31.000Z", "max_issues_repo_path": "Training/MachineLearning/code/chapter 3/2148_03.r", "max_issues_repo_name": "davidmeza1/NASADatanauts", "max_issues_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "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": "Training/MachineLearning/code/chapter 3/2148_03.r", "max_forks_repo_name": "davidmeza1/NASADatanauts", "max_forks_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-04-27T11:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T19:22:24.000Z", "avg_line_length": 32.4181818182, "max_line_length": 90, "alphanum_fraction": 0.6890072911, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6852186057616814}} {"text": "#' f_descent\n#'\n#' The descent algorithm using back tracking line search stepsize\n#'\n#' @param v_y vector of y\n#' @param v_x vector of x\n#' @param v_k0 vector of internal knots for covariates\n#' @param v_m vector of orders for covariates\n#'\n#' @param init initialization for $\\beta$\n#' @param alpha threshold $\\alpha$, within $(0, 0.5)$.\n#' @param bet shrinkage rate $\\bet$, within $(0, 1)$.\n#' @param v_smooth vector of smoothing parameters\n#' @param maxit maximum number of iterations\n#' @param eps stopping critria threshhold\n#' @param eta stopping criteria for gradient size\n#' @param trace indicator whether to plot trace\n#'\n#'\n#' @return the estimated $\\beta$\n#'\nf_descent <- function(v_y, v_x, v_k0, v_m, init = NULL,\n alpha = 0.3, bet = 0.5, v_smooth = rep(1, 3),\n maxit = 1e4, eps = 1e-3, eta = NULL, trace = NULL) {\n\n#-------------------------------------------------------\n##### set up #####\n#-------------------------------------------------------\n function_call <- match.call()\n x_ord <- order(v_x)\n v_x <- v_x[x_ord]\n v_y <- v_y[x_ord]\n s_center <- mean(v_x)\n s_sd <- sd(v_x)\n v_x <- c(scale(v_x))\n iter <- 0L\n converge <- F\n s_n <- length(v_y)\n #Define dimensions\n k1 <- v_k0[2]; ktau <- v_k0[1]; m1 <- v_m[2]; mtau <- v_m[1]\n v_dim <- v_k0 + v_m\n #Require\n m_n1 <- f_n1(v_x, k1, m1)\n m_g1 <- f_g1(ktau, mtau)\n m_g2 <- f_g2(ktau, mtau)\n m_sigmatau <- f_sigmatau(v_dim[1])\n m_sigma <- f_sigma(v_dim[1], v_dim[2])\n m_s <- f_mats(v_dim[1], v_dim[2], v_smooth)\n\n #Precalculate h1\n m_h1 <- f_h1(m_n1, m_g1, m_g2, m_sigmatau)\n\n #Initialization\n if (is.null(init)) {\n init <- f_init(v_y, v_x, m_sigma, m_n1, v_k0, v_m, m_s)\n }\n til_beta <- init\n v_beta <- og_beta(til_beta, v_dim[1], v_dim[2])\n v_grad <- 0\n\n #Calculate H2 (most time consuming)\n v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, ktau, mtau)\n m_ntaustar <- f_ntaustar(v_taustar, ktau, mtau)\n m_h2 <- f_h2(m_n1, m_ntaustar, m_g1, m_sigmatau)\n\n ##Loss\n s_loss <- f_criteria(v_beta, til_beta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n\n ##trace\n ##trace\n if (!is.null(trace)) {\n v_taus <- trace\n con_quan <- list(x = v_x, y = v_y, center = s_center, sd = s_sd,\n v_k0 = v_k0, v_m = v_m, m_sigma = m_sigma, n1 = m_n1,\n til_beta = til_beta)\n sub <- paste(\"Iter:\", iter, \", Error=\", round(s_loss, 3))\n main <- paste(\"alpha=\", alpha, \"beta=\", bet,\n \"Smoothing:\", v_smooth[1:2], \"dim:\", v_dim)\n cq_plot(trace, con_quan, sub = sub, main = main)\n }\n\n #Repeat\n while (maxit > iter) {\n iter <- iter + 1\n\n #Calculate gradient\n v_deriv <- f_lossderiv(til_beta, v_k0 + v_m, m_sigma, m_h1, m_h2) / s_n\n v_grad <- f_grad(v_beta, v_deriv, m_s)\n grad_size <- sum(v_grad ^ 2)\n\n #backtracking line search\n t <- 1\n repeat{\n new_beta <- v_beta - t * v_grad\n new_tilbeta <- tilde_beta(new_beta, v_dim[2])\n new_loss <- f_criteria(new_beta, new_tilbeta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n t <- bet * t\n if (new_loss <= (s_loss - alpha * t * grad_size) || t < 1e-4) {\n break\n }\n }\n\n #Update v_beta\n v_beta <- new_beta\n til_beta <- new_tilbeta\n\n #Update H2 (most time consuming)\n#ptm <- proc.time()# Start the clock!\n v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, ktau, mtau)\n#print(proc.time() - ptm)# Stop the clock\n m_ntaustar <- f_ntaustar(v_taustar, ktau, mtau)\n m_h2 <- f_h2(m_n1, m_ntaustar, m_g1, m_sigmatau)\n\n ##trace\n if (!is.null(trace)) {\n con_quan$til_beta <- til_beta\n sub <- paste(\"Iter:\", iter, \", Error=\", round(new_loss, 3))\n cq_plot(trace, con_quan, sub = sub, main = main)\n }\n\n #Check stop criterion\n if (is.null(eta)) {\n converge <- (abs(new_loss - s_loss) <= eps * abs(s_loss))\n } else {\n converge <- (sqrt(grad_size) / norm_2(v_beta) <= eta)\n }\n\n s_loss <- new_loss\n #If gradient size criteria\n if (is.na(converge)) {\n converge <- F\n break\n }\n if (converge) break\n }\n\n#-------------------------------------------------------\n##### Output #####\n#-------------------------------------------------------\n out <- list(\n beta = v_beta,\n til_beta = til_beta,\n gradient = v_grad,\n converge = converge,\n grad_size = sum(v_grad ^ 2),\n iter = iter,\n loss = s_loss,\n tau = v_taustar,\n x = v_x,\n y = v_y,\n center = s_center,\n sd = s_sd,\n v_k0 = v_k0,\n v_m = v_m,\n n1 = m_n1,\n m_sigma = m_sigma,\n mat_s = m_s,\n alpha = alpha,\n bet = bet,\n call = function_call)\n\n return(out)\n}", "meta": {"hexsha": "19e6ded177e23d951571af842547d881f27e01ce", "size": 5032, "ext": "r", "lang": "R", "max_stars_repo_path": "R/descent.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/descent.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/descent.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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.8711656442, "max_line_length": 99, "alphanum_fraction": 0.5202702703, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6851427988343667}} {"text": "# ===\n# R code used as basis for illustratig the CLT theorem and\n# construction of the confidence interval.\n# ===\n\n# ---\n# Load the libraries that we need. Indicate whether \"shiny\" is needed (probably not)\n# ---\n\nload_libraries <- function(withshiny = FALSE) {\n library(tidyverse) # Load the whole tidyverse (ggplot2, dplyr, purrr etc..)\n library(statsr) # Companion package for the Coursera \"Statistics with R\" specialization \n library(reshape2) # Provides \"reshape\" to \"melt\" a data frame\n if (withshiny) {\n library(shiny) # \"An R package to build interactive web apps straight from R.\", by RStudio. \n }\n library(testit) # For \"assert\": https://www.rdocumentation.org/packages/testit/versions/0.11\n # install.packages('testit')\n}\n\n# ---\n# Load the \"ames\" dataset and return the \"area\" information\n# ---\n\nload_dataset_ames_area <- function() {\n data(ames) \n # We are interested in the area of transacted property, in feet² \n ames_area <- select(ames,area)\n # \"ames_area\" is a tibble of 1 column named \"area\"\n # to rename column \"area\" to just \"x\" (one could also use dplyr's rename function)\n # names(ames_area)[names(ames_area) == \"area\"] <- \"x\"\n str(ames_area)\n return (ames_area)\n}\n\n# ---\n# Given a plot created by ggplot2, add vertical lines for certain statistics\n# ---\n\nadd_stats_vlines_to_plot <- function(stats, plot, add_median = TRUE) {\n\n stddev <- stats$stddev\n mean <- stats$mean\n median <- stats$median\n stddev_range_high <- stats$mean + stddev\n stddev_range_low <- stats$mean - stddev\n \n color_mean <- \"red\"\n color_stddev <- \"blue\"\n color_median <- \"orange\"\n \n # add a vertical line for \"mean\"\n \n x_where <- mean\n plot <- plot +\n geom_vline(xintercept=x_where, color=color_mean) +\n annotate(geom=\"text\", x=x_where, y=0, label=\"<>\", color=color_mean)\n \n # add a vertical line for \"median\"\n \n if (add_median) {\n x_where <- median\n plot <- plot + \n geom_vline(xintercept=x_where, color=color_median) +\n annotate(geom=\"text\", x=x_where, y=0, label=\"∇\", color=color_median) \n }\n\n # add a dashed vertical line for \"1-stddev range, low value\"\n\n x_where <- stddev_range_high\n plot <- plot + \n geom_vline(xintercept=x_where, color=color_stddev, linetype=\"dotdash\") + \n annotate(geom=\"text\", x=x_where, y=0, label=\"sd-\", color=color_stddev)\n\n # add a dashed vertical line for \"1-stddev range, high value\" \n \n x_where <- stddev_range_low\n plot <- plot + \n geom_vline(xintercept=x_where, color=color_stddev, linetype=\"dotdash\") + \n annotate(geom=\"text\", x=x_where, y=0, label=\"sd+\", color=color_stddev)\n\n return(plot) \n}\n\n# ---\n# Create a ggplot2 histogram of \"ames\" \"area\" values. This may be\n# over the whole population or just over a sample. Returns the plot.\n# ---\n\nplot_histogram_of_ames_area_data <- function(ames_area_data, binwidth, x_max, titlestr) {\n\n stats <- compute_ames_area_stats(ames_area_data)\n\n subtitlestr <-\n paste0(stats$num_obs, \" observations\",\n \", binwidth = \" , binwidth,\n \", min = \" , stats$min,\n \", max = \" , stats$max,\n \", mean = \" , round(stats$mean,1),\n \", median = \" , stats$median,\n \", stddev = \" , round(stats$stddev,1)) \n\n plot <-\n ggplot(ames_area_data) +\n coord_cartesian(xlim=c(0,x_max)) + \n geom_histogram(aes(x=area), binwidth=binwidth, color=\"grey\") +\n labs(x=\"property area (feet²)\", title=titlestr, subtitle=subtitlestr)\n\n stats_to_add <-\n setNames(as.list(c(stats$stddev,\n stats$mean,\n stats$median)), \n c(\"stddev\", \"mean\", \"median\"))\n \n plot <- add_stats_vlines_to_plot(stats_to_add, plot)\n\n return(plot)\n}\n\n# ---\n# Create a Probability Density Function for the \"ames\" \"area\" values. This may\n# be over the whole population or just over a sample.\n# \"Adjust\" gives the kernel width (measure of \"smoothness\")\n# ---\n\ncreate_pdf_for_ames_area_data <- function(ames_area_data, adjust) {\n density_obj = density(ames_area_data$area, adjust=adjust)\n # str(density_obj)\n pdf <- tibble(x=density_obj$x, y=density_obj$y)\n # str(pdf)\n return(pdf)\n}\n\n# ---\n# Create a ggplot2 graph of a Probability Density Function for the \"ames\" \"area\"\n# values. This may be over the whole population or just over a sample. Returns the plot\n# ---\n\nplot_pdf_of_ames_area_data <- function(ames_area_data, adjust, x_max, titlestr) {\n\n stats <- compute_ames_area_stats(ames_area_data)\n \n subtitlestr <-\n paste0(stats$num_obs, \" observations\",\n \", smoothing = \", adjust,\n \", min = \" , stats$min,\n \", max = \" , stats$max,\n \", mean = \" , round(stats$mean,1),\n \", median = \" , stats$median,\n \", stddev = \" , round(stats$stddev,1)) \n \n pdf <- create_pdf_for_ames_area_data(ames_area_data,adjust)\n\n plot <-\n ggplot(pdf) +\n coord_cartesian(xlim=c(0,x_max)) + \n geom_line(aes(x=x,y=y)) +\n labs(x=\"property area (feet²)\", y=\"dp/dx\", title=titlestr, subtitle=subtitlestr)\n\n stats_to_add <-\n setNames(as.list(c(stats$stddev,\n stats$mean,\n stats$median)), \n c(\"stddev\", \"mean\", \"median\"))\n \n plot <- add_stats_vlines_to_plot(stats_to_add, plot)\n\n return(plot)\n}\n\n# ---\n# Create a single sample by selecting observations at random\n# ---\n\ncreate_single_sample_of_ames_area_observations <- function(ames_area, sample_size) {\n # Use dplyr:sample_n\n # Resulting \"sample\" is a tibble \"sample_size x 1\", listing observations\n sample <- sample_n(ames_area, size=sample_size, replace=FALSE)\n # str(sample)\n return(sample)\n}\n\n# ---\n# Compute statistics of ames area data (either a sample or the whole set\n# of observations)\n# ---\n\ncompute_ames_area_stats <- function(ames_area_data) {\n\n # Use \"summarise\" from package \"dplyr\".\n # This creates a tibble of dimensions \"1 x 8\", with the columns having the\n # names given below.\n\n stats <- \n summarise(ames_area_data,\n mean = mean(area),\n median = median(area),\n stddev = sd(area),\n iqr = IQR(area),\n min = min(area),\n max = max(area),\n quart1 = quantile(area, 0.25), # first ¼-ile, 25th %-ile\n quart3 = quantile(area, 0.75)) # third ¼-ile, 75th %-ile\n\n stats <- add_column(stats, num_obs = nrow(ames_area_data))\n return(stats)\n\n}\n\n# ---\n# Create multiple samples (and then their sample stats) from the ames dataset\n# ---\n\ncreate_multiple_ames_area_sample_stats <- function(ames_area, sample_size, sample_count) {\n # message(\"Creating \", sample_count, \" samples of \", sample_size, \" individuals, and their corresponding sample statistics\")\n\n # Create empty list to store the \"sample_count\" sample statistics\n\n fillable_list <- rep(list(NA), sample_count)\n\n # This can probably be done in vector fashion instead of a loop...\n\n for(i in 1:sample_count) {\n # \"sample\" is a tibble \"sample_size x 1\", listing observations\n sample <- create_single_sample_of_ames_area_observations(ames_area, sample_size) \n # \"sample_stats\" is a tibble \"1 x 9\", with columns \"mean\", \"median\", \"stddev\", ...\n sample_stats <- compute_ames_area_stats(sample)\n # str(sample_stats)\n fillable_list[[i]] <- sample_stats\n }\n\n # Not sure why the next instruction works but it does!\n # The result is a tibble with \"sample_size x 9\", with columns \"mean\", \"median\", \"stddev\", ...\n\n multiple_sample_stats <- do.call(rbind.data.frame, fillable_list)\n return(multiple_sample_stats)\n}\n\n\n# ---\n# Compute the sampling stats (mean of sample means) from the collection of sample stats (sample means etc.)\n# ---\n\ncompute_sampling_stats_for_mean <- function(multiple_sample_stats) {\n\n # Use \"summarise\" from package \"dplyr\".\n # This creates a tibble of dimensions \"1 x 5\", with the columns having the\n # names given below.\n\n stats <- \n summarise(multiple_sample_stats,\n mean = mean(multiple_sample_stats$mean),\n median = median(multiple_sample_stats$mean),\n stddev = sd(multiple_sample_stats$mean),\n min = min(multiple_sample_stats$mean),\n max = max(multiple_sample_stats$mean))\n\n stats <- add_column(stats, sample_count = nrow(multiple_sample_stats))\n stats <- add_column(stats, sample_size = mean(multiple_sample_stats$num_obs)) # constant over samples\n \n return(stats)\n}\n\n# ---\n# Create a ggplot2 histogram of the \"mean\" sample statistics (over the samples). Returns the plot.\n# ---\n\nplot_histogram_of_ames_area_sample_stats_for_mean <- function(multiple_sample_stats, binwidth, mean_min, mean_max) {\n\n sampling_stats <- compute_sampling_stats_for_mean(multiple_sample_stats)\n\n titlestr <- \"Histogram of mean of property area over samples of property transactions made in Ames, Iowa, 2006-2010\"\n\n subtitlestr <-\n paste0(sampling_stats$sample_count, \" samples of \",\n sampling_stats$sample_size, \" observations \",\n \", binwidth = \" , binwidth,\n \", min = \" , round(sampling_stats$min,1),\n \", max = \" , round(sampling_stats$max,1),\n \", mean = \" , round(sampling_stats$mean,1),\n \", stddev = \" , round(sampling_stats$stddev,2),\n \"\\nOverlaid: limit Gaussian postulated by CLT (scaled)\")\n\n plot <-\n ggplot(multiple_sample_stats) +\n coord_cartesian(xlim=c(mean_min,mean_max)) + \n geom_histogram(aes(x=mean), binwidth=binwidth, color=\"grey\") +\n labs(x=\"mean of property area over a single sample (feet²)\", title=titlestr, subtitle=subtitlestr)\n\n stats_to_add <-\n setNames(as.list(c(sampling_stats$stddev,\n sampling_stats$mean,\n sampling_stats$median)), \n c(\"stddev\", \"mean\", \"median\"))\n \n plot <- add_stats_vlines_to_plot(stats_to_add, plot, add_median = FALSE)\n\n return(plot)\n}\n\n# ---\n# Overlay the Normal to which the histogram should converge according to the CLT\n# ---\n\noverlay_clt_normal <- function(plot, binwidth, mean_min, mean_max, population_mean, population_stddev, sample_size, sample_count) {\n num_points <- 200\n x <- seq(mean_min, mean_max, (mean_max-mean_min)/(num_points-1)) \n stretch <- sample_count*binwidth # stretch the small Normal curve to the same dimension as the histogram\n y <- dnorm(x, mean=population_mean, sd=population_stddev/sqrt(sample_size))*stretch\n normal = tibble(x,y)\n plot <- plot + geom_line(data = normal, aes(x=x,y=y))\n return(plot)\n}\n\n# ---\n# Compute a confidence interval then add its lower and upper limit to the \"sample_stat\", which is returned\n# ---\n\nadd_confidence_interval <- function(sample_stats, confidence, verbose) {\n zscore = -qnorm((1.0-confidence)/2) # positive surface in tail of the Gaussian (one side)\n sample_size = sample_stats$num_obs\n standard_error = sample_stats$stddev / sqrt(sample_size)\n margin_of_error = zscore*standard_error\n conf_interval_low = sample_stats$mean - margin_of_error\n conf_interval_high = sample_stats$mean + margin_of_error\n if (verbose) {\n message(\"The confidence interval at \" \n ,(confidence*100)\n ,\"% is [\"\n ,conf_interval_low\n ,\",\"\n ,conf_interval_high\n ,\"]\")\n }\n res <- add_column(sample_stats\n ,conf_interval_low = conf_interval_low\n ,conf_interval_high = conf_interval_high)\n return(res)\n}\n\n# ---\n# Return TRUE if the population mean is indeed within the confidence interval\n# ---\n\ncheck_confidence_interval <- function(ames_area, population_mean, sample_size, confidence) { \n # create a single sample and compute its statistics \n # \"sample_stats\" is a tibble of 9x1 observations with variables \"mean\", \"median, \"stddev\" etc..\n sample_stats <- create_multiple_ames_area_sample_stats(ames_area,\n sample_size=sample_size,\n sample_count=1)\n # extend the \"sample_stats\" tibble with information about the confidence interval\n sample_stats <- add_confidence_interval(sample_stats, confidence, verbose=FALSE)\n # str(sample_stats)\n # return TRUE if the population mean is indeed within the confidence interval\n return(sample_stats$conf_interval_low < population_mean && population_mean < sample_stats$conf_interval_high)\n}\n\n", "meta": {"hexsha": "47d5d35940f7798ffb19ea634dcfe6ea00f76bcd", "size": 12796, "ext": "r", "lang": "R", "max_stars_repo_path": "confidence_interval/code/confidence_interval_base.r", "max_stars_repo_name": "dtonhofer/rstudio_coding", "max_stars_repo_head_hexsha": "01b8ab8f2630ab7686729d7e4a30c3d86724f2b7", "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": "confidence_interval/code/confidence_interval_base.r", "max_issues_repo_name": "dtonhofer/rstudio_coding", "max_issues_repo_head_hexsha": "01b8ab8f2630ab7686729d7e4a30c3d86724f2b7", "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": "confidence_interval/code/confidence_interval_base.r", "max_forks_repo_name": "dtonhofer/rstudio_coding", "max_forks_repo_head_hexsha": "01b8ab8f2630ab7686729d7e4a30c3d86724f2b7", "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": 35.7430167598, "max_line_length": 131, "alphanum_fraction": 0.641216005, "num_tokens": 3190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.6850073786621765}} {"text": "############################################################################\n# Marek Opuszko\n# Analytics of the COVID-19 (Corona) Spread\n############################################################################\n\n\n#\n# In order to easily model the whole thing, the data is logarithmized so \n# that we can then use a simple linear regression. Building on this, \n# we can then make forecasts for the next few days\nlibrary(tidyr)\nlibrary(data.table)\nlibrary(ggplot2)\nrequire(scales)\nlibrary(ggsci)\nlibrary(ggdark)\n\n\n###################################################################################################\n# 1. PREPROCESSING - DATA PREPARATION\n###################################################################################################\n\n# Define Working Directory\nsetwd(\"~/yourdirectoryhere\")\n\nsubject = \"Deaths\" # or \"Deaths\" or \"Recovered Cases\"\n\n# Load the Dataset \nif (subject==\"Cases\") {\n data = read.csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\")\n}else if(subject == \"Deaths\") {\n data = read.csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv\")\n}else if(subject == \"Recovered Cases\") {\n data = read.csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv\")\n}\n\n# The dataset needs some adjustments. Clearing data types:\ndata$Province.State = as.character(data$Province.State)\ndata$Country.Region = as.character(data$Country.Region)\n\n#We can remove lat and long since we are not using this geo information here\ndata$Lat <- NULL\ndata$Long <- NULL\n# check the data frame\nstr(data)\n\n# We need to change the format of the data frame, from wide (columns) to long\n# meaning we want a \"date\" and a \"cases\" variable instead of multiple columns for each date\n# This is necesary to make use of the data for later functions and plotting\n\n# using the melt function to transpose the data frame (needs prior transformation to data table format)\ndata_transformed <- melt(as.data.table(data), id=c(\"Province.State\",\"Country.Region\"), fun=\"Sum\")\n# change the variable names to something more \"speaking\"\nnames(data_transformed) <- c(\"region\",\"country\",\"date\",\"cases\")\n# remove the X invoked by R (no variable names beginning with a number allowed)\ndata_transformed$date <- gsub(\"X\", \"0\", paste(data_transformed$date))\n# transform character dates to actual date format\ndata_transformed$date <- as.Date(data_transformed$date, \"%m.%d.%Y\")\n# This is optional, save the new formatted data frame\nwrite.csv(data_transformed,paste0(\"covid_19_data_\",subject,\"_confirmed.csv\"),row.names=FALSE)\n\n\n###################################################################################################\n# 2. ANALYTICS\n# 2.1 World wide Trend\n###################################################################################################\n\n# Aggregate all cases by date -> overall sum over all countries for on date\ndata_subset <- aggregate(cases ~ date , data = data_transformed, sum)\n# Aggregated Cases by Date and by Country\ndata_subset_countries <- aggregate(cases ~ country + date , data = data_transformed, sum)\n\n# First Impressions - Plot\nplot(data_subset$cases ~ data_subset$date)\n# We see a string exponential development from mid of march ...\n# logarithmize the cases to linearize expoential growth\nplot(log(data_subset$cases) ~ data_subset$date)\n\n# In order to make predictions we will simplify the model and use a simple linear\n# regression model for the timespan the cases grow exponentially\n\nlastDay <- max(data_subset$date)\n# let's use the last two weeks ... \ndata_model <- data_subset[data_subset$date >= lastDay-21,]\n# check plot ...\nplot(log(data_model$cases) ~ data_model$date)\n\n# To understand the regression, it's better to use Day Numbers\n# so we can ask later on, what will today plus 7 days look like?\ndata_model$daynr = seq(1,length(data_model$cases))\n# logarithmize the cases to apply linear regression\ndata_model$casesLog = log(data_model$cases)\n\n# Check the plot ... looks \"linear\" ?\nplot(data_model$casesLog ~ data_model$date)\n\n# Run a simple linear regression\nmodel <- lm(data_model$casesLog ~ data_model$daynr)\n# extract Coefficients\na = as.numeric(model$coefficients[1])\nb = as.numeric(model$coefficients[2])\n\n\n###################################################################################################\n# 2.2 Predictions ... the whole world\n###################################################################################################\n# Function to predict cases based on our simple model\npredict <- function(day,a,b){\n cases = a + b*day\n return(cases)\n}\n\n# Since the model is based an logarithmic values <- reverse operation of the values\npredict_cases <- function(day,a,b) {\n result = exp(predict(day,a,b))\n return(result)\n}\n\ntoday = length(data_model$daynr)\n\n# Prediction of our model for today (31st of March as i'm writing this)\npredict_cases(today,a,b)\n# 800,000 vs 780,000 ... not bad ..\n\n# Prediction of our model for tomorrow\npredict_cases(today+1,a,b)\n# Prediction of our model for one week into the future\npredict_cases(today+7,a,b)\n# 1,69 Million cases 7th of April :/\n\n# Prediction of our model for two weeks into the future\npredict_cases(today+14,a,b)\n\n\n# Plot the model timespan\ndateMin = min(data_model$date)\ndateMax = max(data_model$date) + 7\nggplot(data_model, aes(x=date,y=cases)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7,color=\"white\") + \n geom_point(aes(y=cases),alpha=0.5,color=\"grey\") + \n scale_y_log10(labels = scales::comma) + \n geom_smooth(method = lm, fullrange=TRUE, color=\"red\") +\n ggtitle(paste0(\"Worldwide COVID-19 \",subject,\" over Time\")) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n xlim(dateMin, dateMax) +\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n\n# Plot the whole date span\nggplot(data_subset, aes(x=date,y=cases)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7,color=\"white\") + \n geom_point(aes(y=cases),alpha=0.5,color=\"grey\") + \n scale_y_log10(labels = scales::comma) + \n geom_smooth(method = loess, fullrange=TRUE, color=\"red\") +\n ggtitle(paste0(\"Worldwide COVID-19 \",subject)) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n\n\n\n###################################################################################################\n# 2.3 Predictions ... Single Countries or Regions\n###################################################################################################\n\n###################################################################################################\n# US \n###################################################################################################\nneedle = c(\"US\")\n\n# Subset by Country list\ndata_subset_US = data_subset_countries[which(data_subset_countries$country %in% needle),]\n\n# first impressions\nplot(log(data_subset_US$cases) ~ data_subset_US$date)\n# exponential growth since beginning of march \ndata_model_US <- data_subset_US[data_subset_US$date >= lastDay-14,]\nplot(log(data_model_US$cases) ~ data_model_US$date)\n\n# create Day Nr\ndata_model_US$daynr = seq(1,length(data_model_US$cases))\n# logarithmize\ndata_model_US$casesLog = log(data_model_US$cases)\n\n\n# Regression\nmodel_US <- lm(data_model_US$casesLog ~ data_model_US$daynr)\n# extract coefficients\na = as.numeric(model_US$coefficients[1])\nb = as.numeric(model_US$coefficients[2])\n\ntoday = length(data_model_US$daynr)\n\n# Prediction of our model for today, tomorrow, etc (31st of March as i'm writing this)\npredict_cases(today,a,b)\npredict_cases(today+1,a,b)\npredict_cases(today+7,a,b)\npredict_cases(today+14,a,b)\n\n\n# Plot the model timespan\ndateMin = min(data_model_US$date)\ndateMax = max(data_model_US$date) + 7\nggplot(data_model_US, aes(x=date,y=cases)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7,color=\"white\") + \n geom_point(aes(y=cases),alpha=0.5,color=\"grey\") + \n scale_y_log10(labels = scales::comma) + \n geom_smooth(method = lm, fullrange=TRUE, color=\"red\") +\n ggtitle(paste0(\"US COVID-19 \",subject,\" over Time\")) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n xlim(dateMin, dateMax) +\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n\n# Plot the whole date span\nggplot(data_subset_US, aes(x=date,y=cases)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7,color=\"white\") + \n geom_point(aes(y=cases),alpha=0.5,color=\"grey\") + \n scale_y_log10(labels = scales::comma) + \n geom_smooth(method = loess, fullrange=TRUE, se=FALSE, color=\"red\") +\n ggtitle(paste0(\"US COVID-19 \",subject)) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n\n##############################################################################################\n# what About the daily increase/change?\n# Lazy Approach: Calculate the daily cases based on the subtraction today and yesterday\n# Works only for single cases, not if you have groups !!!\n##############################################################################################\nyesterday = c(data_subset_US$cases[1],data_subset_US$cases[1:length(data_subset_US$cases)-1])\ndata_subset_US$newInfects = data_subset_US$cases - yesterday\n\nggplot(data_subset_US, aes(x=date,y=newInfects,colour=country)) + \n geom_line(aes(y=newInfects),size=1.1,alpha=0.7) + \n geom_point(aes(y=newInfects),alpha=0.5) + \n geom_smooth(method = loess, aes(color=country),color=\"white\") +\n ggtitle(paste0(\"Daily COVID-19 \",subject,\" in the US\")) + xlab(\"Date\") + \n ylab(\"Daily Increase\")+\n xlim(dateMin, dateMax) +\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=30,color=\"orange\")) \n\n#############################################################################################\n\n\n\n###################################################################################################\n# Top 6 Countries in Case Numbers \n###################################################################################################\nneedle = c(\"China\",\"US\",\"Italy\",\"Germany\",\"Spain\",\"Iran\")\n\n# Subset by Country list\ndata_subset_top6 = data_subset_countries[which(data_subset_countries$country %in% needle),]\n# Plot - log scales\nggplot(data_subset_top6, aes(x=date,y=cases,color=country)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7) + \n geom_point(aes(y=cases),alpha=0.5) + \n scale_y_log10(labels = scales::comma) + \n ggtitle(paste0(\"COVID-19 \",subject,\" over Time\")) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n# Plot - normal scales\nggplot(data_subset_top6, aes(x=date,y=cases,color=country)) + \n geom_line(aes(y=cases),size=1.1,alpha=0.7) + \n geom_point(aes(y=cases),alpha=0.5) + \n ggtitle(paste0(\"COVID-19 \",subject,\" over Time\")) + xlab(\"Date\") + \n ylab(\"Number (log)\")+\n scale_color_nejm() + \n dark_theme_gray() +\n theme(axis.text.x = element_text(size = 15)) +\n theme(axis.text.y = element_text(size = 12)) +\n theme(plot.title = element_text(size=20,color=\"orange\")) \n\n#############################################################################################\n", "meta": {"hexsha": "983bc03a7341746064fb5c6acef5e65db7a18b7f", "size": 12049, "ext": "r", "lang": "R", "max_stars_repo_path": "COVID-19_Analytics.r", "max_stars_repo_name": "Wirtschaftsinformatik/COVID-19", "max_stars_repo_head_hexsha": "9120b6ddcda47aabb61a099cf34082cf944e8eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-01T06:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T06:44:44.000Z", "max_issues_repo_path": "COVID-19_Analytics.r", "max_issues_repo_name": "Wirtschaftsinformatik/COVID-19", "max_issues_repo_head_hexsha": "9120b6ddcda47aabb61a099cf34082cf944e8eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-22T12:11:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T12:11:45.000Z", "max_forks_repo_path": "COVID-19_Analytics.r", "max_forks_repo_name": "Wirtschaftsinformatik/COVID-19", "max_forks_repo_head_hexsha": "9120b6ddcda47aabb61a099cf34082cf944e8eb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-22T12:10:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:09:56.000Z", "avg_line_length": 40.8440677966, "max_line_length": 171, "alphanum_fraction": 0.624284173, "num_tokens": 2932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6849885764826613}} {"text": "# ......................................................................................\n# ..............................Cvičení 2 - Pravděpodobnost.............................\n# ..................Adéla Vrtková, Michal Béreš, Martina Litschmannová .................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# V tomto cvičení projdeme úvod do pravděpodobnosti. Předpokládáme znalosti z přednášky,\n# především pojmy: **definice pravděpodobnosti, podmíněná pravděpodobnost, věta o úplné\n# pravděpodobnosti, Bayesova věta**.\n# \n# Pomocné funkce ####\n# \n# * Úplná pravděpodobnost ####\n# $P(A)=\\sum_{i=1}^{n}P(B_i)P(A|B_i)$\n\n\n# spočítání pravděpodobnosti P(A) - věta o úplné pravděpodobnosti\nuplna_pravdepodobnost = function(P_B, P_AB)\n{ # uvažujeme P_B jako vektor hodnot P(B_i) a P_BA jako vektor hodnot P(A|B_i)\n P_A = 0\n for (i in 1:length(P_B))\n {\n P_A = P_A + P_B[i]*P_AB[i]\n }\n return(P_A)\n}\n\n# * Bayesova věta ####\n# $P(B_k|A)=\\frac{P(B_k)P(A|B_k)}{\\sum_{i=1}^{n}P(B_i)P(A|B_i)}$\n\n\n# spočítání podmíněné pravděpodobnosti P(B_k|A) - Bayesova věta\nbayes = function(P_B, P_AB, k)\n{ # uvažujeme P_B jako vektor hodnot P(B_i), P_BA jako vektor hodnot P(A|B_i)\n P_A = uplna_pravdepodobnost(P_B, P_AB)\n P_BkA = P_B[k]*P_AB[k]/P_A\n return(P_BkA)\n} \n\n# **Přidáme funkce z munulého cvičení pro počítání kombinatorických výběrů, jsou v\n# skriptu kombinatorika.R**\n\n\nsource('kombinatorika.R')\n\n# Příklady ####\n# * Příklad 1. ####\n# Určete pravděpodobnost, že při hodu 20stěnnou spravedlivou (férovou) kostkou padne\n# číslo větší než 14.\n\n\nomega = 1:20\nA = c(15,16,17,18,19,20)\n# pravděpodobnost jako podíl příznivých ku všem \nlength(A)/length(omega)\n\n# * Příklad 2. ####\n# Určete pravděpodobnost, že při hodu 20stěnnou kostkou padne číslo větší než 14,\n# víte-li, že sudá čísla padají 2x častěji než lichá.\n\n\np_liche = 1/(20+10)\np_sude = 2*p_liche\npravd = c(p_liche, p_sude, p_liche, p_sude, p_liche, p_sude, p_liche, p_sude, \n p_liche, p_sude, p_liche, p_sude, p_liche, p_sude, p_liche, p_sude, \n p_liche, p_sude, p_liche, p_sude)\npravd\n#pravdepodobnost je\nsum(pravd[15:20])\n\n# * Příklad 3. ####\n# Určete pravděpodobnost, že ve sportce uhodnete 4 čísla. (Ve sportce se losuje 6 čísel\n# ze 49.)\n\n\n(kombinace(6,4)*kombinace(43,2))/kombinace(49,6)\n\n# * Příklad 4. ####\n# Z abecedního seznamu studentů zapsaných na dané cvičení vybere učitel prvních 12 a\n# nabídne jim sázku: „Pokud se každý z Vás narodil v jiném znamení zvěrokruhu, dám\n# každému z Vás 100 Kč. Pokud jsou však mezi Vámi alespoň dva studenti, kteří se\n# narodili ve stejném znamení, dá mi každý z Vás 100 Kč.“ Vyplatí se studentům sázku\n# přijmout? S jakou pravděpodobností studenti vyhrají?\n\n\npermutace(12)/variace_opak(12,12)\n\n# * Příklad 5. ####\n# Spočtěte pravděpodobnost toho, že z bodu 1 do bodu 2 bude protékat elektrický proud,\n# je-li část el. obvodu včetně pravděpodobnosti poruch jednotlivých součástek vyznačen\n# na následujícím obrázku. (Poruchy jednotlivých součástek jsou na sobě nezávislé.)\n# Obrázek viz sbírka úloh.\n\n\n# rozdělíme na bloky I=(A,B) a II=(C,D,E)\nPI = 1 - (1 - 0.1)*(1 - 0.3)\nPI\nPII = 0.2*0.3*0.2\nPII\n# výsledek\n(1 - PI)*(1-PII)\n\n# * Příklad 6. ####\n# Ohrada má obdélníkový tvar, východní a západní stěna mají délku 40 m, jižní a severní\n# pak 100 m. V této ohradě běhá kůň. Jaká je pravděpodobnost, že je k jižní stěně blíž\n# než ke zbývajícím třem?\n\n\n# geometrická pravděpodobnost\nohrada = 40*100\n#blize k jihu\nblize_J = 20*60 + 20*20\n#pravdepodobnosti\nblize_J/ohrada\n\n# * Příklad 7. ####\n# U pacienta je podezření na jednu ze čtyř vzájemně se vylučujících nemocí - N1, N2, N3,\n# N4 s pravděpodobností výskytu P(N1)=0,1; P(N2)=0,2; P(N3)=0,4; P(N4)=0,3. Laboratorní\n# zkouška A je pozitivní v případě první nemoci v 50 % případů, u druhé nemoci v 75 %\n# případů, u třetí nemoci v 15 % případů a u čtvrté v 20 % případů. Jaká je\n# pravděpodobnost, že výsledek laboratorní zkoušky bude pozitivní?\n\n\n# věta o úplné pravděpodobnosti\nP_N = c(0.1,0.2,0.4,0.3) # P(N1), P(N2), ...\nP_PN = c(0.5,0.75,0.15,0.2) # P(P|N1), P(P|N2), ... \nP_P = uplna_pravdepodobnost(P_B = P_N, P_AB = P_PN) # P(P)\nP_P\n\n# * Příklad 8. ####\n# Telegrafické znaky se skládají ze signálů „tečka“, „čárka“. Je statisticky zjištěno,\n# že se zkomolí 25 % sdělení „tečka“ a 20 % signálů „čárka“. Dále je známo, že signály\n# se používají v poměru 3:2. Určete pravděpodobnost, že byl přijat správně signál,\n# jestliže byl přijat signál „tečka“.\n\n\n# Bayesova věta\nP_O = c(0.6, 0.4) # P(O.), P(O-)\nP_PO = c(0.75, 0.2) # P(P.|O.), P(P.|O-)\nbayes(P_B = P_O, P_AB = P_PO, k = 1) # k = 1 protože správně = O.\n\n# * Příklad 9. ####\n# V jednom městě jezdí 85 % zelených taxíků a 15 % modrých. Svědek dopravní nehody\n# vypověděl, že nehodu zavinil řidič modrého taxíku, který pak ujel. Testy provedené za\n# obdobných světelných podmínek ukázaly, že svědek dobře identifikuje barvu taxíku v 80\n# % případů a ve 20 % případů se mýlí.\n# - Jaká je pravděpodobnost, že viník nehody skutečně řídil modrý taxík?\n# - Následně byl nalezen další nezávislý svědek, který rovněž tvrdí, že taxík byl\n# modrý. Jaká je nyní pravděpodobnost, že viník nehody skutečně řídil modrý taxík?\n# - Ovlivní pravděpodobnost, že viník nehody skutečně řídil modrý taxík to, zda dva\n# výše\n# zmínění svědci vypovídali postupně nebo najednou?\n\n\n# a) opět Bayesova věta\nP_B = c(0.85, 0.15) # P(Z), P(M) \nP_SB = c(0.20, 0.80) # P(SM|Z), P(SM|M) \nbayes(P_B = P_B, P_AB = P_SB, k = 2) # modrý je druhý\n\n# b) první možnost - druhý průchod Bayesem\nP_M = bayes(P_B = P_B, P_AB = P_SB, k = 2)\nP_B = c(1 - P_M, P_M) # P(Z), P(M) \nP_SB = c(0.20, 0.80) # P(S2M|Z), P(S2M|M) \nbayes(P_B = P_B, P_AB = P_SB, k = 2)\n\n# c) nebo odpověděli najednou \nP_B = c(0.85, 0.15) # P(Z), P(M) \nP_SB = c(0.20^2, 0.80^2) # P(S1M&S2M|Z), P(S1M&S2M|M) \nbayes(P_B = P_B, P_AB = P_SB, k = 2)\n\n# * Příklad 10. ####\n# Potřebujeme zjistit odpověď na určitou citlivou otázku. Jak odhadnout, kolik procent\n# dotazovaných na otázku odpoví ANO a přitom všem respondentům zaručit naprostou\n# anonymitu? Jedním z řešení je tzv. dvojitě anonymní anketa:\n# Necháme respondenty hodit korunou a dvojkorunou a ti, kterým padl na koruně líc\n# napíšou na lísteček odpověď (ANO/NE) na citlivou otázku. Ostatní respondenti napíší,\n# zda jim padl na dvojkoruně líc (ANO/NE). Jakým způsobem určíme podíl studentů, kteří\n# na citlivou otázku odpověděli ANO?\n# Předpokládejme, že respondenti byli dotazování, zda podváděli u zkoušky. Z anketních\n# lístků se zjistilo, že „ANO“ odpovědělo 120 respondentů a „NE“ odpovědělo 200\n# respondentů. Kolik procent studentů podvádělo u zkoušky?\n\n\n# věta o úplné pravděpodobnosti \n# P(A) = P(K_lic)*P(A|K_lic)+P(K_rub)*P(D_lic|K_rub)\n# rovnice 120/320=0.5*x+0.5*0.5\n(120/320-0.5^2)/0.5\n\n# * Bonus - Monty Hall Problem ####\n# \n# Začneme s vygenerováním n instancí soutěže - cena bude náhodný index dveří (1,2,3) za\n# kterými se může nacházet cena\n\n\nn = 10000 # počet pokusů\ncena = sample.int(n = 3, size = n, replace = TRUE) # náhdný výběr dveří\nhead(cena) # head vykresli prvních 6 prvků/řádků\n\n# Totéž pro naši původní volbu - náhodný index dveří.\n\n\nvolba_orig = sample.int(n = 3, size = n, replace = TRUE) # původní volba\nhead(volba_orig)\n\n# V prvním kole moderátor jedny prázdné dveře otevře, takto se to dá nasimulovat:\n\n\notevrene_dvere = rep(0, n) # inicializace vektoru\ndvere_c = 1:3 # pomocná proměnná - identifikátory dveří\nfor (i in 1:n){\n dvere_k_otevereni = c(TRUE, TRUE, TRUE) # inicializace \n dvere_k_otevereni[cena[i]] = FALSE # nesmíme otevřít dveře s cenou\n dvere_k_otevereni[volba_orig[i]] = FALSE # ani naše vybrané dveře\n # ve zbytku jsou buď 2 (pokud jsme se trefili) nebo 1 dveře (pokud ne)\n idx_dvere = dvere_c[dvere_k_otevereni]\n if (length(idx_dvere) == 1){\n otevrene_dvere[i] = idx_dvere # pokud jedny otevřeme je\n } else { # pokud 2 tak jedny náhodně vybereme a otevřeme je\n otevrene_dvere[i] = sample(x = idx_dvere, size = 1)\n }\n}\nhead(otevrene_dvere)\n\n# Naše nová volba pokud se tak rozhodneme - součet indexů je 1+2+3=6 takže pokud my máme\n# vybraný nějaký index, dále nějaký index se otevře, tak do zbytku 6 jsou ty třetí =\n# naše nová volba.\n\n\nnova_volba = 6 - (volba_orig + otevrene_dvere)\nhead(nova_volba)\n\n# Úspěšnost při originální volbě:\n\n\np_orig = sum(cena == volba_orig)/n\np_orig\n\n# Úspěšnost při výměně:\n\n\np_zmena = sum(cena == nova_volba)/n\np_zmena\n\np_orig + p_zmena\n\n\n\n", "meta": {"hexsha": "f0f1af4c14ac70cc4e5e2294a2d60634ff0feab5", "size": 8704, "ext": "r", "lang": "R", "max_stars_repo_path": "CV2/cv2.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV2/cv2.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV2/cv2.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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.6772908367, "max_line_length": 88, "alphanum_fraction": 0.6784237132, "num_tokens": 4035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6847610359815757}} {"text": "#!/usr/bin/env Rscript\n\nnumsteps <- 10000000\n\nargs <- commandArgs(trailingOnly=TRUE)\n\nif (length(args)>0) {\n numsteps <- strtoi(args)\n}\n\ncat(\"Calculating PI using:\\n \", numsteps, \"slices \\n\")\ncat(\" 1 process\\n\")\n\nstart <- Sys.time()\n\nsum <- 0.0\nstep <- 1.0/numsteps\n\nfor (i in 1:numsteps) {\n x <- (i - 0.5) * step\n sum <- sum + 4.0/(1.0 + (x^2))\n}\n\nmypi = sum * step\n\nstop <- Sys.time()\nelapsed <- stop - start\n\ncat(\"Obtained value of PI:\", mypi, \"\\n\")\ncat(\"Time taken:\", elapsed, \"seconds\\n\")\n", "meta": {"hexsha": "76d03d1de7d2a606c14fff1abfb6d829c945a836", "size": 498, "ext": "r", "lang": "R", "max_stars_repo_path": "r_pi_dir/pi.r", "max_stars_repo_name": "adrianjhpc/pi_examples", "max_stars_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-04-13T11:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:22:06.000Z", "max_issues_repo_path": "r_pi_dir/pi.r", "max_issues_repo_name": "adrianjhpc/pi_examples", "max_issues_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-05-24T11:28:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T16:22:17.000Z", "max_forks_repo_path": "r_pi_dir/pi.r", "max_forks_repo_name": "adrianjhpc/pi_examples", "max_forks_repo_head_hexsha": "ba624038a865e194b361d783a0e8647f2a9bb376", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-12T15:08:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T09:35:21.000Z", "avg_line_length": 16.064516129, "max_line_length": 54, "alphanum_fraction": 0.6004016064, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6842661743188686}} {"text": "\nNCPgen <- function(q,R,K,CaseN,ConN) {\n # q is the AF\n # R is the RR\n \n p <- 1-q;\n \n p_d_aa <- K / (p*p + 2*p*q*R + q*q*R*R);\n p_d_ab <- p_d_aa * R;\n p_d_bb <- p_d_aa * R * R;\n \n p_aa_d <- p_d_aa * p * p/ K ;\n p_ab_d <- p_d_ab * p * q * 2 / K ;\n p_bb_d <- p_d_bb * q * q/ K ;\n \n p_aa_u <- (p*p - K * p_aa_d) / (1-K) ;\n p_ab_u <- (2*p*q - K * p_ab_d) / (1-K) ; \n p_bb_u <- (q*q - K * p_bb_d) / (1-K)\t;\n \n p_case <- p_aa_d + 0.5*p_ab_d;\n p_con <- p_aa_u + 0.5*p_ab_u;\n q_case <- 1 - p_case ;\n q_con <- 1 - p_con ;\n \n# NCP <- chisq.test(matrix(c(2*p_case*CaseN,2*p_con*ConN,2*q_case*CaseN,2*q_con*ConN),2,2),correct=F);\n \n summary(as.table(matrix(c(2*p_case*CaseN,2*p_con*ConN,2*q_case*CaseN,2*q_con*ConN),2,2)))$statistic;\n \n}\n\ndenovoGen <- function(R, q,f,CaseN,ConN) {\n\n # q is number of de novo mutations \n # R is the relative risk of having a variant\n # CaseN is the number of cases - N*r/(1+r)\n # CaseN is the number of controls - N/(1+r)\n MutCases = rpois(CaseN, q * 1* (1-f) ) + rpois(CaseN, q * R * f )\n MutCon = rpois(ConN, q * 1)\n \n m <- glm(c(MutCases, MutCon)~ c(rep(1, CaseN), rep(0, ConN)), family=\"poisson\")\n -(m$deviance-m$null.deviance)\n\n}\n\ndenovoGenPower <- function(R, q,f,CaseN,ConN, p_cut_denovo) {\n \n pchisq(qchisq(p_cut_denovo, 1, low=F), 1, ncp=denovoGen(R, q,f,CaseN,ConN), low=F)\n \n}\n\ngetSingleVarPower <- function(f, AF, R, K, N, r, P_cut_single){\n chi <- unlist(lapply(AF[1:f], function(i){ NCPgen(i,R,K,N*r/(1+r),N/(1+r)) })) \n power_snp <- pchisq(qchisq(P_cut_single, 1, low=F), 1, ncp=chi, low=F)\n ret <- 1-prod(1-power_snp) \n ret\n}\n\ngetBurdenPower <- function(f, AF, sum_var, R, K, N, r, p_cut_burden){\n \n ratio <- sum(AF[1:f] * (1-AF[1:f]) ) / sum_var\n chi <- NCPgen(sum(AF) , exp(log(R)*ratio), K, N*r/(1+r),N/(1+r))\n pchisq(qchisq(p_cut_burden, 1, low=F), 1, ncp=chi , low=F) \n}\n\ngetDenovoPower_parametric <- function(rr, q,f, N, r, p_cut_denovo){\n\n MutCases <- N*r/(1+r)\n MutCon <- N/(1+r)\n x1 <- q * 1* (1-f) + q * rr * f\n x0 <- q * 1\n chi <- (x1-x0)^2/(x1/MutCases+x0/MutCon)\n power <- pchisq(qchisq(p_cut_denovo, 1, low=F), 1, ncp=chi, low=F)\n power\n}\n", "meta": {"hexsha": "93766c8212383beca6db3fd36f21899125f7f701", "size": 2167, "ext": "r", "lang": "R", "max_stars_repo_path": "helper.r", "max_stars_repo_name": "hailianghuang/BurdenPower", "max_stars_repo_head_hexsha": "34d86bf097988ef622a6ec1fad2108b7e6b83c6c", "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": "helper.r", "max_issues_repo_name": "hailianghuang/BurdenPower", "max_issues_repo_head_hexsha": "34d86bf097988ef622a6ec1fad2108b7e6b83c6c", "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": "helper.r", "max_forks_repo_name": "hailianghuang/BurdenPower", "max_forks_repo_head_hexsha": "34d86bf097988ef622a6ec1fad2108b7e6b83c6c", "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": 28.8933333333, "max_line_length": 103, "alphanum_fraction": 0.5712967236, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6840260882219988}} {"text": "Full_Data<-structure(list(item = c(\"map\", \"compass\", \"water\", \"sandwich\",\n\"glucose\", \"tin\", \"banana\", \"apple\", \"cheese\", \"beer\", \"suntan_cream\",\n\"camera\", \"T-shirt\", \"trousers\", \"umbrella\", \"waterproof_trousers\",\n\"waterproof_overclothes\", \"note-case\", \"sunglasses\", \"towel\",\n\"socks\", \"book\"), weigth = c(9, 13, 153, 50, 15, 68, 27, 39,\n23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30), value = c(150,\n35, 200, 160, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70,\n75, 80, 20, 12, 50, 10)), .Names = c(\"item\", \"weigth\", \"value\"\n), row.names = c(NA, 22L), class = \"data.frame\")\n\n\nBounded_knapsack<-function(Data,W)\n{\n\tK<-matrix(NA,nrow=W+1,ncol=dim(Data)[1]+1)\n\t0->K[1,]->K[,1]\n\tmatrix_item<-matrix('',nrow=W+1,ncol=dim(Data)[1]+1)\n\tfor(j in 1:dim(Data)[1])\n\t{\n\t\tfor(w in 1:W)\n\t\t{\n\t\t\twj<-Data$weigth[j]\n\t\t\titem<-Data$item[j]\n\t\t\tvalue<-Data$value[j]\n\t\t\tif( wj > w )\n\t\t\t{\n\t\t\t\tK[w+1,j+1]<-K[w+1,j]\n\t\t\t\tmatrix_item[w+1,j+1]<-matrix_item[w+1,j]\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif( K[w+1,j] >= K[w+1-wj,j]+value )\n\t\t\t\t{\n\t\t\t\t\tK[w+1,j+1]<-K[w+1,j]\n\t\t\t\t\tmatrix_item[w+1,j+1]<-matrix_item[w+1,j]\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tK[w+1,j+1]<-K[w+1-wj,j]+value\n\t\t\t\t\tmatrix_item[w+1,j+1]<-item\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nreturn(list(K=K,Item=matrix_item))\n}\n\nbacktracking<-function(knapsack, Data)\n{\n\tW<-dim(knapsack$K)[1]\n\titens<-c()\n\tcol<-dim(knapsack$K)[2]\n\tselected_item<-knapsack$Item[W,col]\n\twhile(selected_item!='')\n\t{\n\t\tselected_item<-knapsack$Item[W,col]\n\t\tif(selected_item!='')\n\t\t{\n\t\t\tselected_item_value<-Data[Data$item == selected_item,]\n\t\t\tif(-knapsack$K[W - selected_item_value$weigth,col-1]+knapsack$K[W,col]==selected_item_value$value)\n\t\t\t{\n\t\t\t\tW <- W - selected_item_value$weigth\n\t\t\t\titens<-c(itens,selected_item)\n\t\t\t}\n\t\t\tcol <- col - 1\n\t\t}\n\t}\nreturn(itens)\n}\n\nprint_output<-function(Data,W)\n{\n\tBounded_knapsack(Data,W)->Knap\n\tbacktracking(Knap, Data)->Items\n\toutput<-paste('You must carry:', paste(Items, sep = ', '), sep=' ' )\n\treturn(output)\n}\n\nprint_output(Full_Data, 400)\n", "meta": {"hexsha": "91afd75423018a7439b5595aa5ab75d6d7b115b9", "size": 1962, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.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/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.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/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.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.835443038, "max_line_length": 101, "alphanum_fraction": 0.5988786952, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6840260882219988}} {"text": "#' @title calcKristTotalRes\n#'\n#' @description Calculate total ship resistance (\\code{Rtot}) (kN) using the\n#' Kristensen method.\n#'\n#' @param wettedSA Wetted hull surface area (vector of numericals, m^2) (see\n#' \\code{\\link{calcKristWettedSA}})\n#' @param Cf Frictional resistance coefficient (vector of numericals,\n#' dimensionless) (see \\code{\\link{calcCf}})\n#' @param Cr Residual resistance coefficient (vector of numericals,\n#' dimensionless) (see \\code{\\link{calcKristCr}})\n#' @param Ca Incremental hull (roughness) resistance coefficient (vector of\n#' numericals, dimensionless) (see \\code{\\link{calcKristCa}})\n#' @param Caa Air resistance coefficient (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcKristCaa}})\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 shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param serviceMargin A service margin to account for weather and sea effects:\n#' \\itemize{\\item Coastal operations = 10 \\item At-sea operations = 15} Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#'\n#' @details\n#' Note that service margin is included here as a resistance term.\n#'\n#' @return \\code{Rtot} (vector of numericals, kN)\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{calcCf}}\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'}\n#'\n#' @family Kristensen Calculations\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcKristTotalRes(10714.62,0.0015,0.00043,6.46e-05,5e-05,1.025,10.8,15)\n#'\n#' @export\n\ncalcKristTotalRes<- function(wettedSA,Cf,Cr,Ca,Caa,seawaterDensity,shipSpeed,\n serviceMargin){\n\n Rtot<- wettedSA*(Cf+Cr+Ca+Caa)*seawaterDensity*(shipSpeed^2)*0.5*(1+serviceMargin/100)\n return(Rtot)\n}\n", "meta": {"hexsha": "cd46bdd32c08ca3f989b9566499a35d80833c15a", "size": 2157, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristTotalRes.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/calcKristTotalRes.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/calcKristTotalRes.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.2181818182, "max_line_length": 88, "alphanum_fraction": 0.719054242, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6840260705540108}} {"text": "inputs <- c(1, 2, 3, 2.5)\nweights1 <- c(0.2, 0.8, -0.5, 1.0)\nweights2 <- c(0.5, -0.91, 0.26, -0.5)\nweights3 <- c(-0.26, -0.27, 0.17, 0.87)\nbias1 <- 2\nbias2 <- 3\nbias3 <- 0.5\n\noutput <- c(inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + inputs[4] * weights1[4] + bias1,\n inputs[1] * weights2[1] + inputs[2] * weights2[2] + inputs[3] * weights2[3] + inputs[4] * weights2[4] + bias2,\n inputs[1] * weights3[1] + inputs[2] * weights3[2] + inputs[3] * weights3[3] + inputs[4] * weights3[4] + bias3)\noutput\n", "meta": {"hexsha": "049855e4aa9f426e42950eae3a4eaef8dbf64159", "size": 551, "ext": "r", "lang": "R", "max_stars_repo_path": "R/p002.r", "max_stars_repo_name": "yarikbratashchuk/NNfSiX", "max_stars_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1045, "max_stars_repo_stars_event_min_datetime": "2020-04-16T20:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:33:49.000Z", "max_issues_repo_path": "R/p002.r", "max_issues_repo_name": "yarikbratashchuk/NNfSiX", "max_issues_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-04-17T02:36:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T01:04:27.000Z", "max_forks_repo_path": "R/p002.r", "max_forks_repo_name": "yarikbratashchuk/NNfSiX", "max_forks_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 359, "max_forks_repo_forks_event_min_datetime": "2020-04-16T21:41:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:23:47.000Z", "avg_line_length": 42.3846153846, "max_line_length": 122, "alphanum_fraction": 0.5589836661, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6838048177340611}} {"text": "v = c(2, 3, 7, 1, 5, 10, 2)\nsoma = 0\nfor(i in 1:length(v)) {\n soma = soma + v[i]*v[i]\n}\nprint(sqrt(soma))\n", "meta": {"hexsha": "8ad0a06dc41c3c4d7654857a267b7195e555f626", "size": 107, "ext": "r", "lang": "R", "max_stars_repo_path": "resolucao/r/norma.r", "max_stars_repo_name": "rafaelbes/numericalAnalysis", "max_stars_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "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": "resolucao/r/norma.r", "max_issues_repo_name": "rafaelbes/numericalAnalysis", "max_issues_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "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": "resolucao/r/norma.r", "max_forks_repo_name": "rafaelbes/numericalAnalysis", "max_forks_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-15T00:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T14:52:19.000Z", "avg_line_length": 15.2857142857, "max_line_length": 27, "alphanum_fraction": 0.5046728972, "num_tokens": 56, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6836134192331134}} {"text": "\"\"\"\nК статье по метаанализам\n\n\n\n\"\"\"\n\nlibrary(epiR)\nlibrary(pwr)\n\n# Размер эффекта\n\n# График Стандартной ошибки\n\nSE = c()\nmu = c()\n\nfor (i in seq(500)) {\n sample <- rnorm(n = i, mean = 0, sd = 3)\n SE[i] = sd(sample)/sqrt(length(sample))\n mu[i] = mean(sample)\n}\n\nplot(mu,xlab = 'Sample size', ylab = 'Sample mean', type=\"l\")\n\nplot(SE,xlab = 'Sample size', ylab = 'Standard error', type=\"l\")\n\n# standartise demo\n\nm1 = abs(-6)/2\nm2 = (-14)/10\nsd1 = sqrt(2*(1-0.5)/n1 + (m1)/(2*n1))\nsd2 = sqrt(2*(1-0.5)/n2 + (m2)/(2*n2))\n\nsd1r = sqrt((2^2 + 2^2 - 2*(0.5 * 2*2))/n1)\nsd2r = sqrt((10^2 + 16^2 - 2*(0.5 * 10*16))/n2)\n\nn1 = 58\nn2 = 82\n\n-14 - sd2r\n\n-m1 - 2*sd1\nm2 + 2*sd2\n\npooled_sd = sqrt(((n1-1) * sd1^2 + (n2-1) * sd2^2)/(n1 + n2 - 2))\n\n\n# Модели\n\n# Фиксированные эффекты\n\nSE = c()\nmu = c()\n\nfor (i in seq(100)) {\n sample <- rnorm(n = i, mean = 0, sd = 3)\n SE[i] = sd(sample)/sqrt(length(sample))\n mu[i] = mean(sample)\n}\n\nplot(mu, SE, xlab = 'Effect size', ylab = 'Standard error', xlim=c(-2,2))\nabline(v=0, col='red', lwd=3)\n\n\n\"\"\"\nForest plot\n\"\"\"\n\nlibrary(meta)\n\ndata(Fleiss1993cont)\n\nexample = metacont(n.psyc, mean.psyc, sd.psyc, n.cont, mean.cont, sd.cont,\n data = Fleiss1993cont, studlab = paste(study, year),\n random = TRUE, fixed=TRUE)\n\nforest.meta(example)\n\ndrapery(example, labels = \"studlab\", type = \"pvalue\")\n\n\"\"\"\nEffect size\n\"\"\"\n\n\nx <- seq(- 5, 5, by = 0.01)\ny <- dt(x, df = 50)\n\n# расчет критических значений\ncritical = qt(p=0.05/2, df=length(x), lower.tail=F)\ncritical_one_sided = qt(p=0.05, df=length(x), lower.tail=F)\n\n\nplot(x, \n y, \n type = \"l\", \n main = \" \",\n xlab=\"t-статистики\", ylab=\"Плотность вероятности\",\n las=1,\n col = 'blue',\n xlim=c(-5, 6)\n)\n\nlines(x + 2, \n y, \n type = \"l\", \n main = \" \",\n xlab=\"t-статистики\", ylab=\"Плотность вероятности\",\n las=1,\n col = 'red'\n)\n\n\n\"\"\"\nFunnel plot\n\"\"\"\n\nlibrary(metafor)\n\n### copy BCG vaccine data into 'dat'\ndat <- dat.bcg\n\n### calculate log risk ratios and corresponding sampling variances\ndat <- escalc(measure=\"RR\", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat)\n\n### fit random-effects model\nres <- rma(yi, vi, data=dat, slab=paste(author, year, sep=\", \"))\n\n### draw a standard funnel plot\nfunnel(res)\n\n### note: same plot, except that reference line is centered at zero\nfunnel(dat$yi, dat$vi)\n\n### the with() function can be used to avoid having to retype dat$... over and over\nwith(dat, funnel(yi, vi))\n\n\n\"\"\"\nEgger test\n\"\"\"\n\n\n\n", "meta": {"hexsha": "e966be1e8c4af85a3aee8c087d046294df150b0c", "size": 2470, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/pages/metaanalysis/meta.r", "max_stars_repo_name": "aysuvorov/clinstats", "max_stars_repo_head_hexsha": "198042b6d6a08c1bc5edd388dfa84223259006a2", "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": "docs/pages/metaanalysis/meta.r", "max_issues_repo_name": "aysuvorov/clinstats", "max_issues_repo_head_hexsha": "198042b6d6a08c1bc5edd388dfa84223259006a2", "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": "docs/pages/metaanalysis/meta.r", "max_forks_repo_name": "aysuvorov/clinstats", "max_forks_repo_head_hexsha": "198042b6d6a08c1bc5edd388dfa84223259006a2", "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.9178082192, "max_line_length": 83, "alphanum_fraction": 0.5870445344, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.6835688852522233}} {"text": "#\n# Exemplo 1\n#\n\n# Serie de Taylor para a exponencial de x\n# em x=3 em volta do ponto x=2 até n=4\nx <- 3\ntaylor <- exp(2) + exp(2) * (x - 2)\ntaylor <- taylor + exp(2) * (x - 2)^2 / factorial(2)\ntaylor <- taylor + exp(2) * (x - 2)^3 / factorial(3)\ntaylor <- taylor + exp(2) * (x - 2)^4 / factorial(4)\n\ntaylor\n# valor real da exponencial de x\nexp(x)", "meta": {"hexsha": "37e14f6f0dd732653985959f2b08d893467c2471", "size": 347, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/aula4/exemplo1.r", "max_stars_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_stars_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "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/aula4/exemplo1.r", "max_issues_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_issues_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "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/aula4/exemplo1.r", "max_forks_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_forks_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "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": 23.1333333333, "max_line_length": 52, "alphanum_fraction": 0.590778098, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6835139489080273}} {"text": "\n# DySyn_distance <- function (x, method= \"hellinger\"){\n# \n# if (method == \"ord\") {\n# x_dif <- x[1,]-x[2,]\n# acum <- 0\n# aux <- 0\n# for(i in 1:length(x_dif)){\n# aux <- x_dif[i]+aux\n# acum <- acum+aux\n# }\n# return(abs(acum))\n# }\n# return(as.numeric(philentropy::distance(x, method = method, p=0.5)))\n# \n# }\n\nDySyn_distance <- function (x, method= \"hellinger\"){\n \n if (method == \"ord\") {\n x_dif <- x[1,]-x[2,]\n acum <- 0\n aux <- 0\n for(i in 1:length(x_dif)){\n aux <- x_dif[i]+aux\n acum <- acum+aux\n }\n return(abs(acum))\n }\n if(method == \"topsoe\"){\n re <- 0\n for(i in 1:ncol(x))\n re <- re + ( x[1,i] * log( (2*x[1,i])/(x[1,i] + x[2,i]) ) + x[2,i]*log( (2*x[2,i])/(x[2,i] + x[1,i]) ) )\n \n return(re)\n }\n if(method == \"jensen_difference\"){\n re <- 0\n for(i in 1:ncol(x))\n re <- re + ( ((x[1,i]*log(x[1,i]) + x[2,i]*log(x[2,i]) )/2) - ((x[1,i] + x[2,i])/2 ) * log((x[1,i] + x[2,i])/2 ) )\n \n return(re)\n }\n if(method == \"taneja\"){\n re <- 0\n for(i in 1:ncol(x))\n re <- re + ( ((x[1,i] + x[2,i])/2) * log( (x[1,i] + x[2,i]) / (2 * sqrt(x[1,i] * x[2,i]) )) )\n return(re)\n }\n if(method == \"hellinger\"){\n re <- 0\n for(i in 1:ncol(x))\n re <- re + sqrt((x[1,i] * x[2,i]))\n return(2*sqrt(1 - re))\n }\n \n if(method == \"prob_symm\"){\n re <- 0\n for(i in 1:ncol(x))\n re <- re + ( (x[1,i] - x[2,i] )^2 / (x[1,i] +x[2,i]) )\n return(2*re)\n }\n \n stop(\"measure argument must be a valid option\")\n}\n\ngetHist <- function(scores, nbins){\n breaks <- seq(0,1,length.out = nbins+1)\n breaks <- c(breaks[-length(breaks)], 1.1)\n re <- rep((1/(length(breaks)-1)),length(breaks)-1)\n for(i in 2:length(breaks)){\n re[i-1] <- (re[i-1] + length(which(scores >= breaks[i-1] & scores < breaks[i])))/(length(scores)+1)\n }\n return(re)\n}\n\n\nTernarySearch <- function(left, right, f, eps=1e-4){\n while(TRUE){\n if (abs(left - right) < eps) return((left + right) / 2)\n \n leftThird <- left + (right - left) / 3\n rightThird <- right - (right - left) / 3\n \n if (f(leftThird) > f(rightThird))\n left <- leftThird\n else\n right <- rightThird\n }\n \n}", "meta": {"hexsha": "3fe3c74a932a3618b339561c419eca08da70f55f", "size": 2203, "ext": "r", "lang": "R", "max_stars_repo_path": "proposals/utils.r", "max_stars_repo_name": "andregustavom/icdm21_paper", "max_stars_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "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": "proposals/utils.r", "max_issues_repo_name": "andregustavom/icdm21_paper", "max_issues_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "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": "proposals/utils.r", "max_forks_repo_name": "andregustavom/icdm21_paper", "max_forks_repo_head_hexsha": "ee4f5247ae6574ab69f5a29134846d50d9e305b8", "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": 24.2087912088, "max_line_length": 123, "alphanum_fraction": 0.4788924194, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6833891532862865}} {"text": "halve <- function(a) floor(a/2)\ndouble <- function(a) a*2\niseven <- function(a) (a%%2)==0\n\nethiopicmult <- function(plier, plicand, tutor=FALSE) {\n if (tutor) { cat(\"ethiopic multiplication of\", plier, \"and\", plicand, \"\\n\") }\n result <- 0\n while(plier >= 1) {\n if (!iseven(plier)) { result <- result + plicand }\n if (tutor) {\n cat(plier, \", \", plicand, \" \", ifelse(iseven(plier), \"struck\", \"kept\"), \"\\n\", sep=\"\")\n }\n plier <- halve(plier)\n plicand <- double(plicand)\n }\n result\n}\n\nprint(ethiopicmult(17, 34, TRUE))\n", "meta": {"hexsha": "1fbb7a37183dcba8189ec99909333fc313da5e8c", "size": 540, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Ethiopian-multiplication/R/ethiopian-multiplication-1.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/Ethiopian-multiplication/R/ethiopian-multiplication-1.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/Ethiopian-multiplication/R/ethiopian-multiplication-1.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": 27.0, "max_line_length": 91, "alphanum_fraction": 0.587037037, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6831645353251788}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Non parametric Tests - Exercise 15\n\nrm(list = ls())\n\nx <- c(0.01, 0.02, 0.03, 0.01, 0.01, 0.01, 0.02, 0.04,\n 0.05, 0.03, 0.02, 0.01, 0.06, 0.01, 0.01, 0.04)\n\ny <- c(0.02, 0.04, 0.03, 0.01, 0.04, 0.06, 0.01, 0.01,\n 0.05, 0.01, 0.04, 0.03, 0.04, 0.06, 0.03, 0.01)\n\n(s <- (x - y)[x != y])\n# -0.01 -0.02 -0.03 -0.05 0.01 0.03 0.02 -0.02 -0.02 0.02 -0.05 -0.02 0.03\n\n(n <- length(s))\n# 13\n\nsum(duplicated(s))\n# 5\n\n(V <- sum((s > 0) * rank(abs(s))))\n# 30.5\n\n(V.mean <- n * (n + 1) / 4)\n# 45.5\n\n(V.var <- n * (n + 1) * (2 * n + 1) / 24)\n# 204.75\n\n# Asymptotic pvalue (with continuity correction, without tie correction)\n2 * (1 - pnorm(abs(V + 0.5 * sign(V.mean - V) - V.mean) / sqrt(V.var)))\n# 0.310896828516612\n\n## Asymptotic pvalue (with continuity correction, with tie correction\n# TODO\n\n# Exact pvalue (not valid due to ties)\n2 * (1 - psignrank(V - (V.mean < V), n, lower.tail = V.mean < V))\n# 0.339599609375\n\nwilcox.test(x, y, paired = TRUE, alternative = \"two.sided\", exact = FALSE)\n# Wilcoxon signed rank test with continuity correction\n#\n# data: x and y\n# V = 49, p-value = 0.3388\n# alternative hypothesis: true location shift is not equal to 0\n\n", "meta": {"hexsha": "227333db3d4486bafd9c1777b25a0a3b59bc4b59", "size": 1225, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/non-parametric/exercise-15.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/non-parametric/exercise-15.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/non-parametric/exercise-15.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "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": 25.5208333333, "max_line_length": 74, "alphanum_fraction": 0.586122449, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.6831645250792233}} {"text": "# Using arithmetic operators on variables\nnumber1 <- 10\nnumber2 <- 3\n\n# Addition\nnumber1 + number2\n\n# Subtraction\nnumber1 - number2\n\n# Multiplication\nnumber1 * number2\n\n# Exponent \nnumber1 ^ number2\n\n# Modulus\nnumber1 %% number2\n\n# Integer Division\nnumber1 %/% number2\n\n# Using arithmetic operators on vectors\nvector1 <- c(5, 10, 15)\nvector2 <- c(3, 6, 9)\n\n# Addition\nvector1 + vector2\n\n# Subtraction\nvector1 - vector2\n\n# Multiplication\nvector1 * vector2\n\n# Division \nvector1 / vector2\n\n# Exponent \nvector1 ^ vector2\n\n# Modulus\nvector1 %% vector2\n\n# Integer Division\nvector1 %/% vector2\n\n", "meta": {"hexsha": "78fffb83fedfb7df48bd543498bdca44b48a5f3b", "size": 588, "ext": "r", "lang": "R", "max_stars_repo_path": "0 - Learn R from scratch/arithmetic_operators.r", "max_stars_repo_name": "fdAssis/Linguagem-R", "max_stars_repo_head_hexsha": "80ec74ce6954e37cc1e71bf11c0f0942d1b1dce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-16T01:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T21:36:18.000Z", "max_issues_repo_path": "0 - Learn R from scratch/arithmetic_operators.r", "max_issues_repo_name": "fdAssis/Linguagem-R", "max_issues_repo_head_hexsha": "80ec74ce6954e37cc1e71bf11c0f0942d1b1dce2", "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": "0 - Learn R from scratch/arithmetic_operators.r", "max_forks_repo_name": "fdAssis/Linguagem-R", "max_forks_repo_head_hexsha": "80ec74ce6954e37cc1e71bf11c0f0942d1b1dce2", "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": 12.25, "max_line_length": 41, "alphanum_fraction": 0.7227891156, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.6831290747983422}} {"text": "# Author: Nikos Kougianos\n# Date: 4/12/2020\n\n\ncalculateW2 <- function(x) {\n # We call mean and sd functions outside of loop for performance reasons\n mean <- mean(x)\n s <- sd(x)\n \n result <- c()\n \n tmp <- 0\n \n # Loop vector\n for (i in 1:length(x)) {\n if (abs((i - mean) / s) < 1) {\n tmp = 1\n } else if (abs((i - mean) / s) >= 1 &\n abs((i - mean) / s) < 2) {\n tmp = 0.5\n } else {\n tmp = 0\n }\n result <- append(result, tmp)\n }\n \n return(result)\n \n}\n\ncalculateW3 <- function(x) {\n mean <- mean(x)\n s <- sd(x)\n \n tmp = 1 / (s * sqrt(2 * pi))\n result = tmp * exp((-1 / (2 * s ** 2)) * ((x - mean) ** 2))\n \n return(result)\n \n}\n\n\n# This function is the solution of the exercise\nf <- function(x) {\n # Initialize object to return\n result <- c()\n \n # Calculate w1\n result[[1]] <- rep(1, length(x))\n # Calculate w2\n result[[2]] <- calculateW2(x)\n # Calculate w3\n result[[3]] <- calculateW3(x)\n return(result)\n}\n\n\n# Call function f with a vector with values from 1 to 50\nf(1:50)\n", "meta": {"hexsha": "8c7fe76fa33eca76f95a47272f7df9de08ae4c8f", "size": 1148, "ext": "r", "lang": "R", "max_stars_repo_path": "exercise2/solutionNikosKougianos.r", "max_stars_repo_name": "kougianos/R-code", "max_stars_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": "exercise2/solutionNikosKougianos.r", "max_issues_repo_name": "kougianos/R-code", "max_issues_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": "exercise2/solutionNikosKougianos.r", "max_forks_repo_name": "kougianos/R-code", "max_forks_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": 19.1333333333, "max_line_length": 75, "alphanum_fraction": 0.4799651568, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6831076496357003}} {"text": "cube <- function(x) x^3\ncroot <- function(x) x^(1/3)\ncompose <- function(f, g) function(x){f(g(x))}\n\nf1 <- c(sin, cos, cube)\nf2 <- c(asin, acos, croot)\n\nfor (i in 1:3) {\n\tprint (compose(f1[[i]], f2[[i]])(.5))\n}\n", "meta": {"hexsha": "0a01aa9dec2ea7713c856a80352f1deda07c8ab0", "size": 211, "ext": "r", "lang": "R", "max_stars_repo_path": "r/func.r", "max_stars_repo_name": "gregorymorrison/euler1", "max_stars_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-13T11:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-13T11:11:50.000Z", "max_issues_repo_path": "r/func.r", "max_issues_repo_name": "gdm9000/euler1", "max_issues_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "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/func.r", "max_forks_repo_name": "gdm9000/euler1", "max_forks_repo_head_hexsha": "171d98a60e62041bc49882336cd65687df810b6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-10T00:27:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-10T00:27:17.000Z", "avg_line_length": 19.1818181818, "max_line_length": 46, "alphanum_fraction": 0.5545023697, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6829312499232421}} {"text": "# Filename:\tcode.r\n# Project:\t/Users/shume/Developer/stat/MedicalStatisticsClass/2019/3\n# Authors:\tshumez \n# Created:\t2019-10-23 16:38:57\n# Modified:\t2019-11-10 15:02:05\n# -----\n# Copyright (c) 2019 shumez\n\n##### 医学統計勉強会18 第3回 連続変数の比較 R code #####\n\n# 二標本問題 ##\nx1 <- c(8, 17, 9, 5, 14, 13, 13, 3, 9, 0)\nx2 <- c(19, 13, 13, 18, 21, 18, 11, 21, 20, 11)\n\nboxplot(x1, x2)\n\nt.test(x1, x2)\t\t# Welch's t test\nwilcox.test(x1, x2)\t# Mann-Whitney test, Wilcoxon's rank sum test\n\n# QQ-norm plot #\n\nqqplot(x1)\nqqline(x1)\n\nqqplot(x2)\nqqline(x2)\n\n# Shapiro-Wilk normality test #\n\nshapiro.test(x1)\n\n\n\n## 分散分析 ##\n\n# サンプルデータ #\nData <- data.frame(\n\tz = c(8, 16, 7, 18, 6, 11, 15, 11, 20, 7, 19, 20, 21, 19, 24), \n\tgroup = factor(c(rep(1,5), rep(2,5), rep(3,5)), label=c(\"placebo\", \"drugA\", \"drugB\")))\nprint(Data)\nboxplot(z ~ group, data=Data)\n\n# One-way ANOVA #\nfit.aov <- aov(z ~ group, data=Data)\nsummary(fit.aov)\n\n# One-way ANOVA (not assuming equal variances) #\noneway.test(z ~ group, data=Data)\n\n# Kruskal-Wallis rank sum test #\nkruskal.test(z ~ group, data=Data)\n\n\n\n## モデル診断 (model diagnostics) ##\n\npar(mfrow=c(2,2))\nplot(fit.aov)\npar(mfrow=c(1,1))\n\n\n\n## Box-Cox transformation ##\n\nlibrary(MASS)\nbxcx <- boxcox(fit.aov)\nlambda <- bxcx$x[which.max(bxcx$y)]\n\nfit.aov2 <- aov((z^lambda - 1)/lambda ~ group, data=Data)\nsummary(fit.aov2)\n\npar(mfrow=c(2,2))\nplot(fit.aov2)\npar(mfrow=c(1,1))\n\n\n\n## 多重比較 ##\n\n# Tukey's method #\nlibrary(MASS)\nfit.mc <- TukeyHSD(fit.aov)\nprint(fit.mc)\nplot(fit.mc)\n\n# Dunnett's method (Dunnett post hoc test) #\ninstall.packages(\"multcomp\")\t# 最初の一回のみ実行\nlibrary(multcomp)\nfit.dunnett <- glht(fit.aov, linfct = mcp(group = \"Dunnett\"))\nconfint(fit.dunnett, level=0.95)\nsummary(fit.dunnett)\n\n# William's method #\nfit.williams <- glht(fit.aov, linfct = mcp(group = \"Williams\"))\nconfint(fit.williams, level=0.95)\nsummary(fit.williams)", "meta": {"hexsha": "04f21028feec000f6f15ac89ec93f5fb9153a051", "size": 1864, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/3/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "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": "MedicalStatisticsClass/2019/3/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "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": "MedicalStatisticsClass/2019/3/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "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": 19.4166666667, "max_line_length": 87, "alphanum_fraction": 0.6534334764, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6828325279158989}} {"text": "# La mecánica detrás del OLS (II): matrices en R.\n\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n# definir x\nx = matrix(\n c(1,1,1,2,7,3,2,4,6),\n nrow = 3, \n ncol = 3\n )\n\nx\n\n# definir y\ny = matrix(\n c(3,5,7),\n nrow = 3, \n ncol = 1\n)\n\ny\n###########################\n# transponer x con comando \"t\"\n###########################\nt(x)\n\n###########################\n# x'x\n###########################\nt(x) %*% x\n\n###########################\n# inverse\n###########################\n\n## primero, encontrar determinante\n# det(t(x)%*%x)\n# 324\n\n## segundo, encontrar Adjacente\n\n# Hagamos el proceso de manera directa. Invirtamos x'x\n\nsolve(t(x)%*%x)\n\n###########################\n# Modelo\n###########################\n\n# En Matriz: b = (x'x)-1*x'y\noptions(scipen=99)\nsolve(t(x) %*% x)%*%t(x)%*%y # beta\n\nb = round(solve(t(x) %*% x)%*%t(x)%*%y, 0)\nb\n\n# Usando el comando \"lm\"\ndata = data.frame(\n x=x[,2:3],\n y=y\n )\n\ndata\n\nmodelo = lm(y ~ x.1 + x.2, data) # \"lineal model\"\nsummary(modelo)\n", "meta": {"hexsha": "cec6f9a0ddafaf5d0faaf66d03e2941549faed60", "size": 995, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase9/Clase9.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": "Lectures/Clase9/Clase9.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": "Lectures/Clase9/Clase9.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": 14.4202898551, "max_line_length": 54, "alphanum_fraction": 0.4271356784, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6828323612084135}} {"text": "library(VGAM)\r\n\r\n###############################################################################\r\n#\r\n# library \r\n# \r\n# source the plfit.r function (from http://www.santafe.edu/~aaronc/powerlaws/)\r\n# if needed\r\n# source(\"plfit.r\")\r\n#\r\n###############################################################################\r\n#\r\n# example zone \r\n#\r\n###############################################################################\r\nrunexample <- function(){\r\n set.seed(123)\r\n x <- (1-runif(1000))^(-1/(2.5-1))\r\n #if plfit exist (with source(\"plfit.r\") for example):\r\n #plfit(x)\r\n #plfit R : xmin=1.007756 alpha=2.517830 D=0.02054889\r\n plpva(x,1)\r\n #plpva R p=0.233 gof=0.02164176\r\n}\r\n###############################################################################\r\n# PLPVA calculates the p-value for the given power-law fit to some data.\r\n# Source: http://www.santafe.edu/~aaronc/powerlaws/\r\n#\r\n# PLPVA(x, xmin) takes data x and given lower cutoff for the power-law\r\n# behavior xmin and computes the corresponding p-value for the\r\n# Kolmogorov-Smirnov test, according to the method described in \r\n# Clauset, Shalizi, Newman (2007).\r\n# PLPVA automatically detects whether x is composed of real or integer\r\n# values, and applies the appropriate method. For discrete data, if\r\n# min(x) > 1000, PLPVA uses the continuous approximation, which is \r\n# a reliable in this regime.\r\n# \r\n# The fitting procedure works as follows:\r\n# 1) For each possible choice of x_min, we estimate alpha via the \r\n# method of maximum likelihood, and calculate the Kolmogorov-Smirnov\r\n# goodness-of-fit statistic D.\r\n# 2) We then select as our estimate of x_min, the value that gives the\r\n# minimum value D over all values of x_min.\r\n#\r\n# Note that this procedure gives no estimate of the uncertainty of the \r\n# fitted parameters, nor of the validity of the fit.\r\n#\r\n# Example:\r\n# x <- (1-runif(10000))^(-1/(2.5-1))\r\n# plpva(x,1)\r\n#\r\n# Version 1.0 (2012 August)\r\n#\r\n# Copyright (C) 2012 Laurent Dubroca (Sete, France)\r\n# laurent - dot -dubroca - at - gmail - dot - com \r\n# Distributed under GPL 2.0\r\n# http://www.gnu.org/copyleft/gpl.html\r\n# PLPVA comes with ABSOLUTELY NO WARRANTY\r\n# Matlab to R translation based on the original code of Aaron Clauset (Santa Fe Institute)\r\n# Source: http://www.santafe.edu/~aaronc/powerlaws/\r\n#\r\n# Notes:\r\n#\r\n# 1. In order to implement the integer-based methods in R, the numeric\r\n# maximization of the log-likelihood function was used. This requires\r\n# that we specify the range of scaling parameters considered. We set\r\n# this range to be seq(1.5,3.5,0.01) by default. This vector can be\r\n# set by the user like so,\r\n#\r\n# a <- plpva(x,1,vec=seq(1.001,5,0.001))\r\n#\r\n# 2. plvar can be told to limit the range of values considered as estimates\r\n# for xmin in two ways. First, it can be instructed to sample these\r\n# possible values like so,\r\n#\r\n# a <- plpva(x,1,\"sample\",100)\r\n#\r\n# which uses 100 uniformly distributed values on the sorted list of\r\n# unique values in the data set. Alternatively, it can simply omit all\r\n# candidates below a hard limit, like so\r\n#\r\n# a <- plpva(x,1,\"limit\",3.4)\r\n#\r\n# In the case of discrete data, it rounds the limit to the nearest\r\n# integer.\r\n#\r\n# 3. The default number of nonparametric repetitions of the fitting\r\n# procedure is 1000. This number can be changed like so\r\n# \r\n# a <- plpva(x,Bt=10000)\r\n# \r\n# 4. To silence the textual output to the screen, do\r\n# \r\n# a <- plpva(x,1,quiet=TRUE)\r\n# \r\n###############################################################################\r\nplpva<-function(x=rpareto(1000,10,2.5),xmin=1,method=\"limit\",value=c(),Bt=1000,quiet=FALSE,vec=seq(1.5,3.5,.01)){\r\n #init method value to NULL\t\r\n sampl <- c() ; limit <- c()\r\n###########################################################################################\r\n#\r\n# test and trap for bad input\r\n#\r\n switch(method, \r\n sample = sampl <- value,\r\n limit = limit <- value,\r\n argok <- 0)\r\n \r\n if(exists(\"argok\")){stop(\"(plvar) Unrecognized method\")}\r\n\r\n if( !is.null(vec) && (!is.vector(vec) || min(vec)<=1 || length(vec)<=1) ){\r\n print(paste(\"(plvar) Error: ''range'' argument must contain a vector > 1; using default.\"))\r\n vec <- c()\r\n }\r\n if( !is.null(sampl) && ( !(sampl==floor(sampl)) || length(sampl)>1 || sampl<2 ) ){\r\n print(paste(\"(plvar) Error: ''sample'' argument must be a positive integer > 2; using default.\"))\r\n sample <- c()\r\n }\r\n if( !is.null(limit) && (length(limit)>1 || limit<1) ){\r\n print(paste(\"(plvar) Error: ''limit'' argument must be a positive >=1; using default.\"))\r\n limit <- c()\r\n }\r\n if( !is.null(Bt) && (!is.vector(Bt) || Bt<=1 || length(Bt)>1) ){\r\n print(paste(\"(plvar) Error: ''Bt'' argument must be a positive value > 1; using default.\"))\r\n vec <- c()\r\n }\r\n\r\n# select method (discrete or continuous) for fitting and test if x is a vector\r\n fdattype<-\"unknow\"\r\n if( is.vector(x,\"numeric\") ){ fdattype<-\"real\" }\r\n if( all(x==floor(x)) && is.vector(x) ){ fdattype<-\"integer\" }\r\n if( all(x==floor(x)) && min(x) > 1000 && length(x) > 100 ){ fdattype <- \"real\" }\r\n if( fdattype==\"unknow\" ){ stop(\"(plfit) Error: x must contain only reals or only integers.\") }\r\n\r\n N <- length(x)\r\n nof <- rep(0,Bt)\r\n\r\n if( !quiet ){\r\n print(\"Power-law Distribution, parameter error calculation\")\r\n print(\"Warning: This can be a slow calculation; please be patient.\")\r\n print(paste(\" n =\",N,\"xmin =\",xmin,\"- reps =\",Bt,fdattype))\r\n } \r\n#\r\n# end test and trap for bad input\r\n#\r\n###########################################################################################\r\n\r\n###########################################################################################\r\n#\r\n# estimate xmin and alpha in the continuous case\r\n#\r\n if( fdattype==\"real\" ){\r\n\r\n # compute D for the empirical distribution\r\n z <- x[x>=xmin]; nz <- length(z)\r\n y <- x[xpz)\r\n q1 <- y[sample(ny,n1,replace=TRUE)]\r\n n2 <- N-n1\r\n q2 <- xmin*(1-runif(n2))^(-1/(alpha-1))\r\n q <- sort(c(q1,q2))\r\n\r\n # estimate xmin and alpha via GoF-method\r\n qmins <- sort(unique(q))\r\n qmins <- qmins[-length(qmins)]\r\n if(!is.null(limit)){\r\n\t qmins<-qmins[qmins<=limit] \r\n } \r\n if(!is.null(sampl)){ \r\n\t qmins <- qmins[unique(round(seq(1,length(qmins),length.out=sampl)))]\r\n }\r\n dat <-rep(0,length(qmins))\r\n for(qm in 1:length(qmins)){\r\n qmin <- qmins[qm]\r\n zq <- q[q>=qmin]\r\n nq <- length(zq)\r\n a <- nq/sum(log(zq/qmin))\r\n cq <- (0:(nq-1))/nq\r\n cf <- 1-(qmin/zq)^a\r\n dat[qm] <- max(abs(cq-cf))\r\n }\r\n if(!quiet){\r\n\t print(paste(B,sum(nof[1:B]>=gof)/B))\r\n }\r\n # store distribution of estimated gof values\r\n nof[B] <- min(dat)\r\n } \r\n }\r\n\r\n###########################################################################################\r\n#\r\n# estimate xmin and alpha in the discrete case\r\n#\r\n if( fdattype==\"integer\" ){\r\n\r\n if( is.null(vec) ){ vec<-seq(1.5,3.5,.01) } # covers range of most practical scaling parameters\r\n zvec <- zeta(vec)\r\n\r\n # compute D for the empirical distribution\r\n z <- x[x>=xmin]; nz <- length(z); xmax <- max(z)\r\n y <- x[xpz)\r\n q1 <- y[sample(ny,n1,replace=TRUE)]\r\n n2 <- N-n1\r\n # simple discrete zeta generator\r\n r2 <- sort(runif(n2)); d <- 1\r\n q2 <- rep(0,n2); k <- 1\r\n for(i in xmin:(mmax+1)){\r\n while((d <= length(r2)) && (r2[d]<=cdf[i,2])){d <- d+1}\r\n if (k <= d - 1)\r\n q2[k:(d-1)] <- i\r\n k <- d\r\n if( k > n2 ){break}\r\n } \r\n q <-c(q1,q2)\r\n ########################################\r\n # estimate xmin and alpha via GoF-method\r\n qmins <- sort(unique(q))\r\n qmins <- qmins[-length(qmins)]\r\n if(!is.null(limit)){\r\n qmins <- qmins[qmins<=limit]\r\n }\r\n if(!is.null(sampl)){\r\n qmins <- qmins[sort(unique(round(seq(1,length(qmins),length.out=sampl))))]\r\n } \r\n dat <- rep(0,length(qmins))\r\n qmax <- max(q) \r\n zq <- q\r\n\r\n if (length(qmins) > 0)\r\n for(qm in 1:length(qmins)){\r\n qmin <- qmins[qm]\r\n zq <- zq[zq>=qmin]\r\n nq <- length(zq)\r\n if(nq>1){\r\n \t # vectorized version of numerical calculation\r\n if(qmin==1){\r\n \t #WARNING\r\n #zdiff <- rep(1,length(vec))\r\n #correction added the 6/10/2009 (following Naoki Masuda for plfit) \r\n zdiff <- rep(0,length(vec))\r\n }else{\r\n zdiff <- apply(rep(t(1:(qmin-1)),length(vec))^-t(kronecker(t(array(1,qmin-1)),vec)),2,sum)\r\n }\r\n L <- -vec*sum(log(zq)) - nq*log(zvec - zdiff);\r\n I <- which.max(L)\r\n # compute KS statistic\r\n fit <- cumsum((((qmin:qmax)^-vec[I]))\r\n / (zvec[I]\r\n - (if (qmin == 1) 0 else sum((1:(qmin-1))^-vec[I]))))\r\n\r\n hist = aggregate(zq, list(zq), length)\r\n cdi = rep(0, qmax - qmin + 1)\r\n cdi[hist$Group.1 - qmin + 1] = hist$x / nq\r\n cdi = cumsum(cdi)\r\n\r\n dat[qm] <- max(abs( fit - cdi ))\r\n }else{\r\n dat[qm] <- -Inf\r\n }\r\n }\r\n if(!quiet){\r\n print(paste(B,\"-\",sum(nof[1:B]>=gof)/B))\r\n }\r\n # -- store distribution of estimated gof values\r\n nof[B] <- min(c(dat, Inf))\r\n\r\n\r\n }\r\n\r\n####################################\r\n\r\n }\r\n#\r\n# end discrete case\r\n#\r\n###########################################################################################\r\n# return p and gof in a list\r\n p <- sum(nof>=gof)/length(nof)\r\n return(list(p=p,gof=gof))\r\n}\r\n", "meta": {"hexsha": "c859ac25d5a9d3919b5a386217c44320fc686862", "size": 11532, "ext": "r", "lang": "R", "max_stars_repo_path": "R/powerlaw/plpva.r", "max_stars_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_stars_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "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": "R/powerlaw/plpva.r", "max_issues_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_issues_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-12-01T15:29:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-30T13:05:54.000Z", "max_forks_repo_path": "R/powerlaw/plpva.r", "max_forks_repo_name": "lsaravia/MarineFoodWebsSmallWorld", "max_forks_repo_head_hexsha": "b045b92d97e624b8ad2a780d208b02a0309cfb27", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-20T21:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T17:05:54.000Z", "avg_line_length": 35.4830769231, "max_line_length": 114, "alphanum_fraction": 0.494276795, "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.682674588058321}} {"text": "dgp <- rpois(100000, 12.75) # pretending we know the true distribution\nmean(dgp)\n\n#### sampling uncertainty when sample size is 16 -------------------------------\nn <- 16\nm <- 10000\n\nset.seed(1)\nmus <- c()\nfor (i in 1:m) {\n x <- sample(dgp, n, rep = T) # sampling with replacement\n mus <- c(mus, mean(x)) \n \n if (i <= 10) {\n print(i)\n print(x)\n print(mean(x))\n }\n}\n\nhist(mus, breaks = 20)\nprint(quantile(mus, p = c(0.025, 0.975)))", "meta": {"hexsha": "296a4b74b48773be36175d7288e4aff0eab56af4", "size": 444, "ext": "r", "lang": "R", "max_stars_repo_path": "R_code/03_mean_participants_idealized.r", "max_stars_repo_name": "bstatcomp/stat_workshop_code", "max_stars_repo_head_hexsha": "23f14056d1d1bb3e49de07237c5a2f03de19b5a8", "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": "R_code/03_mean_participants_idealized.r", "max_issues_repo_name": "bstatcomp/stat_workshop_code", "max_issues_repo_head_hexsha": "23f14056d1d1bb3e49de07237c5a2f03de19b5a8", "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": "R_code/03_mean_participants_idealized.r", "max_forks_repo_name": "bstatcomp/stat_workshop_code", "max_forks_repo_head_hexsha": "23f14056d1d1bb3e49de07237c5a2f03de19b5a8", "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": 20.1818181818, "max_line_length": 80, "alphanum_fraction": 0.5495495495, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6826432807439047}} {"text": "\nquantile_estimation <- function (actual_quantiles, actual_values, estimate_quantiles){\n ##Overview\n #This will return the estimates for the given estimate quantile. If there are estimates\n #that are above or below the actual data range than the last standard deviation is used\n #for the calculation. Currently the only family of estimation supported is gaussian.\n \n ##inputs\n #actual_quantiles: vector of the quantiles for actual data\n #actual_values: the values associated with the actual_quantiles\n #estimate_quantiles: the quantiles to be estimated (0 < estimate_quantiles < 1)\n \n ##outputs\n #returns a tibble (dplyr dataframe) with estimate being the quantile estimates\n \n ##dependencies\n #dplyr\n #tidyr\n \n ##examples\n #tst <- quantile_estimation(actual_quantiles = seq(.05,.95,.05), actual_values = c(253,287,306,320,343,362,377,395,406,419,430,445,462,479,512,546,583,634,771), estimate_quantiles = seq(.01,.99, .01))\n \n \n ##load dependencies if not already loaded\n if(\"dplyr\" %in% (.packages())){\n #already loaded\n } else{\n library(dplyr)\n }\n\n if(\"tidyr\" %in% (.packages())){\n #already loaded\n } else{\n library(tidyr)\n }\n \n \n ##Gather data around actual information and information to be estimated\n actual_quantiles <- round(actual_quantiles, 5)\n estimate_quantiles <- round(estimate_quantiles, 5)\n \n all_quantiles <- sort(unique(c(actual_quantiles, estimate_quantiles)))\n \n all_sd <- qnorm(p = all_quantiles)\n all_sd_diff <- all_sd[2:length(all_sd)] - all_sd[1:(length(all_sd)-1)]\n \n\n ##tibble with only the estimate information\n df_all_estimates <- tibble(\n quantile = all_quantiles\n , sd_diff = lead(qnorm(quantile)) - qnorm(quantile)\n )\n\n \n ##tibble with only the actual information\n df_actual <- tibble(\n quantile = actual_quantiles[1:(length(actual_quantiles))]\n , start_quantile = quantile\n , end_quantile = c(actual_quantiles[2:length(actual_quantiles)],NA)\n , val = actual_values[1:(length(actual_values))]\n , end_val = c(actual_values[2:length(actual_values)],NA)\n ) %>% mutate(\n val_diff = end_val - val\n , val_sd = val_diff / (qnorm(end_quantile) - qnorm(start_quantile))\n )\n \n \n ##tibble with the actual and estimate information combined\n df_all_estimates <- df_all_estimates %>% left_join(\n df_actual\n , by = 'quantile'\n ) %>% mutate(\n source = case_when(is.na(val) ~ 'ESTIMATE', TRUE ~ 'ACTUAL')\n , group = case_when(\n !is.na(val) ~ paste0(start_quantile,\" - \", end_quantile)\n )\n ) %>% fill(\n val_sd\n , .direction = 'down'\n ) %>% fill(\n group\n , .direction = 'down'\n ) %>% fill(\n val_sd \n , .direction = 'up'\n ) %>% mutate(\n group = case_when(\n is.na(group) ~ paste0('0 - ', min(actual_quantiles))\n , TRUE ~ group\n )\n , sd_diff = case_when(\n quantile < min(actual_quantiles) ~ -sd_diff\n , TRUE ~ sd_diff\n )\n )\n \n \n ##rearrange the estimates that are below the actual range\n df_low_estimates <- df_all_estimates %>% filter(\n quantile < min(actual_quantiles)\n ) %>% arrange(\n desc(quantile)\n ) %>% mutate(\n sd_diff_rt = cumsum(sd_diff)\n ) %>% arrange(\n quantile\n ) \n \n \n ##Combine the low estimates to the other estimates\n df_all_estimates <- bind_rows(\n df_low_estimates\n , df_all_estimates %>% filter(\n quantile >= min(actual_quantiles)\n ) %>% group_by(\n group\n ) %>% mutate(\n sd_diff_rt = cumsum(\n sd_diff\n )\n )\n )\n \n \n ##calculate the estimates\n df_all_estimates <- df_all_estimates %>% fill(\n val\n , .direction = 'down'\n ) %>% fill(\n val\n , .direction = 'up'\n ) %>% mutate(\n sd_diff_rt = case_when(\n quantile < min(actual_quantiles) ~ sd_diff_rt\n , quantile == min(actual_quantiles) ~ 0\n , TRUE ~ lag(sd_diff_rt)\n )\n #, estimate = val + sd_diff_rt * val_sd\n , estimate = case_when(\n source == 'ACTUAL' ~ val\n , TRUE ~ val + sd_diff_rt * val_sd\n )\n )\n\n \n return(df_all_estimates)\n}\n\n", "meta": {"hexsha": "31d5aa2d13b85d6a73787dd5d32b3c8a0a498a65", "size": 4012, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantile Estimation.r", "max_stars_repo_name": "rchecketts/quantile-estimation", "max_stars_repo_head_hexsha": "e450dda55fd38c1c854918f31218aeb324428349", "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": "Quantile Estimation.r", "max_issues_repo_name": "rchecketts/quantile-estimation", "max_issues_repo_head_hexsha": "e450dda55fd38c1c854918f31218aeb324428349", "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": "Quantile Estimation.r", "max_forks_repo_name": "rchecketts/quantile-estimation", "max_forks_repo_head_hexsha": "e450dda55fd38c1c854918f31218aeb324428349", "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.9261744966, "max_line_length": 202, "alphanum_fraction": 0.6490528415, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6825372417905183}} {"text": "# Convenient functions for evaluating ising model simulators.\n\n#####################################################################\n## Functions to order Ising states.\n\nto_binary <- function(n, n_digits, ising_state = FALSE) {\n # Convert base 10 number to base 2 number, with digits\n # stored as an n_digits-vector.\n #\n # n: the state number (start counting at 0)\n # n_digitis: the number of digits, hence of particles in the graph.\n # ising_state: if TRUE, returns a vector 1 and -1, instead of 1 and 0's.\n j = 0\n x = rep(ifelse(ising_state, -1, 0), n_digits)\n while (n > 0) {\n x[n_digits - j] = n %% 2\n if (ising_state && (x[n_digits - j] == 0)) x[n_digits - j] = ifelse(ising_state, -1, 0)\n n = as.integer(n/2)\n j = j + 1\n }\n x\n}\n\nto_decimal <- function(samples) {\n # convert samples to decimal numbers\n n_iter = nrow(samples)\n n_particles = ncol(samples)\n decimals <- rep(NA, n_iter)\n for (i in 1:n_iter) {\n decimals[i] = 0\n for (j in 1:ncol(samples)) decimals[i] = decimals[i] +\n 2^{n_particles - j} * samples[i, j] * (samples[i, j] == 1)\n }\n decimals\n}\n\n# returns the number of samples with a spin up (+1)\ncount_states <- function(samples, n_part) {\n 0.5 * (rowSums(samples) + n_part)\n}\n\n# same as above, but for a single sample\ncount_states_single <- function(samples, n_part) {\n 0.5 * (sum(samples) + n_part)\n}\n\n#####################################################################\n## Functions to do an exact computation of the partition function.\n\nising_kernel <- function (beta, A, x, B = 0, log = FALSE) {\n # Returns the kernel for an ising model.\n hamiltonian = 0.5 * beta * (t(x) %*% A %*% x) + B * sum(x)\n if (log) { hamiltonian } else { exp(hamiltonian) }\n}\n\n# use this in the tempering algorithm to not double-count the beta.\nraw_hamiltonian <- function (A, x) {\n 0.5 * t(x) %*% A %*% x\n}\n\npotts_log_kernel <- function (beta, A, x, B = 0, n_states = 2) {\n n_particle = nrow(A)\n exp_term = 0\n Y = matrix(NA, nrow = n_particle, ncol = n_states)\n for (l in 1:n_states) {\n Y[, l] = rep(0, n_particle)\n Y[x == l, l] = 1\n exp_term = exp_term + t(Y[, l]) %*% A %*% Y[, l]\n }\n\n # for (j in 2:n_particle) {\n # for (i in 1:(j - 1)) {\n # if (x[i] == x[j]) exp_term = exp_term + A[i, j]\n # }\n # }\n\n beta * exp_term\n}\n\npartition <- function (beta, A, B = 0, prob = FALSE) {\n # brute-force computes the partition function for\n # an Ising model. Useful for simple configurations\n # and unit tests.\n # If prob = TRUE, return a list which contains the \n # partition function and the probability mass for\n # each configuration.\n n_particles = nrow(A)\n x = rep(-1, n_particles)\n Z = 0\n if (prob) p = rep(NA, 2^n_particles)\n \n for (i in 0:((2^n_particles) - 1)) {\n # update state of the system\n x = to_binary(i, n_particles, ising_state = TRUE)\n local_kernel = ising_kernel(beta, A, x, B)\n Z = Z + local_kernel\n if (prob) p[i + 1] = local_kernel\n }\n \n Z = as.numeric(Z)\n \n if (!prob) { Z } else {\n list(Z = Z, p = p / Z)\n }\n}\n\npartition_complete <- function (beta, A, B = 0, prob = FALSE) {\n # a specialized function that computes the partition function\n # for a complete graph.\n # Remark: the probability are over the summary count space.\n n_particles = nrow(A)\n d = A[1, 2]\n\n # number of positive spins\n # n = 0:(floor(n_particles / 2))\n n = 0:n_particles\n length_n = length(n)\n # double_count = rep(2, length_n)\n # if (n_particles %% 2 == 0) {double_count[length_n] = 1}\n\n p = rep(NA, n_particles + 1)\n for (i in n) {\n j = i + 1\n p[j] = choose(n_particles, i) * exp(0.5 * beta * d *\n (4 * i^2 - 4 * i * n_particles +\n n_particles^2 - n_particles) +\n B * (2 * i - n_particles))\n # if (double_count[j] == 2) p[n_particles + 1 - (j - 1)] = p[j]\n }\n \n Z = sum(p)\n if (!prob) { Z } else {\n list(Z = Z, p = p / Z)\n }\n}\n\ncount_probability <- function(p_analytical, n_particles) {\n # Returns probability over the summary count space, given\n # the exact probability for each state.\n # Useful in non-symmetric cases.\n \n n_states = length(p_analytical)\n # for (i in 0:n_states) {\n prob = rep(0, n_particles + 1)\n for (i in 0:(n_states - 1)) {\n index = sum(to_binary(i, n_particles, ising_state = FALSE)) + 1\n prob[index] = prob[index] + p_analytical[i + 1]\n }\n prob\n}\n\n#####################################################################\n# Functions which return performance metrics, based on the\n# produced samples.\n\nsummary <- function (samples, p_analytical, discard_burn_in = TRUE) {\n # Returns a few summaries statistics, including accuracy ratio\n # and variational distance.\n #\n # samples: simulated samples with x in {-1, 1}^n\n # p_analytical: a vector of probability\n # discard_burn_in: if TRUE, only use the second half of the samples.\n \n n_particles = ncol(samples)\n n_iter = nrow(samples)\n n_states = 2^n_particles\n \n # convert results to decimal numbers\n decimals = to_decimal(samples)\n if (discard_burn_in) decimals = decimals[(n_iter / 2):n_iter]\n \n p_empirical = rep(NA, n_states)\n for (i in 0:(n_states - 1)) p_empirical[i + 1] = sum(decimals == i)\n p_empirical = p_empirical / length(decimals)\n \n # p_empirical = table(decimals) / length(decimals)\n \n accuracy_ratio = as.vector(abs(p_empirical / p_analytical - 1))\n max_ratio = max(accuracy_ratio)\n total_distance = 0.5 * sum(abs(p_empirical - p_analytical))\n variational_distance = max(abs(p_empirical - p_analytical))\n \n list(decimals = decimals,\n accuracy_ratio = accuracy_ratio,\n max_ratio = max_ratio,\n total_distance = total_distance,\n variational_distance = variational_distance)\n}\n\ngen_frequency_iter <- function (decimals, n_particles) {\n # Returns a 2-array with the frequency of each state\n # after the i^th iteration.\n # WARNING: this function takes some time to run!\n # For loops in R are very inefficient.\n # FIX ME -- find a slicker way of writing this.\n\n n_iter = length(decimals)\n n_states = 2^n_particles\n\n frequency_iter = matrix(0, nrow = n_iter, ncol = 2^n_particles)\n \n for (j in 1:n_iter) {\n if (j %% 100 == 0) print(paste0(\"iteration: \", j, \" / \", n_iter))\n unique_elements = sort(unique(decimals[1:j])) + 1 # adjust index\n current_frequency = table(decimals[1:j]) / j\n \n if (length(current_frequency) == n_states) {\n frequency_iter[j, ] = current_frequency\n } else {\n for (i in 1:length(unique_elements)) {\n frequency_iter[j, unique_elements[i]] = current_frequency[i]\n }\n }\n }\n \n frequency_iter\n}\n\nttv_total <- function (samples, p_analytical, discard_burn_in = TRUE) {\n # Return the total variational distance (ttv). \n n_particles = ncol(samples)\n n_iter = nrow(samples)\n n_states = 2^n_particles\n \n # convert results to decimal numbers\n decimals = to_decimal(samples)\n if (discard_burn_in) decimals = decimals[(n_iter / 2):n_iter]\n \n p_empirical = rep(NA, n_states)\n for (i in 0:(n_states - 1)) p_empirical[i + 1] = sum(decimals == i)\n p_empirical = p_empirical / length(decimals)\n \n 0.5 * sum(abs(p_empirical - p_analytical))\n}\n\nttv_count <- function (samples, p_analytical, discard_burn_in = TRUE) {\n # Return the variational distance over the count space\n # (i.e. the number of up spins)\n\n n_particles = ncol(samples)\n n_iter = nrow(samples)\n n_states = n_particles + 1\n\n # convert results to spin up counts.\n if (discard_burn_in) samples = samples[(n_iter / 2):n_iter, ]\n count_sample = count_states(samples, n_particles)\n\n p_empirical = rep(NA, n_states)\n for (i in 0:(n_states - 1)) p_empirical[i + 1] = sum(count_sample == i)\n p_empirical = p_empirical / length(count_sample)\n \n 0.5 * sum(abs(p_empirical - p_analytical))\n}\n\nttv_comp <- function(samples, p_analytical, type = \"total\", \n discard_burn_in = T) {\n if (type == 'total') \n return(ttv_total(samples, p_analytical, discard_burn_in))\n if (type == 'count') \n return(ttv_count(samples, p_analytical, discard_burn_in))\n}\n\nESS <- function(gen_quant, batch_size, burn_in, n_algorithms,\n sd_gen_quant, gq_index = 1) {\n # Do multiple estimates of the generated quantity, by splitting\n # the sample into multiple batches. This allows us to estimate\n # the Monte Carlo error.\n n_sample <- dim(gen_quant)[1]\n batch <- seq(from = burn_in + 1, to = n_sample, by = batch_size)\n batch_means <- matrix(NA, nrow = length(batch), ncol = n_algorithms)\n for (b in 1:length(batch)) {\n for (i in 1:n_algorithms) {\n batch_means[b, i] =\n mean(gen_quant[batch[b]:(batch[b] + batch_size - 1), i, gq_index])\n }\n }\n mc_sd <- rep(NA, n_algorithms)\n ratio <- rep(NA, n_algorithms)\n for (i in 1:n_algorithms) {\n mc_sd[i] <- sd(batch_means[, i])\n ratio[i] <- (sd_gen_quant / mc_sd[i])^2 / 1e3\n }\n\n list(mc_sd = mc_sd, ratio = ratio)\n}\n\n# Compute means for sufficient statistics for an array\n# of samples (whihch a n x m x p object)\nmonte_carlo_estimate <- function(sample_all) {\n n_replica <- dim(sample_all)[1]\n n_iter <- dim(sample_all)[2]\n\n M_square <- rep(NA, n_replica)\n for (i in 1:n_replica) M_square[i] <- mean(rowSums(sample_all[i, , ])^2)\n \n mean_log_kernel <- rep(NA, n_replica)\n log_kernel <- array(NA, c(n_replica, n_iter))\n for (i in 1:n_replica) {\n for (j in 1:n_iter) {\n log_kernel[i, j] <- ising_kernel(beta_vector[i], A, \n sample_all[i, j, ],\n log = T)\n }\n mean_log_kernel[i] <- mean(log_kernel[i, ])\n }\n\n list(M_square = M_square, mean_log_kernel)\n}\n\n###############################################################################\n## Function to compute a multivariate normal distribution, given\n# a mean vector and cholesky decomposition of the covariance matrix.\nmvrnorm_cholesky <- function (n = 1, mu, L) {\n # Samples from a multivariate normal distribution, given a mean vector\n # a (lower triangular) Cholesky decomposition of the covariance matrix.\n dimension <- length(mu)\n X = matrix(NA, nrow = n, ncol = dimension)\n for (i in 1:n) {\n z = rnorm(dimension)\n X[i, ] = L %*% z + mu \n }\n X\n}\n\n###############################################################################\n## Function to generate the adjancency matrix for special grids\n\ngrid_graph <- function (m, anti_corr = FALSE, ignore_degrees = FALSE) {\n # The nodes row-ordered.\n # For example:\n # 1 2 3\n # 4 5 6\n # 7 8 9\n # The nodes are connected using the \"+m\" and\n # \"non-edge neighbor\" rules.\n # \n # m: the number of column in the graph, and in the square grid setting\n # the square root of the total number of particles.\n # anti_corr: if true, then the connection is -1 instead of 1 with\n # probability 0.5.\n\n # FIX ME: condition sometimes fail -- numerical error?\n # if (m %% 1 != 0) stop(\"The number of particles must be a square!\")\n\n n_particle = m^2\n A = matrix(0, nrow = n_particle, ncol = n_particle)\n for (i in 1:n_particle) {\n # edge neihbor rule\n if (i %% m != 0) {\n if (anti_corr) { connection = 1 - 2 * rbinom(1, 1, 0.5)\n } else { connection = 1}\n A[i + 1, i] = connection\n A[i, i + 1] = connection\n }\n\n # \"+m\" rule\n if (i + m <= n_particle) {\n if (anti_corr) { connection = 1 - 2 * rbinom(1, 1, 0.5)\n } else { connection = 1}\n A[i + m, i] = connection\n A[i, i + m] = connection\n }\n }\n\n degree_of_connect = mean(colSums(abs(A)))\n if (ignore_degrees) { d_divide = 1 } else \n { d_divide = degree_of_connect}\n list(A = A / d_divide, d = degree_of_connect)\n}\n\ncube_graph <- function (m, anti_corr = FALSE) {\n # The nodes are row-ordered, then column-ordered.\n # The nodes are connected by first creating the block-diagonal\n # adjacency matrix with grid connection, and then connecting\n # each to the node \"in front\" of it.\n #\n # m is the lattice number, hence the total number of particles\n # is m x m x m.\n \n # FIX ME: condition sometimes fail -- numerical error?\n # if (m %% 1 != 0) stop(\"The number of particles must be a cube!\")\n\n n_particle = m^3\n A = matrix(0, nrow = n_particle, ncol = n_particle)\n for (i in 1:m) {\n grid = grid_graph(m, anti_corr, ignore_degrees = TRUE)\n cube_index = ((i - 1) * m^2 + 1):(i * m^2)\n A[cube_index, cube_index] = grid$A\n }\n \n for (i in 1:(n_particle - m^2)) {\n j = i + m^2\n if (anti_corr) { connection = 1 - 2 * rbinom(1, 1, 0.5)\n } else { connection = 1}\n A[i, j] = connection\n A[j, i] = connection\n }\n\n degree_of_connect = mean(colSums(abs(A)))\n list(A = A / degree_of_connect, d = degree_of_connect) \n}\n\ncube_graph(m = round(216^{1/3}), anti_corr = TRUE)\n\n# Test the method\n# m <- 3\n# alpha <- 2\n# A <- grid_graph(m)\n# C <- A + alpha * diag(m^2)\n# solve(C)\n\n\nadjacency_graph <- function(n_part, type, anti_corr = FALSE,\n do_round = TRUE, m_hopfield = 1) {\n# n_part: number of particles\n# type: complete, grid, gaussian\n# anti_corr: for complete and grid, make some of the connections\n# negative.\n# do_round: round the cube or square of n_part to make sure we\n# we get an integer. Useful for numerical stability.\n if (type == \"complete\") {\n A <- matrix(1, nrow = n_part, ncol = n_part)\n diag(A) <- 0\n A <- A / (n_part - 1) # CHECK -- normalize?\n } else if (type == \"grid\") {\n lattice <- sqrt(n_part)\n if (do_round) lattice <- round(lattice)\n A <- grid_graph(lattice, anti_corr = anti_corr)$A\n } else if (type == \"cube\") {\n lattice <- n_part^{1/3}\n if (do_round) lattice <- round(lattice)\n A <- cube_graph(lattice, anti_corr = anti_corr)$A\n } else if (type == \"gaussian\") {\n A <- matrix(NA, nrow = n_part, ncol = n_part)\n for (i in 1:n_part) {\n for (j in 1:i) {\n A[i, j] = rnorm(1, 0, 1)\n if (i != j) A[j, i] = A[i, j]\n }\n }\n diag(A) <- 0\n A <- A / sqrt(n_part)\n } else if (type == \"hopfield\") {\n eta <- matrix(sample(c(-1, 1), n_part * m_hopfield, replace = TRUE),\n nrow = n_part, ncol = m_hopfield)\n # CHECK: how do we normalize this?\n # A <- eta %*% t(eta) / m_hopfield\n A <- eta %*% t(eta) / max(n_part, m_hopfield)\n diag(A) <- 0\n } else {\n print(\"Could not recognize the type of graph.\")\n }\n A\n}\n", "meta": {"hexsha": "34cb31dd9daf81d9332ea0a995b5574ffd1d265a", "size": 14346, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/tools.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/tools.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/tools.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": 31.5296703297, "max_line_length": 91, "alphanum_fraction": 0.6074167015, "num_tokens": 4370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6825372291933206}} {"text": "\n\n\n# install.packages(\"moments\", repos = \"http://cran.us.r-project.org\")\n\n# install.packages(\"ggpubr\", repos = \"http://cran.us.r-project.org\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nlibrary(moments)\n\nx <- c(0, 3, 6, 7, 9, 12)\n\nskewness(x)\n\nkurtosis(x)\n", "meta": {"hexsha": "4d2c8425655a3a6ee526982a0c3e31975b4459db", "size": 227, "ext": "r", "lang": "R", "max_stars_repo_path": "examen/test.r", "max_stars_repo_name": "underpostnet/r-work", "max_stars_repo_head_hexsha": "aed51988551dbcb02602148578949c0ee39ae8ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-12T05:29:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T21:33:57.000Z", "max_issues_repo_path": "examen/test.r", "max_issues_repo_name": "underpostnet/R-FrameWork", "max_issues_repo_head_hexsha": "ec001b1f3fbd6f22298dffdbe89ca62a3194c66e", "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": "examen/test.r", "max_forks_repo_name": "underpostnet/R-FrameWork", "max_forks_repo_head_hexsha": "ec001b1f3fbd6f22298dffdbe89ca62a3194c66e", "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.1071428571, "max_line_length": 69, "alphanum_fraction": 0.5991189427, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6824901374518721}} {"text": "#####################\n# 数据集说明:\n# data : 剔除NOX后的全部数据,506个观测,12个自变量,1个因变量\n# datafor : 经过变量选择后所保留的自变量和因变量\n# dataExchas : 全模型数据剔除定性变量CHAS后的数据\n#\n#####################\nlibrary(car)\nlibrary(lmtest)\nlibrary(MASS)\n\ndata <- read.csv('BostonHousePrice.csv')\ndata <- data[c(c(2:5),c(7:15))]\n# 包含定性变量拟合模型,R^2为0.7406,CHAS变量不能剔除\nlm <- lm(MEDV~.,data)\nsummary(lm)\n# 不包含定性变量CHAS直接拟合模型,R^2为0.7355\ndataEXchas <- data[c(c(1:3),c(5:13))]\nlmEXchas <- lm(MEDV~.,dataEXchas)\nsummary(lmEXchas)\n\n# 方差分析 全部通过显著性检验\nanova(lm)\n\n# 选模型\nlm.for <- step(lm,direction = \"backward\")\n#lm.for <- step(lm,direction = \"forward\")\n#lm.for <- step(lm,direction = \"both\")\nsummary(lm.for)\ndatafor <- data[c(c(1:2),c(4:5),c(7:13))]\n\n# 异方差检验\ndata1 <- data.frame(data)\nlm1 <- lm(MEDV~.,data = data1)\ne <- resid(lm1,digits = 5)\ne2 <- e^2\ndata2 <- data.frame(datafor,e2)\nlm2 <- lm(e2~.,data = data2)\nan1 <- anova(lm2)\n\n#多重共线性检验 RAD和TAX的方差扩大因子较大,相关系数0.91,RAD和TAX存在多重共线性\nvif(lm.for)\ncor(datafor$RAD,datafor$TAX)\n\n#岭迹图\ndatas <- data.frame(scale(datafor))\nridge <- lm.ridge(MEDV~.-1,data=datas,lambda = seq(0,200,10))\nbeta <- coef(ridge)\nbeta\nk <- ridge$lambda\nplot(k,k,type=\"n\",xlab=\"岭参数\",ylab=\"岭回归系数\",ylim=c(-0.5,0.5))\nlinetype <- c(1:10)\nchar <- c(18:27)\nfor (i in 1:10)\n lines(k, beta[,i], type=\"o\", lty = linetype[i], pch = char[i], cex = 0.75)\nlegend(locator(1),inset = 0.5, legend = c(\"CRIM\",\"ZN\",\"CHAS\",\"RM\",\"DIS\",\n \"RAD\",\"TAX\",\"PTRATIO\",\"B\",\"LSTAT\"), \n cex = 0.6, pch = char, lty = linetype)\n# 确定加权函数的自变量\ne <- resid(lm.for)\nabse <- abs(e)\nvalue <- as.null()\nfield <- c(\"CRIM\",\"ZN\",\"CHAS\",\"RM\",\"DIS\",\"RAD\",\"TAX\",\"PTRATIO\",\"B\",\"LSTAT\")\nfor (i in 1:length(field)){\n a <- data.frame()\n a <- cor.test(datafor[,i],abse,method = \"spearman\")\n print(a$estimate)\n if(is.null(value)){\n value <- a$estimate\n var <- i\n }else if(value <= a$estimate){\n value <- a$estimate\n var <- i\n }\n}\n# 寻找最优权函数,加权最小二乘\ns <-seq(-2,2,0.2)\nresult1 <- vector(length = 21,mode = \"list\")\nresult2 <- vector(length = 21,mode = \"list\")\nfor (j in 1 : 21)\n{\n w <- datafor[,var] ^ (-s[j])\n lm4 <- lm(MEDV~.,weights = w,data = datafor)\n result1[[j]] <- logLik(lm4)\n result2[[j]] <- summary(lm4)\n}\nresult1\nresult2[9]\n\n# DW检验\ndwtest(lm.for,alternative = \"two.sided\")\n# BOX-COX\nbc <- boxcox(MEDV~.,data = datafor,lambda = seq(-2,2,0.01))\nlambda <- bc$x[which.max(bc$y)]\nMEDV_bc <- (datafor$MEDV^lambda-1)/lambda\nlm_bc <- lm(MEDV_bc~.-MEDV,datafor)\nsummary(lm_bc)\nabse_bc <- abs(resid(lm_bc))\nfor (i in 1:length(field)){\n print(cor.test(datafor[,i],abse_bc,method = \"spearman\"))\n}\n\n\n# 定性变量的回归系数相等性检验\nlmQual <- lm(MEDV~.+I(CRIM*CHAS)+I(ZN*CHAS)+I(RM*CHAS)+I(DIS*CHAS)+I(RAD*CHAS)\n +I(TAX*CHAS)+I(PTRATIO*CHAS)+I(B*CHAS)+I(LSTAT*CHAS),datafor)\nsummary(lmQual)\n", "meta": {"hexsha": "21e7728ebf2c8843682826ba3485b26a59cd296b", "size": 2770, "ext": "r", "lang": "R", "max_stars_repo_path": "regression.r", "max_stars_repo_name": "caokefan/regression", "max_stars_repo_head_hexsha": "d178cb4552ce071e66cbdc9bcd4b382943098d3d", "max_stars_repo_licenses": ["BSD-2-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": "regression.r", "max_issues_repo_name": "caokefan/regression", "max_issues_repo_head_hexsha": "d178cb4552ce071e66cbdc9bcd4b382943098d3d", "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": "regression.r", "max_forks_repo_name": "caokefan/regression", "max_forks_repo_head_hexsha": "d178cb4552ce071e66cbdc9bcd4b382943098d3d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-11-25T10:44:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-28T04:11:39.000Z", "avg_line_length": 25.6481481481, "max_line_length": 78, "alphanum_fraction": 0.6097472924, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6824164129370544}} {"text": "=begin\n # sample-groebner01.rb\n\n require \"algebra\"\n P = MPolynomial(Rational, \"xyz\")\n x, y, z = P.vars(\"xyz\")\n f1 = x**2 + y**2 + z**2 -1\n f2 = x**2 + z**2 - y\n f3 = x - z\n p Groebner.basis([f1, f2, f3])\n #=> [x - z, y - 2z^2, z^4 + 1/2z^2 - 1/4]\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "6b85141a339e4d279a30c50385ce51fc6248d1b2", "size": 278, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-groebner01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-groebner01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-groebner01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 19.8571428571, "max_line_length": 43, "alphanum_fraction": 0.4928057554, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6823926156071585}} {"text": "## Functions\n\ndNt <- function(N0, r, K, Rclim, iter){\n N <- c()\n Nt <- N0\n for(i in 1:iter) { \n Nt <- Nt * exp(Rclim[i]) ## climate effect on growth rate \n Nt <- Nt + Nt*r*(1-Nt/K) #discrete logistic\n if (Nt < 1) {Nt <- 1}\n N <- c(N,Nt) #add result to vector\n }\n return(N)\n}\n\n\ndNtExtreme <- function(N0, r, K, Rclim, iter, severity){\n N <- c()\n Nt <- N0\n for(i in 1:iter) { \n severityPer <- severity/100 ## convert severity to percentage\n Nt <- ifelse(i == 20, Nt*severityPer, Nt)\n Nt <- Nt * exp(Rclim[i]) ## climate effect on growth rate \n Nt <- Nt + Nt*r*(1-Nt/K) #discrete logistic\n if (Nt < 1) {Nt <- 1}\n N <- c(N,Nt) #add result to vector\n }\n return(N)\n}", "meta": {"hexsha": "f88758b5f4220deb373fabd69d780b31eaec7a4e", "size": 738, "ext": "r", "lang": "R", "max_stars_repo_path": "ExtremeEventsSim/scripts/functions.r", "max_stars_repo_name": "afilazzola/ExtremeEventsPopulations", "max_stars_repo_head_hexsha": "345af728594c32f6c98cc047e28aa8a9089258f6", "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": "ExtremeEventsSim/scripts/functions.r", "max_issues_repo_name": "afilazzola/ExtremeEventsPopulations", "max_issues_repo_head_hexsha": "345af728594c32f6c98cc047e28aa8a9089258f6", "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": "ExtremeEventsSim/scripts/functions.r", "max_forks_repo_name": "afilazzola/ExtremeEventsPopulations", "max_forks_repo_head_hexsha": "345af728594c32f6c98cc047e28aa8a9089258f6", "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.3571428571, "max_line_length": 65, "alphanum_fraction": 0.5216802168, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6823203523985204}} {"text": "euclidean <- function(a, b) sqrt(sum((a - b) ^ 2))\n\nrectKernel <- function(dist) 0.5 * (abs(dist) <= 1)\ntrKernel <- function(dist) (1 - abs(dist)) * (abs(dist) <= 1)\nepKernel = function(dist) (3 / 4) * (1 - dist ^ 2) * (abs(dist) <= 1)\ngaussKernel = function(dist) dnorm(dist) * (abs(dist) <= 1)\n\nclassify <- function (dset, point, labels, potentials, h, dist = euclidean, kernel = trKernel) {\n distances <- apply(dset, 1, dist, point)\n \n weights <- potentials * kernel(distances / h)\n names(weights) <- labels\n \n classes <- unique(labels)\n classScores <- sapply(classes, function(class, w) sum(w[names(w) == class]), weights)\n \n if (length(unique(classScores)) == 1) {\n return(classes[sample(1:length(classes), 1)])\n }\n \n return (classes[which.max(classScores)])\n}\n\ncomputePotentials <- function (dset, labels, h, maxError) {\n dsetLength <- dim(dset)[1]\n potentials <- integer(dsetLength)\n \n errorCount <- maxError + 1\n while (errorCount > maxError) {\n repeat {\n randIndex <- sample(1:dsetLength, 1)\n tmpResult <- classify(dset, dset[randIndex,], labels, potentials, h)\n \n cat(\"\\rSearching...\", randIndex, labels[randIndex], tmpResult)\n \n if (tmpResult != paste(labels[randIndex])) {\n potentials[randIndex] <- potentials[randIndex] + 1\n break\n }\n }\n cat(\"\\n\")\n \n errorCount <- 0\n for (i in 1:dsetLength) {\n cat(\"\\rProcessing\", i, \"of\", dsetLength)\n tmpResult <- classify(dset, dset[i,], labels, potentials, h, kernel = epKernel)\n \n if (tmpResult != paste(labels[i])) {\n errorCount <- errorCount + 1\n }\n }\n cat(\"\\n\", errorCount, potentials, \"\\n\")\n }\n \n return (potentials)\n}\n\ncomputePotentials(iris[3:4], iris$Species, rep(1, 150), 5)\n\n\n# 4Tria: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n# 7Gaus: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0\n# 7Rect: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n# 4Epac: 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\n", "meta": {"hexsha": "57cc7f4131406f6c128957158bb138a535a751ab", "size": 3598, "ext": "r", "lang": "R", "max_stars_repo_path": "3 - Potential functions method/potential-functions.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "3 - Potential functions method/potential-functions.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "3 - Potential functions method/potential-functions.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": 54.5151515152, "max_line_length": 457, "alphanum_fraction": 0.4699833241, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6820408212582058}} {"text": "################################## INTERPOLACAO VIA TENSOR PRODUCT #################################\n\n#' Suavizacao De \\code{curvacolina} Por Produto Tensor De P-Splines\n#' \n#' Funcao interna executada quando \\code{metodo = \"tensorprod\"} em \\code{interpolador}\n#' \n#' Esta funcao nao deve ser chamada pelo usuario diretamente na maioria dos casos\n#' \n#' @param colina objeto \\code{curvacolina} retornado pelas funcoes de leitura\n#' @param ... parametros extras para configuracao do modelo estimado. Ver Detalhes em \n#' \\code{\\link{interpolador}}\n#' \n#' @return objeto da classe \\code{tensorprod} contendo a suavizacao da curva colina\n#' \n#' @importFrom mgcv gam te\n#' \n#' @export\n\ntensorprod <- function(colina, ...) {\n\n args <- list(...)\n\n if(is.null(args$bs)) BS <- \"ps\" else BS <- args$bs\n if(is.null(args$k)) K <- NA else K <- args$k\n\n mod <- gam(rend ~ te(hl, pot, k = K, bs = BS), data = colina$CC)\n\n new_tensorprod(mod, colina)\n}\n\nnew_tensorprod <- function(mod, colina) {\n obj <- list(superficie = mod, colina = colina)\n class(obj) <- c(\"tensorprod\", \"interpolador\")\n return(obj)\n}\n\n# METODOS ------------------------------------------------------------------------------------------\n\n#' @rdname getcolina\n\ngetcolina.tensorprod <- function(object) object$colina\n\n#' Amostragem De Pontos Na Suavizacao\n#' \n#' Amostra as coordenadas especificadas via \\code{pontos} na superficie suavizada\n#' \n#' @param object objeto da classe \\code{tensorprod} retornado pela funcao homonima\n#' @param pontos data.frame ou matriz contendo coordenadas \\code{(hl, pot)} dos pontos onde \n#' interpolar\n#' @param as.gradecolina booleano -- se \\code{FALSE} (padrao) retorna apenas o vetor de rendimentos\n#' interpolados nas coordenadas \\code{pontos}; se \\code{TRUE} um objeto \\code{gradecolina}. Veja\n#' \\code{\\link{gradecolina}}\n#' @param ... existe somente para consistencia de metodos. Nao possui utilidade\n#' \n#' @return se \\code{as.gradecolina = FALSE}, vetor de rendimentos interpolados, do contrario um \n#' objeto \\code{\\link{gradecolina}}\n#' \n#' @export\n\npredict.tensorprod <- function(object, pontos, as.gradecolina = FALSE, ...) {\n\n pontos <- pontos[complete.cases(pontos), ]\n\n if(nrow(pontos) == 0) return(numeric(0))\n\n pontos <- as.data.frame(pontos)\n\n rends <- unname(predict(object$superficie, newdata = pontos))\n\n if(as.gradecolina) {\n out <- new_gradecolina(pontos, rends, object)\n } else {\n out <- as.numeric(rends)\n }\n\n return(out)\n}", "meta": {"hexsha": "0d3acf0c2cb8ac8e8c22e2238db26ed35bf72657", "size": 2530, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mod-tensorprod.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/mod-tensorprod.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/mod-tensorprod.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": 32.8571428571, "max_line_length": 100, "alphanum_fraction": 0.6343873518, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6820272304619016}} {"text": "library(reshape2)\nlibrary(ggplot2)\n\n\nsir <- function(beta, gamma, N, S0, I0, R0, tf) {\n time <- 0\n S <- S0\n I <- I0\n R <- R0\n ta <- numeric(0)\n Sa <- numeric(0)\n Ia <- numeric(0)\n Ra <- numeric(0)\n while (time < tf) {\n ta <- c(ta, time)\n Sa <- c(Sa, S)\n Ia <- c(Ia, I)\n Ra <- c(Ra, R)\n pf1 <- beta * S * I\n pf2 <- gamma * I\n pf <- pf1 + pf2\n dt <- rexp(1, rate = pf)\n time <- time + dt\n if (time > tf) {\n break\n }\n ru <- runif(1)\n if (ru < (pf1/pf)) {\n S <- S - 1\n I <- I + 1\n } else {\n I <- I - 1\n R <- R + 1\n }\n if (I == 0) {\n break\n }\n }\n results <- data.frame(time = ta, S = Sa, I = Ia, R = Ra)\n return(results)\n}\n\nset.seed(42)\n\nsir_out <- sir(0.1/1000,0.05,1000,999,1,0,200)\n\nif(dim(sir_out)[1]==1){\n sir_out <- sir(0.1/1000,0.05,1000,999,1,0,200)\n}\n\nhead(sir_out)\n\nsir_out_long <- melt(sir_out,\"time\")\n\n# Plot\nggplot(sir_out_long,aes(x=time,y=value,colour=variable,group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\") + ylab(\"Number\")\n", "meta": {"hexsha": "5807a303f4eaad651caaa7b8b629a248edb443e8", "size": 1165, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_stochastic_models/continuous_t_sir/ssir.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "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": "models/simple_stochastic_models/continuous_t_sir/ssir.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "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": "models/simple_stochastic_models/continuous_t_sir/ssir.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 20.0862068966, "max_line_length": 73, "alphanum_fraction": 0.4420600858, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6819239635580097}} {"text": "\n## Illustration of Profile Likelihood Confidence Intervals and\n## comparison with Wald based CI.\n\n## From example(glm) (needs MASS to be present on the system)\ncounts <- c(18,17,15,20,10,20,25,13,12)\noutcome <- gl(3,1,9); treatment <- gl(3,3)\nglm.D93 <- glm(counts ~ outcome + treatment, family=poisson())\n\nglm.D93$coefficients\n\nconfint(glm.D93) # based on profile likelihood\nconfint.default(glm.D93) # based on asymptotic normality\n", "meta": {"hexsha": "1a1fffa5f53be0547e37ebe120e44a13746c2d88", "size": 436, "ext": "r", "lang": "R", "max_stars_repo_path": "_glm/MadsenThyregod-IMMDTU/GLM/R_examples_2012/week03/example_likel_CI.r", "max_stars_repo_name": "chrislangst/scalable-data-science", "max_stars_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2017-07-25T06:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:23:36.000Z", "max_issues_repo_path": "_glm/MadsenThyregod-IMMDTU/GLM/R_examples_2012/week03/example_likel_CI.r", "max_issues_repo_name": "chrislangst/scalable-data-science", "max_issues_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-08-17T13:45:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T09:06:53.000Z", "max_forks_repo_path": "_glm/MadsenThyregod-IMMDTU/GLM/R_examples_2012/week03/example_likel_CI.r", "max_forks_repo_name": "chrislangst/scalable-data-science", "max_forks_repo_head_hexsha": "c7beee15c7dd14d27353c4864d927c1b76cd2fa9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2017-08-18T17:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:30:51.000Z", "avg_line_length": 31.1428571429, "max_line_length": 62, "alphanum_fraction": 0.7293577982, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6819103362917301}} {"text": "#' Skew BB1 Copula Family\n#'\n#' Adds a skew parameter alpha in [0,1]. Distribution function is found by\n#' \\code{pbb1(u/u^alpha,v,cpar)*u^alpha}.\n#' @author Vincenzo Coia, Harry Joe\n#' @rdname bb1sk\n#' @export\npbb1sk=function(u,v,cparsk)\n{ alp=cparsk[3]\n cpar=cparsk[1:2]\n ua=u^alp\n cdf=pbb1(u/ua,v,cpar)*ua\n cdf\n}\n\n#' @rdname bb1sk\n#' @export\npcondbb1sk21=function(v,u,cparsk)\n{ alp=cparsk[3]\n cpar=cparsk[1:2]\n ua1=u^(1-alp)\n condcdf=(1-alp)*pcondbb1(v,ua1,cpar) + alp*pbb1(ua1,v,cpar)/ua1\n condcdf\n}\n\n#' @rdname bb1sk\n#' @export\npcondbb1sk <- pcondbb1sk21\n\n#' @rdname bb1sk\n#' @export\npcondbb1sk12=function(u,v,cparsk)\n{ alp=cparsk[3]\n cpar=cparsk[1:2]\n ua=u^alp\n condcdf=pcondbb1(u/ua,v,cpar)*ua\n condcdf\n}\n\n#' @rdname bb1sk\n#' @export\ndbb1sk=function(u,v,cparsk)\n{ alp=cparsk[3]\n cpar=cparsk[1:2]\n ua1=u^(1-alp)\n pdf=(1-alp)*dbb1(ua1,v,cpar) + alp*pcondbb1(ua1,v,cpar)/ua1\n pdf\n}\n\n\n", "meta": {"hexsha": "f708d8eaec2f43cef24a79a680611d7d51afdb95", "size": 903, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bb1sk.r", "max_stars_repo_name": "vincenzocoia/copsupp", "max_stars_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-29T23:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-29T23:25:20.000Z", "max_issues_repo_path": "R/bb1sk.r", "max_issues_repo_name": "vincenzocoia/copsupp", "max_issues_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "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/bb1sk.r", "max_forks_repo_name": "vincenzocoia/copsupp", "max_forks_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "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.7058823529, "max_line_length": 74, "alphanum_fraction": 0.6622369878, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6819103331413291}} {"text": "sigma_sq <- 20^2\nmu.antes <- 140\nmu.depois <- 120\nn <- 50\n\nset.seed(666)\nX <- rnorm(n, mean = mu.antes, sd = sqrt(sigma_sq))\nY <- rnorm(n, mean = mu.depois, sd = sqrt(sigma_sq))\n\nplot(X, Y, xlab = \"Pressão arterial antes (mmHg)\",\n ylab = \"Pressão arterial depois (mmHg)\")\n\nt.test(X, Y, paired = TRUE)", "meta": {"hexsha": "f993ff3b53900bf1e7d4feae0817f2b1f0e68bab", "size": 304, "ext": "r", "lang": "R", "max_stars_repo_path": "code/teste_t_pareado.r", "max_stars_repo_name": "jlduim/Statistical_Inference_BSc", "max_stars_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-08-03T15:42:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T15:43:10.000Z", "max_issues_repo_path": "code/teste_t_pareado.r", "max_issues_repo_name": "jlduim/Statistical_Inference_BSc", "max_issues_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-08-16T23:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-07T14:34:43.000Z", "max_forks_repo_path": "code/teste_t_pareado.r", "max_forks_repo_name": "jlduim/Statistical_Inference_BSc", "max_forks_repo_head_hexsha": "6dfa2441c0b09bfe39a68367a242a81d76c41778", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-08-13T00:53:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:35:56.000Z", "avg_line_length": 23.3846153846, "max_line_length": 52, "alphanum_fraction": 0.625, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6817296777318762}} {"text": "F <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))\nM <- function(n) ifelse(n == 0, 0, n - F(M(n-1)))\n", "meta": {"hexsha": "c467fa48a00bd2418c9998e7853603f99057a34b", "size": 100, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Mutual-recursion/R/mutual-recursion-1.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/Mutual-recursion/R/mutual-recursion-1.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/Mutual-recursion/R/mutual-recursion-1.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": 33.3333333333, "max_line_length": 49, "alphanum_fraction": 0.48, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6815996945895881}} {"text": "# Prior and proposal distributions for the parameter,\n# they are all uninformative.\n\npriorTheta <- function(x) {\n return(dnorm(x = x, mean = 1, sd = 500, log = TRUE))\n}\n\n\npriorRho <- function(x) {\n return(dnorm(x = x, mean = 1, sd = 500, log = TRUE))\n}\n\n\npriorDeltaD <- function(x) {\n if (x < 0 || x > 1) {\n return(-Inf)\n }\n return(dbeta(x = x, shape1 = 1, shape2 = 1, log = TRUE))\n}\n\n\npriorDeltaS <- function(x) {\n if (x < 0 || x > 1) {\n return(-Inf)\n }\n return(dbeta(x = x, shape1 = 1, shape2 = 1, log = TRUE))\n}\n\n\npriorLambda <- function(x) {\n if (x < 0 || x > 1) {\n return(-Inf)\n }\n return(dbeta(x = x, shape1 = 1, shape2 = 1, log = TRUE))\n}\n\n\npriorLambdaRight <- function(x) {\n if (x < 0 || x > 1) {\n return(-Inf)\n }\n return(dbeta(x = x, shape1 = 1, shape2 = 1, log = TRUE))\n}\n\n\npriorLambdaDisp <- function(x) {\n if (x < 0) {\n return(-Inf)\n }\n # 2 times since we truncate it at zero\n return(log(2) + dnorm(x = x, mean = 0, sd = 100, log = TRUE))\n}\n\n\nproposeTheta <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$Theta))\n}\n\n\nproposeRho <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$Rho))\n}\n\n\nproposeDeltaD <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$DeltaD))\n}\n\n\nproposeDeltaS <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$DeltaS))\n}\n\n\nproposeLambda <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$Lambda))\n}\n\n\nproposeLambdaRight <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$LambdaRight))\n}\n\n\nproposeLambdaDisp <- function(x = NA) {\n return(rnorm(1, mean = x, sd = proposeParameters$LambdaDisp))\n}\n", "meta": {"hexsha": "24b5e7ef15a1b25ea27d61efbe2f0fa989fe2752", "size": 1696, "ext": "r", "lang": "R", "max_stars_repo_path": "mapdamage/r/stats/priorPropose.r", "max_stars_repo_name": "ginolhac/mapDamage", "max_stars_repo_head_hexsha": "036806b434945594c2e642d03461c64e981507de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2015-03-11T21:29:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T16:01:52.000Z", "max_issues_repo_path": "mapdamage/r/stats/priorPropose.r", "max_issues_repo_name": "ginolhac/mapDamage", "max_issues_repo_head_hexsha": "036806b434945594c2e642d03461c64e981507de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2015-02-06T23:42:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T12:33:35.000Z", "max_forks_repo_path": "mapdamage/r/stats/priorPropose.r", "max_forks_repo_name": "ginolhac/mapDamage", "max_forks_repo_head_hexsha": "036806b434945594c2e642d03461c64e981507de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-07-04T11:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T21:16:47.000Z", "avg_line_length": 19.2727272727, "max_line_length": 64, "alphanum_fraction": 0.5990566038, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6815449104739056}} {"text": "## 1. Revisiting Common arithmetic operators ##\n\n47L + 476L\n3.20 / 4.99\n\n## 2. Dealing with Advanced Arithmetic Operators ##\n\n128 %/% 5\nFALSE\n\n## 3. Using Complex Arithmetic Expression ##\n\n10.50 * 200L\n21.15 * 50\n3.20 * 500\n10.50 * 200L + 21.15 * 50 + 3.20 * 500\n\n## 4. Dealing with Operator Priority Rules ##\n\n12.10 * 200L\n24.90 * 50L\n4.99 * 500L\n12.10 * 200L + 24.90 * 50L + 4.99 * 500L\n\n## 5. Identifying Expression's data type ##\n\n\"numeric\"\n\"numeric\"\n\"integer\"\n\n## 6. Dealing Variables with Naming rules ##\n\nq_0 <- FALSE\nq_1 <- FALSE\nq_2 <- TRUE\nq_3 <- FALSE\nq_4 <- FALSE\nq_5 <- FALSE\n\n## 7. Updating variables ##\n\ntotal_purchase_cost <- 10.50 * 200L + 21.15 * 50L + 3.20 * 500L\ntotal_selling_cost <- 12.10 * 200 + 24.90 * 50 + 4.99 * 500\nprofit_1 <- total_selling_cost - total_purchase_cost\n\n## 8. Identifying variables data type ##\n\nq_1 <- class(total_purchase_cost)\nq_2 <- class(total_selling_cost)\nq_3 <- class(profit_1)", "meta": {"hexsha": "592dc9c7219a82097d400470c29fd603d75e079b", "size": 928, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 1 - Introduction to R/1. Introduction to Data Analysis in R/2. Arithmetic Expressions and Variables in R.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 1 - Introduction to R/1. Introduction to Data Analysis in R/2. Arithmetic Expressions and Variables in R.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "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 Analyst in R/Step 1 - Introduction to R/1. Introduction to Data Analysis in R/2. Arithmetic Expressions and Variables in R.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 18.56, "max_line_length": 63, "alphanum_fraction": 0.6648706897, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6813385377229249}} {"text": "# This plots countours for bivariate density \n#x = random variable 1\n#y = random variable 2\n#cprob = vector of hpd values for contours; depending on how many values in cprob \n# determines the number of contour lines\n#alpha = the smoothing parameter for locfit; small numbers, more jaggedy; large numbers\n# more smooth.\n#xlim = the support limits of the density given as (xmin,ymin,xmax,ymax)\n#gxlim = the limits of the density that are actually plotted.\n#maxk = some number, the bigger it is the less likely locfit is to complain \n# (but makes it slower)\n\nloc2plot <- function(x,y,cprob=0.5,alpha=0.5,xlim,gxlim,maxk,...)\n{\n\tsc1 <- sqrt(var(x))\n\tsc2 <- sqrt(var(y))\n\tif(missing(maxk)) maxk <- 100\n\tif(missing(xlim)) fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\tmaxk=maxk,mint=100,cut=0.8,maxit=100)\n\telse fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\txlim=xlim,maxk=maxk,mint=100,cut=0.8,maxit=100)\n\tlev <- sort(fitted(fit))[floor(cprob*length(x))]\n\tplot(fit,lev=lev,m=100,label=paste(as.character(100*(1-cprob)),\"%\",sep=\"\"),\n\txlim=gxlim,...)\n}\n\n\n#like above, but allows for the points to be weighted - i.e. for output of ABC regression\nloc2plotw <- function(x,y,cprob=0.5,alpha=0.5,xlim,gxlim,wt,maxk,...)\n{\n\tsc1 <- sqrt(var(x))\n\tsc2 <- sqrt(var(y))\n\tif(missing(maxk)) maxk <- 100\n\tif(missing(xlim)) fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\tmaxk=maxk,mint=100,cut=0.8,maxit=100,weight=wt)\n\telse fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\txlim=xlim,maxk=maxk,mint=100,cut=0.8,maxit=100,weight=wt)\n\tlev <- sort(fitted(fit))[floor(cprob*length(x))]\n\tplot(fit,lev=lev,m=100,label=paste(as.character(100*(1-cprob)),\"%\",sep=\"\"),\n\txlim=gxlim,...)\n}\n\n#gives the HPD value for an observation px,py in a density constructed from x, y.\ngethpdprob2 <- function(x,y,px,py,alpha=0.5,xlim,gxlim,maxk,...)\n{\n\tsc1 <- sqrt(var(x))\n\tsc2 <- sqrt(var(y))\n\tif(missing(maxk)) maxk <- 100\n\tif(missing(xlim)) fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\tmaxk=maxk,mint=100,cut=0.8,maxit=100)\n\telse fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\txlim=xlim,maxk=maxk,mint=100,cut=0.8,maxit=100)\n#\td1 <- (x-px)^2+(y-py)^2\n#\tbest <- d1 == min(d1)\n#\tlev <- mean(fitted(fit)[best])\n#\tlev <- predict.locfit(fit,list(px,py)) #commented 2014-12-10\n\tlev <- predict(fit,list(px,py)) #added 2014-12-10\n\tslev <- sort(fitted(fit))\n\tindic <- slev <= lev\n\tsum(indic)/length(x)\n}\n\t\n\t\n# finds the mode for a bivariate density\n\nloc2mode <- function(x,y,alpha=0.5,xlim,maxk,...)\n{\n\tsc1 <- sqrt(var(x))\n\tsc2 <- sqrt(var(y))\n\tif(missing(maxk)) maxk <- 100\n\tif(missing(xlim)) fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\tmaxk=maxk,mint=100,cut=0.8,maxit=100)\n\telse fit <- locfit(~x+y,alpha=alpha,scale=c(sc1,sc2),\n\txlim=xlim,maxk=maxk,mint=100,cut=0.8,maxit=100)\n\ttt <- max(fitted(fit))\n\twt <- fitted(fit) == tt\n\tc(x[wt][1],y[wt][1])\n}\n\n\n# this works for univariate data; gives a vector with \n# mode (global), hpd1_low, hpd1_high, hpd2_low, hpd2_hi, etc\n#The reason for multiple hpd limits is if you have multimodal data. \n#prob = prob *outside* the limit; i.e for a normal distribution 0.05 is expected to give\n# the 0.025 and 0.975 quantiles.\n# this won't work for weighted data, use loc1statsx instead.\n# xlim is optional - use it to define the support of the density.\nloc1stats <- function(x,prob,alpha=0.5,xlim,...) \n{\n\tif(missing(xlim)){\n\t\tfit <- locfit(~x,alpha=alpha)\n\t}\n\telse {\n\t\tfit <- locfit(~x,alpha=alpha,xlim=xlim)\n\t}\n\tfx <- fitted(fit)\n\tx.modef <- max(fx)\n\tx.mode <- x[fx == x.modef]\n\tif(!missing(xlim)){\n\t\tif(predict(fit,xlim[1]) > x.modef){\n\t\t\tx.modef <- predict(fit,xlim[1])\n\t\t\tx.mode <- xlim[1]\n\t\t}\n\t\tif(predict(fit,xlim[2]) > x.modef){\n\t\t\tx.modef <- predict(fit,xlim[2])\n\t\t\tx.mode <- xlim[2]\n\t\t}\n\t}\n\t\t\n\tif(length(x.mode)>1)x.mode <- x.mode[1]\n\tlev <- sort(fx)[floor(prob*length(x))]\n#\tprint(\"log difference from max is \")\n#\tprint(log(x.modef)-log(lev))\n\tl1 <- list()\n\tl1[[1]] <- x.mode\n\tindx <- order(x)\n\tii <- 2\n\tflip <- TRUE\n\tfor(j in 2:length(x)){\n\t\tif(flip && fx[indx[j]] > lev){\n\t\t\tl1[[ii]] <- x[indx[j-1]]\n\t\t\tif(j==2 && !missing(xlim)){\n\t\t\t\tif(predict(fit,xlim[1]) >= lev)l1[[ii]] <- xlim[1]\n\t\t\t}\n\t\t\tflip <- FALSE\n\t\t\tii <- ii+1\n\t\t}\n\t\telse if(!flip && fx[indx[j]] < lev){\n\t\t\tl1[[ii]] <- x[indx[j]]\n\t\t\tflip <- TRUE\n\t\t\tii <- ii+1\n\t\t}\n\t\tif(!flip && !missing(xlim) && j == length(x)){\n\t\t\tl1[[ii]] <- xlim[2]\n\t\t\tflip <- TRUE\n\t\t}\n\t}\n\tif(!flip)stop(\"HPD interval not closed\")\n\tas.numeric(l1)\n}\n\n#this does the hpd calculation in a different way. Should give similar answers\n#to loc1stats. It is best to put xlim in directly. wt is a vector of weights and is optional.\n#numpoint is the number of points to do interpolation - the more the better\nloc1statsx <- function(x,prob,alpha=0.5,xlim,wt,numpoint=10000,...) \n{\n\tif(missing(xlim)){\n\t\tif(min(x) < 0)x.min <- 1.1*min(x)\n\t\telse x.min <- min(x)*0.9\n\t\tif(max(x) < 0)x.max <- 0.9*max(x)\n\t\telse x.max <- 1.1*max(x)\n\t\tprint(paste(\"putting in these xlimits from the data:\",x.min,x.max))\n\t\txlim <- c(x.min,x.max)\n\t}\n\n\tif(missing(wt))fit <- locfit(~x,alpha=alpha,xlim=xlim)\n\telse fit <- locfit(~x,alpha=alpha,xlim=xlim,weight=wt)\n\txx <- seq(xlim[1],xlim[2],len=numpoint)\n#\tyy <- predict.locfit(fit,xx) #commented 2014-12-10\n\tyy <- predict(fit,xx) #added 2014-12-10\n\tsum1 <- sum(yy)\n\tx.modef <- max(yy)\n\tx.mode <- xx[yy == x.modef]\n\tif(length(x.mode)>1)x.mode <- x.mode[1]\n\t\n\tyy2 <- sort(yy)\n\tpval <- 0\n\tfor(j in 1:numpoint){\n\t\tpval <- pval+yy2[j]/sum1\n\t\tif(pval > prob)break\n\t}\n\tlev <- yy2[j]\n#\tprint(\"log difference from max is \")\n#\tprint(log(x.modef)-log(lev))\n\tl1 <- list()\n\tl1[[1]] <- x.mode\n\tii <- 2\n\tflip <- TRUE\n\tfor(j in 2:length(xx)){\n\t\tif(flip && yy[j] > lev){\n\t\t\tl1[[ii]] <- xx[j-1]\n\t\t\tflip <- FALSE\n\t\t\tii <- ii+1\n\t\t}\n\t\telse if(!flip && yy[j] < lev){\n\t\t\tl1[[ii]] <- xx[j]\n\t\t\tflip <- TRUE\n\t\t\tii <- ii+1\n\t\t}\n\t\tif(!flip && j == length(xx)){\n\t\t\tl1[[ii]] <- xx[j]\n\t\t\tflip <- TRUE\n\t\t}\n\t}\n\tif(!flip)stop(\"HPD interval not closed\")\n\tas.numeric(l1)\n\n}\n\n#gives the HPD value for an observation px,in a univariate density constructed from x.\n#uses same method as loc1statsx, so need to specify xlim. wt is optional weight.\n#numpoint is the number of points to do interpolation - the more the better\ngethpdprob1 <- function(x,px,alpha=0.5,xlim,wt,numpoint=10000,...)\n{\n\n\tif(missing(wt))fit <- locfit(~x,alpha=alpha,xlim=xlim)\n\telse fit <- locfit(~x,alpha=alpha,xlim=xlim,weight=wt)\n\txx <- seq(xlim[1],xlim[2],len=numpoint)\n#\tyy <- predict.locfit(fit,xx) #commented 2014-12-10\n#\tlev <- predict.locfit(fit,px) #commented 2014-12-10\n\tyy <- predict(fit,xx) #added 2014-12-10\n\tlev <- predict(fit,px) #added 2014-12-10\n\tsum1 <- sum(yy)\n\n\tindic <- yy <= lev\n\tsum(yy[indic])/sum1\n}\n\n\n#given a function described by x,y points, this works like loc1stats.\n#uses spline interpolation between points.\n#numpoint is the number of points to do interpolation - the more the better\nlinestats <- function(x,y,prob,numpoint=10000)\n{\n\tn <- length(x)\n\tminval <- x[1]\n\tmaxval <- x[n]\n\t# This bit just guarantees that irrespective of what is \n\t# in x and y, we have numpoint *evenly* spaced (interpolated) points between\n\t# max and min\n\tres1 <- spline(x,y,numpoint,xmin=minval,xmax=maxval)\n\txx <- res1$x\n\tyy <- res1$y\n\tsum1 <- sum(yy)\n\tx.modef <- max(yy)\n\tx.mode <- xx[yy == x.modef]\n\tif(length(x.mode)>1)x.mode <- x.mode[1]\n\t\n\tyy2 <- sort(yy)\n\tpval <- 0\n\tfor(j in 1:numpoint){\n\t\tpval <- pval+yy2[j]/sum1\n\t\tif(pval > prob)break\n\t}\n\tlev <- yy2[j]\n#\tprint(\"log difference from max is \")\n#\tprint(log(x.modef)-log(lev))\n\tl1 <- list()\n\tl1[[1]] <- x.mode\n\tii <- 2\n\tflip <- TRUE\n\tfor(j in 2:length(xx)){\n\t\tif(flip && yy[j] > lev){\n\t\t\tl1[[ii]] <- xx[j-1]\n\t\t\tflip <- FALSE\n\t\t\tii <- ii+1\n\t\t}\n\t\telse if(!flip && yy[j] < lev){\n\t\t\tl1[[ii]] <- xx[j]\n\t\t\tflip <- TRUE\n\t\t\tii <- ii+1\n\t\t}\n\t\tif(!flip && j == length(xx)){\n\t\t\tl1[[ii]] <- xx[j]\n\t\t\tflip <- TRUE\n\t\t}\n\t}\n\tif(!flip)stop(\"HPD interval not closed\")\n\tas.numeric(l1)\n}\n\n", "meta": {"hexsha": "61f624f2f1b613bc597fd90c3d486f72c647fc8e", "size": 7892, "ext": "r", "lang": "R", "max_stars_repo_path": "practicals/practical4/bin/loc2plot_d.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/practical4/bin/loc2plot_d.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/practical4/bin/loc2plot_d.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": 29.0147058824, "max_line_length": 93, "alphanum_fraction": 0.6331728332, "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.681315729682528}} {"text": "=begin\n # sample-divmod01.rb\n\n require \"algebra\"\n P = MPolynomial(Rational)\n x, y, z = P.vars(\"xyz\")\n f = x**2*y + x*y**2 + y*2 + z**3\n g = x*y-z**3\n h = y*2-6*z\n \n P.set_ord(:lex) # lex, grlex, grevlex\n puts \"(#{f}).divmod([#{g}, #{h}]) =>\", \"#{f.divmod(g, h).inspect}\"\n #=> (x^2y + xy^2 + 2y + z^3).divmod([xy - z^3, 2y - 6z]) =>\n # [[x + y, 1/2z^3 + 1], xz^3 + 3z^4 + z^3 + 6z]\n # = [[Quotient1,Quotient2], Remainder]\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "62c4b305664ef863671bb6ae6b1992dd361b3633", "size": 460, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-divmod01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-divmod01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-divmod01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 25.5555555556, "max_line_length": 68, "alphanum_fraction": 0.4826086957, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6813152513969609}} {"text": "# Logistic Regression Classification for machine learning.\n# \n# In statistics, logistic regression, or logit regression, or logit model is a\n# regression model where the dependent variable (DV) is categorical. This project\n# covers the case of a binary dependent variable—that is, where it can take\n# only two values, \"0\" and \"1\", which represent outcomes such as pass/fail,\n# win/lose, alive/dead or healthy/sick.\n# \n# The binary Logistic regression model is an example of a qualitative\n# response/discrete choice model. It is used to estimate the probability of a\n# binary response based on one or more predictor (or independent) variables\n# (features).\n\n\n# Importing the data set\ndataset = read.csv('Social_Network_Ads.csv')\ndataset = dataset[, 3:5]\n\n# Splitting the Dataset into a Training set and a Test set\n# install.packages('caTools')\n# library(caTools)\nset.seed(123) # choose random number, only same number for debugging\nsplit = sample.split(dataset$Purchased, SplitRatio = 0.75)\ntraining_set = subset(dataset, split==TRUE)\ntest_set = subset(dataset, split==FALSE)\n\n\n# Feature scaling, normalize scale is important. Especially on algorithms \n# involving euclidian distance. Two main feature scaling formulas are:\n# Standardisation: x_stand = (x-mean(x))/(standard_deviation(x))\n# Normalisation: x_norm = (x-min(x))/(max(x)-min(x))\ntraining_set[, 1:2] = scale(training_set[, 1:2])\ntest_set[, 1:2] = scale(test_set[, 1:2])\n\n\n# Fitting the Logistic Regression Model to the training_set\nclassifier = glm(formula = Purchased ~ .,\n family = binomial,\n data = training_set)\n\n\n# Predict the test_set results by using the classifier\nprob_pred = predict(classifier, type = 'response',\n newdata = test_set[-3])\ny_pred = ifelse(prob_pred>0.5, 1, 0)\n\n\n# Making the Confusion Matrix\ncm = table(test_set[, 3], y_pred)\n\n\n# Plot the training_set results\n# install.packages('ElemStatLearn')\n# library(ElemStatLearn)\nset = training_set\nX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)\nX2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)\ngrid_set = expand.grid(X1, X2)\ncolnames(grid_set) = c('Age', 'EstimatedSalary')\nprob_set = predict(classifier, type = 'response', newdata = grid_set)\ny_grid = ifelse(prob_set>0.5, 1, 0)\nplot(set[, -3],\n main = 'Logistic Regression (Training set)',\n xlab = 'Age', ylab = 'Estimated Salary',\n xlim = range(X1), ylim = range(X2))\ncontour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)\npoints(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))\npoints(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))\n\n\n# Plot the test_set results\n# install.packages('ElemStatLearn')\n# library(ElemStatLearn)\nset = test_set\nX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)\nX2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)\ngrid_set = expand.grid(X1, X2)\ncolnames(grid_set) = c('Age', 'EstimatedSalary')\nprob_set = predict(classifier, type = 'response', newdata = grid_set)\ny_grid = ifelse(prob_set>0.5, 1, 0)\nplot(set[, -3],\n main = 'Logistic Regression (testing set)',\n xlab = 'Age', ylab = 'Estimated Salary',\n xlim = range(X1), ylim = range(X2))\ncontour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)\npoints(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))\npoints(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))\n\n\n\n \n \n \n", "meta": {"hexsha": "b52a7e1826d3ec362fc3e8690b575578ceff7da0", "size": 3463, "ext": "r", "lang": "R", "max_stars_repo_path": "Classification/LogisticRegression/regularLogisticRegression.r", "max_stars_repo_name": "a-holm/MachinelearningAlgorithms", "max_stars_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "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": "Classification/LogisticRegression/regularLogisticRegression.r", "max_issues_repo_name": "a-holm/MachinelearningAlgorithms", "max_issues_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-01T22:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T22:07:30.000Z", "max_forks_repo_path": "Classification/LogisticRegression/regularLogisticRegression.r", "max_forks_repo_name": "a-holm/MachinelearningAlgorithms", "max_forks_repo_head_hexsha": "a07cdddd079cd57ac77a17487a32c594e735baf8", "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.8404255319, "max_line_length": 81, "alphanum_fraction": 0.6820675715, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6808734227440209}} {"text": "x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\ny <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)\ncoef(lm(y ~ x + I(x^2)))\n", "meta": {"hexsha": "2a646e259f44c130576a6cb85f25e733ea86ef66", "size": 136, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Polynomial-regression/R/polynomial-regression-1.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/Polynomial-regression/R/polynomial-regression-1.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/Polynomial-regression/R/polynomial-regression-1.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": 34.0, "max_line_length": 55, "alphanum_fraction": 0.3823529412, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6808233536929934}} {"text": "\n.assign_kmeanspp <- function(x, K) {\n stopifnot(K >= 1)\n stopifnot(is.matrix(x))\n\n result <- list()\n result$k <- K\n\n center_ix <- rep(NA, K)\n center_ix[1] <- sample.int(nrow(x), 1)\n result$centers <- matrix(NA, K, ncol(x))\n result$centers[1,] <- x[center_ix[1],]\n\n if (K > 1) {\n for (i in 2:K) {\n min_dist_sq <- rep(NA, nrow(x))\n for (xi in 1:nrow(x)) {\n dist_sq <- rep(NA, i - 1)\n for (j in 1:(i - 1)) {\n dist_sq[j] <- sum((x[xi,] - result$centers[j,]) ^ 2)\n }\n min_dist_sq[xi] <- min(dist_sq)\n }\n\n total <- sum(min_dist_sq)\n center_ix[i] <- sample.int(nrow(x), 1, prob = min_dist_sq / total)\n result$centers[i,] <- x[center_ix[i],]\n }\n }\n \n result$weights <- matrix(0, nrow(x), K)\n \n for (xi in 1:nrow(x)) {\n dist_sq <- apply(result$centers, 1, function(v) { return(sum((x[xi,] - v) ^ 2)) })\n assign_ix <- which.min(dist_sq)\n result$weights[xi, assign_ix] <- 1\n }\n \n result$covariances <- list()\n result$component_weights <- rep(NA, result$k)\n for (ki in 1:result$k) {\n result$component_weights[ki] <- sum(result$weights[, ki]) / nrow(x)\n weighted <- cov.wt(x, result$weights[, ki])\n if (!is.null(result$min_cov)) {\n weighted$cov <- pmax(weighted$cov, result$min_cov)\n }\n result$covariances[[ki]] <- weighted$cov\n }\n \n return(result)\n}\n\n.mixture_expectation_step <- function(x, fit, truncated, tdist=F, tdistdf=3) {\n log_l <- matrix(NA, nrow(x), fit$k)\n for (ki in 1:fit$k) {\n if (tdist) {\n if (truncated) {\n log_l[, ki] <- tmvtnorm::dtmvt(x, fit$centers[ki,], fit$covariances[[ki]], tdistdf,\n lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = T) + log(fit$component_weights[ki])\n } else {\n log_l[, ki] <- mvtnorm::dmvt(x, fit$centers[ki,], fit$covariances[[ki]], tdistdf, log = T) + log(fit$component_weights[ki])\n }\n } else {\n if (truncated) {\n log_l[, ki] <- tmvtnorm::dtmvnorm(x, fit$centers[ki,], fit$covariances[[ki]],\n lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = T) + log(fit$component_weights[ki])\n } else {\n log_l[, ki] <- mvtnorm::dmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = T) + log(fit$component_weights[ki])\n }\n }\n }\n fit$logl <- sum(apply(log_l, 1, .logsum))\n \n fit$weights <- exp(log_l)\n total_weights <- apply(fit$weights, 1, sum)\n fit$weights <- fit$weights / total_weights\n \n return(fit)\n}\n\n.mixture_maximization_step <- function(x, fit, truncated) {\n fit$component_weights <- rep(NA, fit$k)\n for (ki in 1:fit$k) {\n fit$component_weights[ki] <- sum(fit$weights[, ki]) / nrow(x)\n weighted <- cov.wt(x, fit$weights[, ki])\n if (!is.null(fit$min_cov)) {\n weighted$cov <- pmax(weighted$cov, fit$min_cov)\n }\n \n if (truncated) {\n # Based on Lee and Scott 2012\n old_mu_k <- fit$centers[ki,]\n old_sigma_k <- fit$covariances[[ki]]\n correction <- tmvtnorm::mtmvnorm(sigma = old_sigma_k, lower=fit$bounds[,1] - old_mu_k, upper=fit$bounds[,2] - old_mu_k)\n \n # Make covariance matrices symmetric (numerical issue?)\n symmetric_correction <- (correction$tvar + t(correction$tvar))/2\n \n fit$centers[ki,] <- weighted$center - correction$tmean\n fit$covariances[[ki]] <- weighted$cov + old_sigma_k - symmetric_correction\n } else {\n fit$centers[ki,] <- weighted$center\n fit$covariances[[ki]] <- weighted$cov\n }\n }\n return(fit)\n}\n\n.fit.gmm.internal <- function(x, K, truncated, bounds, min_cov, epsilon, maxsteps, numkmeans=20, verbose, tdist, tdistdf = NA) {\n fit <- NULL\n \n for (j in 1:10) {\n if (verbose) {\n cat(\"Running k-means++..\\n\")\n }\n \n kmeansfits <- list()\n kmeansfits_logl <- rep(NA, numkmeans)\n for (i in 1:numkmeans) {\n fit <- .assign_kmeanspp(x, K)\n fit$bounds <- bounds\n fit$min_cov <- min_cov\n \n return_value <- try(fit <- .mixture_expectation_step(x, fit, truncated, tdist, tdistdf), silent = !verbose)\n if (inherits(return_value, \"try-error\")) {\n next\n }\n if (any(is.na(fit$weights))) {\n next\n }\n if (any(apply(fit$weights, 2, sum, na.rm=T) == 0)) {\n next\n }\n \n kmeansfits[[i]] <- fit\n kmeansfits_logl[i] <- fit$logl\n }\n \n if (sum(!is.na(kmeansfits_logl)) == 0) {\n warning(\"Could not find initial clustering with k-means++\")\n return(NULL)\n }\n \n best_initial_fit <- which.max(kmeansfits_logl)\n fit <- kmeansfits[[best_initial_fit]]\n \n if (verbose) {\n cat(\"Best k-means likelihood:\", kmeansfits_logl[best_initial_fit], \"\\n\")\n cat(\"Starting EM..\\n\")\n }\n \n fit <- .mixture_maximization_step(x, fit, truncated)\n \n previous_logl <- -Inf\n singular <- F\n converged <- F\n for (i in 1:maxsteps) {\n return_value <- try(fit <- .mixture_expectation_step(x, fit, truncated, tdist, tdistdf), silent = !verbose)\n if (inherits(return_value, \"try-error\")) {\n singular <- T\n break\n }\n \n if (any(is.na(fit$weights))) {\n singular <- T\n break\n }\n if (any(apply(fit$weights, 2, sum, na.rm=T) == 0)) {\n singular <- T\n break\n }\n \n if (verbose) {\n cat(\"Log likelihood: \", fit$logl, \"\\n\")\n }\n if (fit$logl < previous_logl) {\n # Uhhh, what?? Numerical issues maybe?\n converged <- T\n break;\n } else if (fit$logl - previous_logl < epsilon) {\n converged <- T\n break;\n } else {\n previous_logl <- fit$logl\n }\n \n fit <- .mixture_maximization_step(x, fit, truncated)\n }\n \n if (!singular) {\n break\n }\n }\n \n if (singular) {\n warning(\"singular solutions for 10 restarts\")\n return(NULL)\n } else {\n if (!converged) {\n warning(\"Solution not converged in\", maxsteps, \", returning optimal found solution\")\n }\n return(fit)\n }\n}\n\n#' Fit a Gaussian mixture with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Integer specifying the number of components of the Gaussian mixture.\n#' @param epsilon For the EM algorithm, stop when the difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned and a warning will be issued.\n#' @param verbose Display the fitting progress by showing the likelihood at every iteration.\n#' @export\nfit.gmm <- function(x, K, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n nparam <- K * (ncol(x) + ncol(x) * (ncol(x) + 1) / 2) + K - 1\n if (nparam >= nrow(x)) {\n warning(\"More parameters than samples, consider lowering K\")\n }\n \n fit <- .fit.gmm.internal(x, K, truncated = F, bounds = NA, min_cov = NULL, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose, tdist = F)\n if (is.null(fit)) {\n return(NULL)\n }\n \n result <- list()\n result$type <- \"gmm\"\n result$K <- K\n result$centers <- fit$centers\n result$covariances <- fit$covariances\n result$proportions <- fit$component_weights\n result$log_likelihood <- fit$logl\n result$AIC <- 2 * nparam - 2 * fit$logl\n result$BIC <- log(nrow(x)) * nparam - 2 * fit$logl\n #result$assignment <- apply(fit$weights, 1, which.max)\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Fit a transformed Gaussian mixture with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Integer specifying the number of components of the Gaussian mixture.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param epsilon For the EM algorithm, stop when the difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned and a warning will be issued.\n#' @param verbose Display the fitting progress by showing the likelihood at every iteration.\n#' @export\nfit.gmm.transformed <- function(x, K, bounds, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n result <- list()\n result$type <- \"gmm.transformed\"\n result$transform.bounds <- bounds\n transformed <- mvd.transform_to_unbounded(x, bounds)\n result$gmm <- fit.gmm(transformed, K, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose)\n if (is.null(result$gmm)) {\n return(NULL)\n }\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Fit a truncated Gaussian mixture with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Integer specifying the number of components of the Gaussian mixture.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param epsilon For the EM algorithm, stop when the difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned and a warning will be issued.\n#' @param verbose Display the fitting progress by showing the likelihood at every iteration.\n#' @export\nfit.gmm.truncated <- function(x, K, bounds = cbind(rep(-Inf, ncol(x)), rep(Inf, ncol(x))), min_cov = NULL, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n fit <- .fit.gmm.internal(x, K, truncated = T, bounds = bounds, min_cov = min_cov, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose, tdist = F)\n if (is.null(fit)) {\n return(NULL)\n }\n \n result <- list()\n result$type <- \"gmm.truncated\"\n result$K <- K\n result$centers <- fit$centers\n result$covariances <- fit$covariances\n result$proportions <- fit$component_weights\n result$bounds <- bounds\n result$log_likelihood <- fit$logl\n nparam <- K * ncol(x) * (ncol(x) + 1) / 2 + K\n result$AIC <- 2 * nparam - 2 * fit$logl\n result$BIC <- log(nrow(x)) * nparam - 2 * fit$logl\n result$assignment <- apply(fit$weights, 1, which.max)\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Fit a truncated t-distribution mixture with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Integer specifying the number of components of the mixture.\n#' @param df Degrees of freedom of the t-distrubtions.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param epsilon For the EM algorithm, stop when the difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned and a warning will be issued.\n#' @param verbose Display the fitting progress by showing the likelihood at every iteration.\n#' @export\nfit.tmixture.truncated <- function(x, K, df = 3, bounds = cbind(rep(-Inf, ncol(x)), rep(Inf, ncol(x))), min_cov = NULL, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n fit <- .fit.gmm.internal(x, K, truncated = T, bounds = bounds, min_cov = min_cov, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose, tdist = T, tdistdf = df)\n if (is.null(fit)) {\n return(NULL)\n }\n \n result <- list()\n result$type <- \"gmm.truncated\"\n result$K <- K\n result$centers <- fit$centers\n result$covariances <- fit$covariances\n result$proportions <- fit$component_weights\n result$bounds <- bounds\n result$log_likelihood <- fit$logl\n nparam <- K * ncol(x) * (ncol(x) + 1) / 2 + K\n result$AIC <- 2 * nparam - 2 * fit$logl\n result$BIC <- log(nrow(x)) * nparam - 2 * fit$logl\n result$assignment <- apply(fit$weights, 1, which.max)\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Calculate AIC of a Gaussian mixture across a range of number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Vector specifying the number of components to test\n#' @param optimal.only If TRUE, directly return only the GMM with optimal number of components; otherwise return a structure with fits for all tested number of components\n#' @param epsilon See fit.gmm\n#' @param maxsteps See fit.gmm\n#' @param verbose Display the fitting progress.\n#' @export\ngmm.AIC <- function(x, K = 1:6, optimal.only = F, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n result <- list()\n result$K <- K\n result$AIC <- rep(NA, length(K))\n result$fits <- list()\n for (k in 1:length(K)) {\n if (verbose) {\n cat(\"Fitting K=\", K[k], \"\\n\")\n }\n \n nparam <- K[k] * (ncol(x) + ncol(x) * (ncol(x) + 1) / 2) + K[k] - 1\n if (k > 1 && nparam >= nrow(x)) {\n result$fits[[k]] <- NULL\n result$AIC[k] <- NA\n } else {\n fit <- fit.gmm(x, K[k], epsilon = epsilon, maxsteps = maxsteps, verbose = verbose)\n if (!is.null(fit)) {\n result$fits[[k]] <- fit\n result$AIC[k] <- result$fits[[k]]$AIC\n }\n }\n }\n if (optimal.only) {\n if (sum(!is.na(result$AIC)) == 0) {\n return(NULL)\n } else {\n ix <- which.min(result$AIC)\n return(result$fits[[ix]])\n }\n } else {\n return(result)\n }\n}\n\n#' Calculate AIC of a transformed Gaussian mixture across a range of number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Vector specifying the number of components to test\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param optimal.only If TRUE, directly return only the GMM with optimal number of components; otherwise return a structure with fits for all tested number of components\n#' @param epsilon See fit.gmm.transformed\n#' @param maxsteps See fit.gmm.transformed\n#' @param verbose Display the fitting progress.\n#' @export\ngmm.transformed.AIC <- function(x, K = 1:6, bounds, optimal.only = F, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n result <- list()\n result$K <- K\n result$AIC <- rep(NA, length(K))\n result$fits <- list()\n for (k in 1:length(K)) {\n if (verbose) {\n cat(\"Fitting K=\", K[k], \"\\n\")\n }\n nparam <- K[k] * (ncol(x) + ncol(x) * (ncol(x) + 1) / 2) + K[k] - 1\n if (k > 1 && nparam >= nrow(x)) {\n result$fits[[k]] <- NULL\n result$AIC[k] <- NA\n } else {\n result$fits[[k]] <- fit.gmm.transformed(x, K[k], bounds, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose)\n if (!is.null(result$fits[[k]])) {\n result$AIC[k] <- result$fits[[k]]$gmm$AIC\n }\n }\n }\n if (optimal.only) {\n if (sum(!is.na(result$AIC)) == 0) {\n return(NULL)\n } else {\n ix <- which.min(result$AIC)\n return(result$fits[[ix]])\n }\n } else {\n return(result)\n }\n}\n\n#' Calculate AIC of a truncated Gaussian mixture across a range of number of components\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param K Vector specifying the number of components to test\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param optimal.only If TRUE, directly return only the GMM with optimal number of components; otherwise return a structure with fits for all tested number of components\n#' @param epsilon See fit.gmm.truncated\n#' @param maxsteps See fit.gmm.truncated\n#' @param verbose Display the fitting progress.\n#' @export\ngmm.truncated.AIC <- function(x, K = 1:6, bounds = cbind(rep(-Inf, ncol(x)), rep(Inf, ncol(x))), optimal.only = F, min_cov = NULL, epsilon = 1e-5, maxsteps = 1000, verbose = F) {\n result <- list()\n result$K <- K\n result$AIC <- rep(NA, length(K))\n result$fits <- list()\n for (k in 1:length(K)) {\n if (verbose) {\n cat(\"Fitting K=\", K[k], \"\\n\")\n }\n nparam <- K[k] * (ncol(x) + ncol(x) * (ncol(x) + 1) / 2) + K[k] - 1\n if (k > 1 && nparam >= nrow(x)) {\n result$fits[[k]] <- NULL\n result$AIC[k] <- NA\n } else {\n result$fits[[k]] <- fit.gmm.truncated(x, K[k], bounds = bounds, min_cov = min_cov, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose)\n if (!is.null(result$fits[[k]])) {\n result$AIC[k] <- result$fits[[k]]$AIC\n }\n }\n }\n if (optimal.only) {\n if (sum(!is.na(result$AIC)) == 0) {\n return(NULL)\n } else {\n ix <- which.min(result$AIC)\n return(result$fits[[ix]])\n }\n } else {\n return(result)\n }\n}\n", "meta": {"hexsha": "a2c746bdfa107602c5d2f176b5e26ca000f56773", "size": 16862, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gmm.r", "max_stars_repo_name": "bramthijssen/mvdens", "max_stars_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "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/gmm.r", "max_issues_repo_name": "bramthijssen/mvdens", "max_issues_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T12:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T12:45:03.000Z", "max_forks_repo_path": "R/gmm.r", "max_forks_repo_name": "NKI-CCB/mvdens", "max_forks_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "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.2229580574, "max_line_length": 178, "alphanum_fraction": 0.6217530542, "num_tokens": 4863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6807491211028306}} {"text": "#линейна регресия - проверява дали Y = Y1,..,Yn (вектор със стойности от извадка) се влияе от предиктори X = X1,..,Xn ... Z = Z1,..,Zn\n#функцията lm(y~x) или lm(y~x1+x2+x3+..+xn) за определяне на коефициентите на регресионната права при съответно един или няколко предиктора\n#функцията coefficients(lm(..)) изкарва много информация за регресията\n\n#Стъки при построяване на регресионен модел (трябва да проверим за всички тези неща и да отстраним предикторите, които създават проблеми):\n#1.Проверка дали някои от предикторите не са зависими помежду си -> с cor(), ако някоя стойност е много близка до 1 или -1, трябва да махнем една от величините или графично със scatterplot() (трябва да бъде заредена библиотеката car предварително library(\"car\"))\n#2.Проверка дали величините са нормално разпределени -> с qqnorm() и qqline() графично, ако някъде точките много се отдалечават от правата, значи величините не са норално разпределени и трябва да се махне от модела\n#3.Проверка за outlier-и -> с boxplot() графично, ако има точки много отгоре или отдолу трябва да бъдат махнати (тези редове да трябва да бъдат махнати от всички предиктори, ако работим с матрица със предиктори по стълбовете)\n#4.Построяване на регресионния моде -> lm(Y~X1+..+Xn); plot(Y); abline(lm(Y~X1+..+Xn)) трябва графично всички точки да са близо до правата\n#5.Заключение дали модела е добър и дали данните са добри -> със summary(lm(..)) се гледа дали предикторите са от голямо значение (броят на звездичките), колкото по-голяма е стойността на R-squared, толкова по-добър е модела\n#6.Може да се направи друг модел с други предиктори и да се провери кой е по-добър с anova\n\n\n#-----------------------------------------------------\n\n\n#01\nx=c(2,-6,7)\ny=c(3,4,6)\n\n#емпирично\nr=cor(x,y)\nsy=sd(y)\nsx=sd(x)\nb1=r*(sy)/sx\ny.cherta=mean(y)\nx.cherta=mean(x)\nb0=y.cherta - b1*x.cherta\n\n#теоретично\nb=lm(y~x)\n\nplot(x,y)\nabline(b)\n#abline(b0,b1)\n\n#02\nx=c(-2,-1,0,1,2)\ny=x*x\n\nplot(x,y)\nabline(lm(y~x))\nm1=lm(y~x)\ncov(x,y)\nsummary(m1)\n\nplot(x,y)\nabline(lm(y~I(x^2)))\nm2=lm(y~I(x^2))\nsummary(m2)\ncov(x^2,y)\n\n#03\nx=c(0,4,10,15,21,29,36,51,68)\ny=c(66.7,71,76.3,80.6,85.7,92.9,99.4,113.6,125.1)\nm=lm(y~x)\nplot(x,y)\nabline(m)\nsummary(m)\n\n#определете интервалите на параметрите на правата\nalpha= 0.05\nc=coefficients(summary(m))\nb0 = summary(m)$coefficients[1]\nse = summary(m)$coefficients[3]\nb1 = summary(m)$coefficients[2]\nse1 = summary(m)$coefficients[4]\n\nupper0 = b0 + qnorm(1-alpha/2)*se\nlower0 = b0 - qnorm(1-alpha/2)*se\n\nupper1 = b1 + qnorm(1-alpha/2)*se1\nlower1 = b1 - qnorm(1-alpha/2)*se1\n\n#04\nx=c(1.5, 1.7, 2.0, 2.5, 2.5, 2.7, 2.9, 3, 3.5, 3.4, 9.5, 9.5, 3.8, 4.2, 4.3, 4.6, 4, 5.1, 5.1, 5.1, 5.2, 5.5)\ny=c(3, 2.5, 3.5, 3, 3.1, 3.6, 3.2, 3.9, 4, 4, 8, 2.5, 4.2, 4.1, 4.8, 4.2, 5.1, 5.1, 5.1, 5.1, 4.8, 5.3)\nplot(x,y)\nm=lm(y~x)\nabline(m)\nsummary(m)\n\n#махаме outlier-ite\nboxplot(x,y)\nx.better=c(1.5, 1.7, 2.0, 2.5, 2.5, 2.7, 2.9, 3, 3.5, 3.4, 3.8, 4.2, 4.3, 4.6, 4, 5.1, 5.1, 5.1, 5.2, 5.5)\ny.better=c(3, 2.5, 3.5, 3, 3.1, 3.6, 3.2, 3.9, 4, 4, 4.2, 4.1, 4.8, 4.2, 5.1, 5.1, 5.1, 5.1, 4.8, 5.3)\nm.better = lm(y.better~x.better)\nplot(x.better,y.better)\nabline(m.better)\nsummary(m.better)\nrstandard(m.better) #???\n\n#05\nEr_red= 630.43\nEr_full = 615.62\np = 2;\nsfull=1.513\nfratio = (Er_red-Er_full)/(p*sfull^2)\nfratio\ndf(3.23,2,269)\n\n#06\n#install.packages(\"faraway\")\nlibrary(faraway)\n?savings\n#install.packages(\"car\")\nlibrary(car)\nscatterplotMatrix(savings)\nsavings\nx=lm(savings$sr~savings$pop75+savings$pop15+savings$dpi+savings$ddpi)\ny1=lm(savings$sr~savings$pop15+savings$dpi+savings$ddpi)\ny2=lm(savings$sr~savings$pop75+savings$pop15+savings$ddpi)\nsummary(y1)\nsummary(y2)\nsummary(x)\nanova(x)\nanova(y1)\nanova(y2)\npredict(y2,interval='confidence')\n", "meta": {"hexsha": "591192a16ef8817b7cb9c0cec9f9bd97fc2bbf9a", "size": 3701, "ext": "r", "lang": "R", "max_stars_repo_path": "week12-14.r", "max_stars_repo_name": "StelaN/Statistics-R", "max_stars_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-17T10:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T10:22:32.000Z", "max_issues_repo_path": "week12-14.r", "max_issues_repo_name": "StelaN/Statistics-R", "max_issues_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "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": "week12-14.r", "max_forks_repo_name": "StelaN/Statistics-R", "max_forks_repo_head_hexsha": "c8f49614bfdb6a294287fb06fac99dfcd558c3d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-06T13:38:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-06T13:38:34.000Z", "avg_line_length": 30.8416666667, "max_line_length": 262, "alphanum_fraction": 0.68332883, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6806340477282973}} {"text": "collatz.chain <- function(n) {\r\n chain <- vector()\r\n i <- 1\r\n while (n != 1) {\r\n if (n%%2 == 0)\r\n n <- n / 2\r\n else\r\n n <- 3 * n + 1\r\n chain[i] <- n\r\n i <- i + 1\r\n }\r\n return(chain)\r\n}\r\nanswer <- 0\r\ncollatz.max <- 0\r\nfor (n in 1:1E6) {\r\n collatz.length <- length(collatz.chain(n))\r\n if (collatz.length > collatz.max) {\r\n answer <- n\r\n collatz.max <- collatz.length\r\n }\r\n}\r\nprint(answer)", "meta": {"hexsha": "874706b1782d0093c461aca5e1e26b98411c7afb", "size": 470, "ext": "r", "lang": "R", "max_stars_repo_path": "DA_Assignment4.r", "max_stars_repo_name": "SADDAM-HUSSAIN-code/DA_LAB-ASSIGNMENTS-1-2-3-4-5-", "max_stars_repo_head_hexsha": "ba4b6bfcb699550c6d602f131d4c578a169f5d74", "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": "DA_Assignment4.r", "max_issues_repo_name": "SADDAM-HUSSAIN-code/DA_LAB-ASSIGNMENTS-1-2-3-4-5-", "max_issues_repo_head_hexsha": "ba4b6bfcb699550c6d602f131d4c578a169f5d74", "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": "DA_Assignment4.r", "max_forks_repo_name": "SADDAM-HUSSAIN-code/DA_LAB-ASSIGNMENTS-1-2-3-4-5-", "max_forks_repo_head_hexsha": "ba4b6bfcb699550c6d602f131d4c578a169f5d74", "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": 20.4347826087, "max_line_length": 47, "alphanum_fraction": 0.4340425532, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.6805866685056315}} {"text": "## Created on Saturday, December 12, 2020 at 9:33pm EST by WeekendEditor on WeekendEditorMachine.\n## Copyright (c) 2020, SomeWeekendReading. All rights reserved. As if you care.\n\nlibrary(\"plyr\") # For ddply()\ntoolsDir <- \"../../tools\" # Various tools available from author\nsource(file.path(toolsDir, \"graphics-tools.r\") # Various graphics hacks\n\n##\n## Re-estimate efficacy and confidence intervals on Pfizer vaccine data.\n##\n## See: https://www.fda.gov/media/144245/download, especially Table 8, p 26.\n##\n## Also analyzed by Gary Cornell:\n## https://garycornell.com/2020/12/09/statistics-in-the-pfizer-data-how-good-is-the-vaccine/\n##\n\ndoit <- function(plotDir = \"../images\",\n posteriorPlotFile = \"2020-12-12-pfizer-vaccine-efficacy-confidence-intervals-posterior-betas.png\") {\n\n efficacy <- function(Ntrt, Ntrtinf, Ncnt, Ncntinf) { # Vaccine efficacy point estimate\n 100.0 * (1 - (Ntrtinf / Ntrt) / (Ncntinf / Ncnt)) # 1 - Pr(inf | trt) / Pr(inf | control)\n } #\n\n efficacyQuantiles <- function(alphaNum, betaNum, alphaDenom, betaDenom,\n n = 1000, probs = c(0.025, 0.500, 0.975)) {\n round(quantile(100.0 * (1 - rbeta(n, alphaNum, betaNum) / rbeta(n, alphaDenom, betaDenom)),\n probs = probs), #\n digits = 1) #\n } #\n\n ## Create table of patient counts by treatment arm & infection status, then add\n ## a point estimate of the efficacy to compare with Pfizer:\n tbl <- transform(data.frame(Subgroup = c(\"Overall\", \"16-17\", \"18-64\", \"65-74\", \">= 75\"),\n Ntrt = c( 18559, 58, 14443, 3239, 805),\n Ntrtinf = c( 9, 0, 8, 1, 0),\n Ncnt = c( 18708, 61, 14566, 3255, 812),\n Ncntinf = c( 169, 1, 149, 14, 5)),\n Subgroup = factor(Subgroup,\n levels = c(\"Overall\", \"16-17\", \"18-64\", \"65-74\", \">= 75\")),\n VE = round(efficacy(Ntrt, Ntrtinf, Ncnt, Ncntinf), digits = 1))\n cat(sprintf(\"Age groups, patient counts, and point estimates of efficacy:\\n\"))\n print(tbl) # Show the data table\n\n ## Make plots of the posterior Beta distributions for the probability of infection in\n ## treatment and control arms, assuming a uniform prior. Do it for each age cohort.\n ps <- seq(from = 0.0, to = 0.05, length.out = 1000) # Values of p (horizontal axis)n\n f <- file.path(plotDir, posteriorPlotFile) # Plot destination pathname\n withPNG(f, 600, 1500, FALSE, function() { # Start file capture\n withPars(function() { # Save/restore graphics params\n ddply(tbl, \"Subgroup\", function(df) { # Do for each age cohort\n stopifnot(nrow(df) == 1) # 1 row only per age cohort\n with(df, {\n pinftrts <- dbeta(ps, shape1 = Ntrtinf + 1, shape2 = Ntrt - Ntrtinf + 1)\n pinftrtsMAP <- ps[which.max(pinftrts)]\n pinftrtsCL <- quantile(rbeta(1000, shape1 = Ntrtinf + 1, shape2 = Ntrt - Ntrtinf + 1),\n probs = c(0.025, 0.975))\n\n pinfcnts <- dbeta(ps, shape1 = Ncntinf + 1, shape2 = Ncnt - Ncntinf + 1)\n pinfcntsMAP <- ps[which.max(pinfcnts)]\n pinfcntsCL <- quantile(rbeta(1000, shape1 = Ncntinf + 1, shape2 = Ncnt - Ncntinf + 1),\n probs = c(0.025, 0.975))\n\n matplot(x = ps, y = cbind(pinftrts, pinfcnts),\n type = \"l\", lty = \"solid\", col = c(\"blue\", \"black\"),\n ylab = \"Density\", xlab = \"p\", main = sprintf(\"%s Cohort\", as.character(Subgroup)))\n legend(\"topright\", inset = 0.01, bg = \"antiquewhite\",\n col = c(\"blue\", \"black\"), lty = \"solid\",\n legend = c(sprintf(\"Treatment MAP: %.4f [%.4f - %.4f]\",\n pinftrtsMAP, pinftrtsCL[[1]], pinftrtsCL[[2]]),\n sprintf(\"Control MAP: %.4f [%.4f - %.4f]\",\n pinfcntsMAP, pinfcntsCL[[1]], pinfcntsCL[[2]])))\n abline(v = c(pinftrtsCL), col = \"blue\", lty = \"dashed\")\n abline(v = c(pinfcntsCL), col = \"black\", lty = \"dashed\")\n }) # Close with()\n NULL # So ddply() will return nothing of interest\n }) # Close ddply()\n }, pty = \"m\", # Maximal plotting area\n bg = \"transparent\", # Transparent background\n ps = 16, # Larger type size for file capture\n mgp = c(1.7, 0.5, 0), # Axis title, label, tick\n mar = c(3, 3, 2, 1), # Pull in on margins a bit\n mfrow = c(length(levels(tbl$\"Subgroup\")), 1)) # 1 column of plots for each age cohort\n }) # End file capture\n cat(sprintf(\"\\n\\nPosterior beta distributions plotted to %s.\", f))\n\n foo <- subset(ddply(tbl, \"Subgroup\", function(df) { # Numerically compute random ratios of\n stopifnot(nrow(df) == 1) # the Beta-distributed variables, and\n with(df, # then find the 2.5% & 97.5% quantiles\n efficacyQuantiles(Ntrtinf + 1, Ntrt - Ntrtinf + 1, Ncntinf + 1, Ncnt - Ncntinf + 1))\n }), select = c(\"Subgroup\", \"2.5%\", \"50%\", \"97.5%\")) # Also report the median, because why not\n tbl <- merge(tbl, foo, by = \"Subgroup\", sort = FALSE)# Join onto our magic table\n cat(\"\\n\\n\"); print(tbl) # Show the table\n\n cat(\"\\n\") # Final newline\n invisible(tbl) # Return data table, invisibly\n} #\n", "meta": {"hexsha": "55c5f50b5f30b9a7dab828a8656de20dc4519400", "size": 6351, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2020-12-12-pfizer-vaccine-efficacy-confidence-intervals-script.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/2020-12-12-pfizer-vaccine-efficacy-confidence-intervals-script.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/2020-12-12-pfizer-vaccine-efficacy-confidence-intervals-script.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": 65.4742268041, "max_line_length": 117, "alphanum_fraction": 0.4796095103, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6805651162974427}} {"text": "=begin\n # sample-splitting-field01.rb\n\n require \"algebra\"\n \n PQ = Polynomial(Rational, \"x\")\n x = PQ.var\n f = x**4 + 2\n p f #=> x^4 + 2\n field, modulus, facts = f.decompose\n p modulus #=> [a^4 + 2, b^2 + a^2]\n p facts #=> (x - a)(x + a)(x - b)(x + b)\n \n fp = Polynomial(field, \"x\")\n x = fp.var\n facts = Factors.new(facts.collect{|g, n| [g.evaluate(x), n]})\n p facts.pi == f.convert_to(fp) #=> true\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "893c3f58f02e91368bafc46918266492ca49b7dd", "size": 434, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-splitting-field01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-splitting-field01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-splitting-field01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 21.7, "max_line_length": 63, "alphanum_fraction": 0.5437788018, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381604, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6804258628438757}} {"text": "library(MFPCA)\r\n\r\nmfpca_train = function(multivar, argvals){\r\n \r\n # multivariate FPCA based on results from uPACE\r\n mFPCA = function(Xi, phi, p , L, I=I){\r\n \r\n # eigenanalysis on matrix M\r\n M = t(Xi)%*%Xi/(I-1)\r\n eigen.M = eigen(M)\r\n values = eigen.M$values\r\n pve = cumsum(values)/sum(values)\r\n Cms = eigen.M$vectors\r\n index = unlist(lapply(1:length(L), function(x) rep(x, L[x])))\r\n \r\n # MFPCA score\r\n rho = mfpca_score(Xi, Cms)\r\n \r\n # MFPCA eigenfunction\r\n psis = NULL\r\n for(j in 1:p){\r\n psi = NULL\r\n for(m in 1:dim(Cms)[2]){\r\n psi = cbind(psi, phi[[j]]%*%Cms[which(index==j),m])\r\n }\r\n psis[[j]] = psi\r\n }\r\n \r\n out = list(eigenvalue = values, Cms = Cms, pve = pve, rho = rho, psis=psis)\r\n return(out)\r\n } \r\n \r\n multivar = as.array(multivar)\r\n argvals = as.numeric(argvals)\r\n multivar = ifelse(multivar==0, NA, multivar)\r\n \r\n I = dim(multivar)[1]\r\n Q = dim(multivar)[3]\r\n \r\n # univariate FPCA via PACE\r\n Xi.train = L = phi.train = NULL\r\n for(p in 1:Q){\r\n tmp.ufpca = uPACE(multivar[,,p], argvals)\r\n Xi.train = cbind(Xi.train, tmp.ufpca$scores) # FPC scores\r\n L = c(L, dim(tmp.ufpca$scores)[2])\r\n phi.train[[p]] = t(tmp.ufpca$functions@X) # FPC eigenfunctions\r\n }\r\n\r\n # multivariate FPCA\r\n mFPCA.train = mFPCA(Xi=Xi.train, phi=phi.train, p=Q, L=L ,I=I)\r\n rho.train = mFPCA.train$rho #MFPC scores\r\n pve = mFPCA.train$pve\r\n Cms = mFPCA.train$Cms\r\n psis = mFPCA.train$psis\r\n psi = array(dim=c(Q,dim(psis[[1]])[1],dim(psis[[1]])[2]))\r\n for(p in 1:Q){\r\n psi[p,,] = psis[[p]]\r\n }\r\n \r\n return(list(\"scores\"=rho.train, \"Cms\"=Cms, \"psi\"=psi))\r\n}\r\n\r\n\r\nmfpca_test = function(multivar.train, multivar.test, argvals, Cms, psi){\r\n multivar.train = as.array(multivar.train)\r\n multivar.test = as.array(multivar.test)\r\n multivar.train = ifelse(multivar.train==0, NA, multivar.train)\r\n multivar.test = ifelse(multivar.test==0, NA, multivar.test)\r\n argvals = as.numeric(argvals)\r\n Q = dim(multivar.test)[3]\r\n \r\n # univariate FPC \r\n Xi.test = NULL\r\n meanf = NULL\r\n for(qq in 1:Q){\r\n tmp.ufpca = uPACE(multivar.train[,,qq], argvals, multivar.test[,,qq])\r\n Xi.test = cbind(Xi.test, tmp.ufpca$scores) # dynamic FPC scores for test subjects \r\n meanf[[qq]] = tmp.ufpca$mu@X\r\n }\r\n \r\n # estimate MFPC scores for test subjects\r\n rho.test = mfpca_score(Xi.test, Cms)\r\n long.pred = mfpca_pred(rho.test, meanf, psi)\r\n \r\n return(list(\"scores\"=rho.test, \"long_pred\"=long.pred))\r\n}\r\n\r\n\r\n\r\n# mfpc score calculation\r\nmfpca_score = function(predXi, Cms){\r\n rho = matrix(NA, nrow = nrow(predXi), ncol=dim(Cms)[2])\r\n for(i in 1:nrow(predXi)){\r\n for(m in 1:dim(Cms)[2]){\r\n rho[i,m] = predXi[i,]%*%Cms[,m]\r\n }\r\n }\r\n return(rho)\r\n}\r\n\r\n\r\n# mfpc trajectories prediction\r\nmfpca_pred = function(score, meanf, psi, n.rho=NULL){\r\n p = dim(psi)[1]\r\n n = nrow(score)\r\n \r\n if(is.null(n.rho)){\r\n n.rho = ncol(score)\r\n }\r\n \r\n out = NULL\r\n for(m in 1:p){\r\n out[[m]] = matrix(meanf[[m]], nrow=n, ncol=length(meanf[[m]]), byrow = T ) + score[,1:n.rho]%*%t(psi[m,,1:n.rho])\r\n }\r\n \r\n long.pred = array(data=NA, dim=c(dim(out[[1]])[1],dim(out[[1]])[2],p))\r\n for(m in 1:p){\r\n long.pred[,,m] = out[[m]]\r\n }\r\n return(long.pred)\r\n}\r\n\r\n\r\n# univariate FPCA via principal analysis by conditional estimation(PACE)\r\nuPACE = function(testData, domain, predData=NULL, nbasis = 5, pve = 0.99, npc = NULL){\r\n tmp = funData(domain, testData)\r\n if(is.null(predData)){\r\n tmp2 = NULL\r\n }else{\r\n tmp2 = funData(domain, predData)\r\n }\r\n res = PACE(tmp, tmp2, pve=pve, npc= npc, nbasis=nbasis)\r\n return(res)\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "2e90ed85d6139b4b33a1eda8ca443344d5bb6ddc", "size": 3959, "ext": "r", "lang": "R", "max_stars_repo_path": "Models/MFPCA_DeepSurv/MFPCA.r", "max_stars_repo_name": "reylined/TransformerJM", "max_stars_repo_head_hexsha": "1f551dd4f00c0b9c73bc93bf6f87450d4392fe34", "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": "Models/MFPCA_DeepSurv/MFPCA.r", "max_issues_repo_name": "reylined/TransformerJM", "max_issues_repo_head_hexsha": "1f551dd4f00c0b9c73bc93bf6f87450d4392fe34", "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": "Models/MFPCA_DeepSurv/MFPCA.r", "max_forks_repo_name": "reylined/TransformerJM", "max_forks_repo_head_hexsha": "1f551dd4f00c0b9c73bc93bf6f87450d4392fe34", "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.6884057971, "max_line_length": 122, "alphanum_fraction": 0.5407931296, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6804247536271717}} {"text": "library(gRain)\n\n\nF = cptable(~F, values=c(10,90),levels=val)\nC = cptable(~C|F, values=c(10,90,20,80),levels=val)\nE = cptable(~E|F, values=c(50,50,30,70),levels=val)\nA = cptable(~A|C, values=c(50,50,70,30),levels=val)\nD = cptable(~D|E, values=c(60,40,70,30),levels=val)\nB = cptable(~B|A:D, values=c(60,40,70,30,20,80,10,90),levels=val)\n\nplist = compileCPT(list(F,E,C,A,D,B))\nplist\n\nprint(plist$F)\nprint(plist$B)\n\njtree = grain(plist)\njtree\n\nquerygrain(jtree, nodes=c(\"F\"), type=\"marginal\")\nquerygrain(jtree, nodes=c(\"C\"), type=\"marginal\")\nquerygrain(jtree, nodes=c(\"B\"), type=\"marginal\")\nquerygrain(jtree, nodes=c(\"A\",\"B\"), type=\"joint\")\nquerygrain(jtree, nodes=c(\"A\",\"B\",\"C\"), type=\"joint\")\n\njtree2 = setEvidence(jtree, evidence=list(F=\"true\"))\nquerygrain(jtree, nodes=c(\"F\"), type=\"marginal\")\nquerygrain(jtree2, nodes=c(\"F\"), type=\"marginal\")\nquerygrain(jtree, nodes=c(\"A\"), type=\"marginal\")\nquerygrain(jtree2, nodes=c(\"A\"), type=\"marginal\")\nquerygrain(jtree, nodes=c(\"B\"), type=\"marginal\")\nquerygrain(jtree2, nodes=c(\"B\"), type=\"marginal\")\n\njtree3 = setEvidence(jtree, evidence=list(F=\"true\",A=\"false\"))\nquerygrain(jtree, nodes=c(\"C\"), type=\"marginal\")\nquerygrain(jtree2, nodes=c(\"C\"), type=\"marginal\")\nquerygrain(jtree3, nodes=c(\"C\"), type=\"marginal\")\n\n", "meta": {"hexsha": "e53f2f1ae3dcc38b6db1ee53a00b4252be75d4a6", "size": 1256, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 02/chapter2_2.r", "max_stars_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_stars_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-05-29T14:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:33.000Z", "max_issues_repo_path": "Chapter 02/chapter2_2.r", "max_issues_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_issues_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "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": "Chapter 02/chapter2_2.r", "max_forks_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_forks_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-05-25T10:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T06:08:58.000Z", "avg_line_length": 32.2051282051, "max_line_length": 65, "alphanum_fraction": 0.6799363057, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129515, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6803085931097441}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\n\r\nlibrary(forecast)\r\nlibrary(ggplot2)\r\nlibrary(seasonal)\r\nlibrary(seasonalview)\r\nlibrary(urca)\r\n\r\n#importar dados do hotel\r\ndados = read.csv(file.choose(),header = F)\r\nprint(dados)\r\nocupacao = ts(dados, start = c(2003,1), end = c(2017,12), frequency=12)\r\n\r\n#resumo\r\nsummary(ocupacao)\r\n\r\n#visualizar\r\nautoplot(ocupacao)\r\nhist(ocupacao)\r\nboxplot(ocupacao)\r\n\r\n#decompor\r\ndec = decompose(ocupacao)\r\nautoplot(dec)\r\n\r\n#analisar a tendência com mais cuidado\r\nautoplot(dec$trend)\r\nautoplot(window(dec$trend, start=c(2015,9)))\r\n\r\n#efeito sazonal por ano\r\nggseasonplot(ocupacao) \r\nggseasonplot(window(ocupacao, start=c(2016))) \r\n\r\n#teste de estacionariedade\r\nest = ur.kpss(ocupacao)\r\nprint(est)\r\nndiffs(ocupacao)\r\n\r\ntsdisplay(ocupacao)\r\n\r\nmodelo = auto.arima(ocupacao, trace = T,stepwise = F, approximation = F )\r\nprint(modelo)\r\n\r\ncheckresiduals(modelo)\r\n\r\nshapiro.test(modelo$residuals)\r\n\r\n#previsao para 2 anos\r\nprevisao = forecast(modelo,h=24)\r\n\r\nautoplot(previsao)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "779180958be5c85c12c531b976e2fc62606a732b", "size": 1062, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.1.Casopratico.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.1.Casopratico.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/11.1.Casopratico.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "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.75, "max_line_length": 74, "alphanum_fraction": 0.6996233522, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6802478149434369}} {"text": "rm(list = ls())\n\nn <- 50\nk <- 3\ny <- c(8, 14)\n\n\nmenosLogLikelihood <- function(theta, y, n) {\n p1 <- theta[1]\n p2 <- theta[2]\n l <- sum(y * log(theta)) + (n - sum(y)) * log(1 - sum(theta))\n return(-l)\n}\n\np.init <- c(0.3, 0.3)\nopt <- optim(p.init, menosLogLikelihood, y=y, n=n, hessian = TRUE)\n\n(emv <- opt$par)\nemv.value <- opt$value\n\ninfo.obs <- opt$hessian\n(v.hat <- solve(info.obs))\n\n(residual.standard <- sqrt(diag(v.hat)))\n\n\n# Hipothesis H0: p2 - 2p1 = 0\n\np.obs <- emv[2] - 2 * emv[1]\np.0 <- 0\n\n# WALD\n\nwald.var <- t(c(2, -1)) %*% v.hat %*% c(2, -1)\nwald.obs <- (p.obs - p.0) ^ 2 / wald.var\n(wald.pvalue <- 1 - pchisq(wald.obs, 1))\n\n# LIKELIHOOD RATIO\n\n# TODO\nlikeratio.obs <- 2 * 0 \n\n(likeratio.pvalue <- 1 - chisq(likeratio.obs, 1))\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f08b81bd5ed03efaf8db6e47898ba1ab163a4204", "size": 752, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/likelihood/exercise-06.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/likelihood/exercise-06.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/likelihood/exercise-06.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "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": 14.4615384615, "max_line_length": 66, "alphanum_fraction": 0.5518617021, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.6802190728066558}} {"text": "=begin\n # sample-algebraic-equation02.rb\n\n require \"algebra\"\n \n PQ = MPolynomial(Rational)\n a, b, c = PQ.vars(\"abc\")\n p AlgebraicEquation.minimal_polynomial(a + b + c, a**2-2, b**2-3, c**2-5)\n #=> x^8 - 40x^6 + 352x^4 - 960x^2 + 576\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "f505bd4966b503a6a4f477cccb0702340549cb54", "size": 262, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-algebraic-equation02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-algebraic-equation02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-algebraic-equation02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 21.8333333333, "max_line_length": 75, "alphanum_fraction": 0.6030534351, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6802190489053186}} {"text": "require(compiler)\nenableJIT(3)\n\nlibrary(MASS)\n\ngenerate_state_seq = function( seq_len = 10, states = c('A', 'B'), probs = matrix(NA, 2, 2), initial_state_pos=NA ) {\n\tret_seq = rep(0, seq_len)\n\trand_list = runif(seq_len)\n\tif (is.na(initial_state_pos)) { ret_seq[1]=sample.int(nrow(probs), 1) }\n\telse { ret_seq[1] = initial_state_pos }\n\tcum_prob = t(apply(probs, 1, cumsum))\n\tcum_prob[,nrow(cum_prob)] = 1 #Set the last column to 1 to avoid rounding errors\n\tfor (i in 2:seq_len){\n\t\t ret_seq[i] = 1+sum(cum_prob[ret_seq[i-1],] <= rand_list[i] )\n\t}\n\t# Could add code to replace the state_index with the state code (as.factor)\n\treturn(ret_seq)\n}\n\nrds.mcmc.props = function( S, weights=NULL, method=\"data.smoothing\")\n{\n\t# Returns the Fixed Vector (W) for Transition Probs when weights=NULL\n\t#\n\t# Variables to hold calculations\n\tif (is.null(dimnames(S)[[1]])) {\n\t\t dimnames(S)[1] = list(1:nrow(S))\n\t\t dimnames(S)[2] = list(1:nrow(S))\n\t}\n\t\n\tgroupNames = dimnames(S)[[1]]\n\tlen = length(groupNames)\n\t\n\t#print(len)\n\t\n \t#Generic Weighted MCMC Estimate\n\tif (len==2) {\t\n\t\t# Weighted Estimates of Equilibrium Proportions\n\t\t# P[A] = S[BA]*D[B]/ ( Sba*Db + Sab*Da )\n\t\tif (is.null(weights) ) { weights=rep(1,nrow(S)) }\n\t\tP.hat = rep(0 , len)\n\t\tfor (i in 1:len ) {\n\t\t\ta = i\n\t\t\tb = 3 - i\n\t\t\t\n\t\t\tP.hat[i] = S[groupNames[b],groupNames[a]]*weights[b] /\n\t\t\t(S[groupNames[b],groupNames[a]]*weights[b] + S[groupNames[a],groupNames[b]]*weights[a])\n\n\t\t}\t\t\n\t\t\t\n\t} else { # (groupCount > 2)\n\t\tP.hat = rep(NA , len)\n\t\tif (method==\"data.smoothing\") {\n\t\t\tif( is.null(weights) ) {\n\t\t\t\t#print(t(S))\n\t\t\t\t#print(diag(1,len,len))\n\t\t\t\tcoe = t(S) - diag(1,len,len)\n\t\t\t\tcoe[len,] = rep(1, len )\n\t\t\t\tb = c(rep(0,len-1),1)\n\t\t\t} else {\n\t\t\t\tcoe = matrix(rep(0,len^2),nrow=len)\n\t\t\t\tcoe[1:len] = c( weights[1] * S[1,] )\n\t\t\t\tdiag(coe) = c(-1*weights*S[,1])\n\t\t\t\tcoe[1,] = rep(1,len)\n\t\t\t\tb = c(1,rep(0,len-1))\n\t\t\t}\n\t\t\ttry((P.hat = solve( coe , b )))\n\t\t}\n\t\tif (method==\"least.squares\") {\n\t\t\tstop(\"*** Unimplemented Method ***\")\n\t\t}\n\t\n\t}\n\tnames(P.hat) = groupNames\n\tP.hat[which(P.hat<=0)]=0\n\t#P.hat[which(is.na(P.hat))]=0\t\n\tP.hat\n}\n\nfundamental_matrix = function( trans_matrix ) {\n\t# Calculate the fundamental matrix of transition matrix\n\t# Z = (I-P+W)^-1\n\tW = matrix(rep(rds.mcmc.props(trans_matrix), nrow(trans_matrix)), nrow=nrow(trans_matrix), ncol=nrow(trans_matrix), byrow=TRUE)\n\tz_inv = diag(x=1, nrow=nrow(trans_matrix), ncol=nrow(trans_matrix) ) - trans_matrix + W\n\t\n\treturn( ginv(z_inv) )\n}\n\n#asym_mean_count = n*w_j where n is sample size\nasym_var_count = function(probs) {\n\tw = rds.mcmc.props(probs)\n\tz = fundamental_matrix(probs)\n\treturn( 2* (w*diag(z)) - w - w^2 )\n}\n\n# Generate a bootstrapped CI for estimate (no variance in transition probs)\nsimple_bs = function(S, degree_weights_lists, trials=100, one_tail_alpha=.025 ) {\n\tbs_results = matrix(nrow=trials, ncol=ncol(S))\n\tsample_size = length(unlist(degree_weights_lists))\n\tbs_mean_deg = unlist(lapply(lapply(degree_weights_lists, mean), '^', -1))\n\toverall_mean = mean(bs_mean_deg)\n\n\tstate_count = nrow(S) \n\t#print(bs_results)\n\t#print(sample_size)\n\t#print(bs_mean_deg)\n\t\n\tfor (j in 1:trials) {\n\t\t#Bootstrap a sample composition and transition probs\n\t\tbs_sample = generate_state_seq(seq_len=sample_size, probs=S)\t\t\n\t\t\n\t\trec = matrix(0, state_count, state_count)\n\t\tfor (i in 2:length(bs_sample)) {\n\t\t\trec[bs_sample[i-1], bs_sample[i]] = rec[bs_sample[i-1], bs_sample[i]]+1\n\t\t}\n\t\t\n\t\tbs.props = prop.table(rec, 1)\n\t\tbs.cnum = as.vector(table( factor(bs_sample, levels=c(1:state_count) ) ))\n\t\t#print(bs.cnum)\n\t\t\n\t\t#Bootstrap a degree for each group, based on the bootstrapped sample composition \n\t\tfor (i in 1:length(bs_mean_deg)){\n\t\t\tif (bs.cnum[i]>=1) {\n\t\t\t\tbs_mean_deg[i] = bs.cnum[i] / sum( sample(degree_weights_lists[[i]], size=bs.cnum[i], replace=TRUE) )\n\t\t\t} else {\n\t\t\t\tbs_mean_deg[i] = overall_mean\n\t\t\t}\n\t\t}\n\t\t\n\t\tbs_results[j,] = unlist(rds.mcmc.props(bs.props, bs_mean_deg))\n\t}\n\t#print(bs_results)\n\tbs_ci = as.vector(apply( bs_results, 2, quantile, c(one_tail_alpha, 1-one_tail_alpha), na.rm=TRUE))\n\t\n\treturn(bs_ci)\n}\n\n# Generate a bootstrapped CI for estimate (with variance in transition probs)\ntrans_var_bs = function(S, degree_weights_lists, trials=100, one_tail_alpha=.025, fudge=1) {\n\tbs_results = matrix(nrow=trials, ncol=ncol(S))\n\tsample_size = length(unlist(degree_weights_lists))\n\tbs_mean_deg = unlist(lapply(lapply(degree_weights_lists, mean), '^', -1))\n\toverall_mean = mean(bs_mean_deg)\n\tstate_count = nrow(S) \n\t#print(bs_results)\n\t#print(sample_size)\n\t#print(bs_mean_deg)\n\t\n\t\n\texpected_sd = apply(S, c(1,2), function(x) sqrt(x*(1-x)/(sample_size/fudge)) )\n\t\n\t\n\tfor (j in 1:trials) {\n\t\t# Add some variation in the S matrix\n\t\t# Create some noise using expected sd\n\t\tnoise = apply(expected_sd, c(1,2), function(x) rnorm(1, sd=x))\n\t\t\n\t\t#if (FALSE) {\n\t\t\t## Correct for dependence of proportions \n\t\t\t## Might only work for 2 states, non-zero recruitment\n\t\t\tnoise[,state_count] = noise[,1:(state_count-1)]*-1\n\t\t\t\n\t\t\t# Re-normalize S after applying noise\n\t\t\tS_noise = S+noise\n\t\t\tS_noise[S_noise<0] = 0 \n\t\t#}\n\t\t\n\t\t\n\t\tS_p = prop.table(S+noise, 1)\n\t\t\n\t\t#Bootstrap a sample composition and transition probs\n\t\tbs_sample = generate_state_seq(seq_len=sample_size, probs=S_p)\t\t\n\t\t\n\t\trec = matrix(0, state_count, state_count)\n\t\tfor (i in 2:length(bs_sample)) {\n\t\t\trec[bs_sample[i-1], bs_sample[i]] = rec[bs_sample[i-1], bs_sample[i]]+1\n\t\t}\n\t\t\n\t\tbs.props = prop.table(rec, 1)\n\t\tbs.cnum = as.vector(table( factor(bs_sample, levels=c(1:state_count) ) ))\n\t\t#print(bs.props)\n\t\t#print(bs.cnum)\n\t\t\n\t\t#Bootstrap a degree for each group, based on the bootstrapped sample composition \n\t\tfor (i in 1:length(bs_mean_deg)){\n\t\t\tif (bs.cnum[i]>=1) {\n\t\t\t\tbs_mean_deg[i] = bs.cnum[i] / sum( sample(degree_weights_lists[[i]], size=bs.cnum[i], replace=TRUE) )\n\t\t\t} else {\n\t\t\t\tbs_mean_deg[i] = overall_mean\n\t\t\t}\n\t\t}\n\t\tbs_results[j,] = unlist(rds.mcmc.props(bs.props, bs_mean_deg))\n\t}\n\t#print(bs_results)\n\tbs_ci = as.vector(apply( bs_results, 2, quantile, c(one_tail_alpha, 1-one_tail_alpha), na.rm=TRUE))\n\t\n\treturn(bs_ci)\n}\n\nsimple_wts_bs = function(vals_list, weights_list, trials=100, one_tail_alpha=.025 ) {\t\n\tbs_results = matrix(nrow=trials, ncol=ncol(S))\n\tsample_size = length(weights_list)\n\tstate_count = length( unique(vals_list) ) \n\tstates = sort(unique(vals_list)) \n\tfor (j in 1:trials) {\n\t\t#Bootstrap a sample \n\t\tbs_sample = sample(vals_list, size=sample_size, replace=TRUE , prob=weights_list )\t\n\n\t\tbs_results[j,] = prop.table( table(factor(bs_sample, levels=states)) )\n\t}\n\tbs_ci = as.vector(apply( bs_results, 2, quantile, c(one_tail_alpha, 1-one_tail_alpha), na.rm=TRUE))\n\t\n\treturn(bs_ci)\n}\n\nvar_wts_bs = function(vals_list, rc_weights_list, dc_weights_list, trials=100, one_tail_alpha=.025 ) {\t\n\tbs_results = matrix(nrow=trials, ncol=ncol(S))\n\tsample_size = length(weights_list)\n\tstates = sort(unique(vals_list))\n state_count = length( states ) \n\t\n\t# use vals to partition weights list and get a distribution for each unique val\n\trc_lists = list()\n\tdc_lists - list()\n\t\n\tfor (i in state_count) {\n\t\tbool_membership = vals_list==state[i]\n\t\trc_lists[[i]] = rc_weights_list[ bool_membership ]\n\t\tdc_lists[[i]] = dc_weights_list[ bool_membership ]\t\n\t}\n\t\n\t#For each trial\n\t# permute the weights list within groups\n\t\n\tfor (j in 1:trials) {\n\t\t#Bootstrap a sample \n\t\tbs_sample = sample(vals_list, size=sample_size, replace=TRUE , prob=weights_list )\t\n\n\t\tbs_results[j,] = prop.table( table(factor(bs_sample, levels=states)) )\n\t}\n\tbs_ci = as.vector(apply( bs_results, 2, quantile, c(one_tail_alpha, 1-one_tail_alpha), na.rm=TRUE))\n\t\n\treturn(bs_ci)\n}\n\n# Generate a bootstrapped CI for estimate (with variance in transition probs)\ntwo_step_trans_var_bs = function(S, degree_weights_lists, trials=100, one_tail_alpha=.05) {\n\tbs_results = matrix(nrow=trials, ncol=ncol(S))\n\tsample_size = length(unlist(degree_weights_lists))\n\tbs_mean_deg = unlist(lapply(lapply(degree_weights_lists, mean), '^', -1))\n\tstate_count = nrow(S) \n\t#print(bs_results)\n\t#print(sample_size)\n\t#print(bs_mean_deg)\n\t\n\t\n\t#Generate a set of draws for n_i and n_ij\n\tw = rds.mcmc.props(S)\n\tasym_var = asym_var_count(probs)\n\t\n\t# random permutations of the transition matrix S\n\tS_p = replicate(trials, S) # random permutations of the transition matrix S\n\tbs_mean_deg_replicates = replicate(trials, bs_mean_deg)\n\t\n\t\n\t# Populate the permutations\n\tfor (i in 1:nrow(S)) {\n\t\t# Sample the number of each state in sample\n\t\tn_sub_i = round(rnorm(trials, sd=sqrt(asym_var[i] * sample_size))+ sample_size*w[i])\n\t\t\n\t\t# Sample the mean degree for each state group\n\t\tbs_mean_deg_replicates[i,] = sapply( n_sub_i, function(x) x / sum( sample(degree_weights_lists[[i]], size=x, replace=TRUE) ) )\n\n\t\t# Sample the transitions from each group ( n_ij, then calculate permuted transitions S )\n\t\tS_p[i,,] = prop.table(sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=S[i,] )), 2)\n\t}\n\thead(bs_mean_deg_replicates)\n\thead(S_p)\n\t\n\tfor (j in 1:trials) {\n\t\tbs_results[j,] = rds.mcmc.props(S_p[,,j], bs_mean_deg_replicates[,j])\n\t}\n\t#print(bs_results)\n\tbs_ci = as.vector(apply( bs_results, 2, quantile, c(one_tail_alpha, 1-one_tail_alpha), na.rm=TRUE))\n\t\n\treturn(bs_ci)\n}\n\n\nsim_transition_probs = function(num_trials, sample_size, probs ) {\n\t# We think the variance for resampled markov chains should be p*(1-p)/n_i when n_i is fixed\n\t# Need to test that theory with MCMC samples\n\tresults = list()\n\t\n\tfor(k in 1:nrow(probs)) {\n\t\tresults[[k]] = matrix(data=NA, nrow=num_trials, ncol=ncol(probs))\n\t}\n\t\n\t\n\tfor (trial in 1:num_trials ) {\n\t\t#Generate State Sequence\n\t\tfoo = generate_state_seq(sample_size, probs=probs)\n\t\t\n\t\tstate_count = length(unique(foo))\n\t\trec = matrix(0, state_count, state_count)\n\t\t\n\t\tfor (i in 2:length(foo)) {\n\t\t\trec[foo[i-1], foo[i]] = rec[foo[i-1], foo[i]]+1\n\t\t}\n\t\t\n\t\tS = prop.table(rec, 1)\n\t\t\n\t\tfor(k in 1:nrow(probs)) {\n\t\t results[[k]][trial,] = S[k,]\n\t }\n\t\n\t}\n\tresults_list = lapply(results,function(x) apply(x, 2, var)) \n\treturn( matrix(unlist(results_list), nrow=nrow(probs), ncol=ncol(probs), byrow=TRUE))\t\n}\n\nsim_transition_probs_mean = function(num_trials, sample_size, probs ) {\n\t# We think the variance for resampled markov chains should be p*(1-p)/n_i when n_i is fixed\n\t# Need to test that theory with MCMC samples\n\tresults = list()\n\t\n\tfor(k in 1:nrow(probs)) {\n\t\tresults[[k]] = matrix(data=NA, nrow=num_trials, ncol=ncol(probs))\n\t}\n\t\n\t\n\tfor (trial in 1:num_trials ) {\n\t\t#Generate State Sequence\n\t\tfoo = generate_state_seq(sample_size, probs=probs)\n\t\t\n\t\tstate_count = length(unique(foo))\n\t\trec = matrix(0, state_count, state_count)\n\t\t\n\t\tfor (i in 2:length(foo)) {\n\t\t\trec[foo[i-1], foo[i]] = rec[foo[i-1], foo[i]]+1\n\t\t}\n\t\t\n\t\tS = prop.table(rec, 1)\n\t\t\n\t\tfor(k in 1:nrow(probs)) {\n\t\t results[[k]][trial,] = S[k,]\n\t }\n\t\n\t}\n\tresults_list = lapply(results,function(x) apply(x, 2, mean)) \n\treturn( matrix(unlist(results_list), nrow=nrow(probs), ncol=ncol(probs), byrow=TRUE))\t\n}\n\nsim_state_count = function(num_trials, sample_size, probs ) {\n\t# We think the variance for resampled markov chains should be p*(1-p)/n_i when n_i is fixed\n\t# Need to test that theory with MCMC samples\n\t\n\tresults = matrix(data=NA, nrow=num_trials, ncol=ncol(probs))\n\n\tfor (trial in 1:num_trials ) {\n\t\t#Generate State Sequence\n\t\tfoo = generate_state_seq(sample_size, probs=probs)\n\t\t\n\t\tstate_count = length(unique(foo))\n\t\trec = matrix(0, state_count, state_count)\n\t\t\n\t\tfor (i in 2:length(foo)) {\n\t\t\trec[foo[i-1], foo[i]] = rec[foo[i-1], foo[i]]+1\n\t\t}\n\t\t\n\t\tS = rowSums(rec)\n\t\t\n\t\tresults[trial,] = S\n\t\n\t}\n\t\n\treturn( apply(results, 2, var) )\n\t\n}\n\ntwo_step_var_est = function(num_replications, sample_size, probs) {\n\tw = rds.mcmc.props(probs)\n\tresults = matrix(NA,nrow=nrow(probs), ncol=nrow(probs))\n\tasym_var = asym_var_count(probs)\n\t\n\tfor (i in 1:nrow(probs)) {\n\t\t\tn_sub_i = round(rnorm(num_replications, sd=sqrt(asym_var[i] * sample_size))+ sample_size*w[i])\n\t\t\tresults[i,] = apply(prop.table(sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=probs[i,] )), 2), 1, var )\n\t}\n\treturn(results)\n}\n\ntwo_step_var_est_const_sample_size = function(num_replications, sample_size, probs) {\n\t#This version holds sample size constant by setting the size of the last group as a function of \n\t# the other groups. Might still produce large samples if the first n-1 groups get large draws\n\tw = rds.mcmc.props(probs)\n\tresults = matrix(NA,nrow=nrow(probs), ncol=nrow(probs))\n\tasym_var = asym_var_count(probs)\n\n\tn_sub = matrix(0,nrow=nrow(probs),ncol=num_replications)\n\tfor (i in 1:nrow(probs)) {\n\t\tif(i==nrow(probs)){\n\t\t\tn_sub[i,] = apply(n_sub, 2, function(x) max(0, sample_size-sum(x)))\n\t\t} else {\n\t\t n_sub[i,] = round(rnorm(num_replications, sd=sqrt(asym_var[i] * sample_size))+ sample_size*w[i])\n\t\t}\n\t\tresults[i,] = apply(prop.table(sapply(n_sub[i,], function(x) rmultinom(1, size=x, prob=probs[i,] )), 2), 1, var )\n\t}\t\n\treturn(results)\n}\n\ntwo_step_mean_est = function(num_replications, sample_size, probs) {\n\tw = rds.mcmc.props(probs)\n\tresults = matrix(NA,nrow=nrow(probs), ncol=nrow(probs))\n\tasym_var = asym_var_count(probs)\n\t\n\tfor (i in 1:nrow(probs)) {\n\t\t\tn_sub_i = round(rnorm(num_replications, sd=sqrt(asym_var[i] * sample_size))+ sample_size*w[i])\n\t\t\tresults[i,] = apply(prop.table(sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=probs[i,] )), 2), 1, mean )\n\t}\n\treturn(results)\n}\n\n\n\nrun_interactive = function() {\n# --------------------------------------------------------------------------------------------\n# ---- this code is protected by the function -------------------------------\n# --------------------------------------------------------------------------------------------\n\ndegree_listA = c( 350, 150, 100, 300, 700, 200, 200, 300, 300, 200, 100, 400, 200, 150, 100, 200, 50, 500, 30, 500, 500, 25, 150, 50, 500, 150, 300, 250, 400, 250, 100, 200, 100, 150, 150, 60, 500, 100, 200, 200, 150, 20, 200, 500, 100, 700, 300, 200, 500, 125, 500, 250, 100, 200, 30, 150, 400, 100, 100, 100, 200, 100, 250, 50, 60, 100, 150, 500, 200, 200, 100, 100, 100, 150, 70, 400, 25, 50, 200, 300, 250, 50, 200, 100, 500, 150, 600, 100, 500, 150, 200, 300, 200, 150, 300, 100, 500, 200, 200, 100, 125, 50, 500, 50, 200, 500, 500, 300, 200, 100, 70, 300, 75, 300, 500, 100, 100, 125, 500, 200, 200, 500, 25, 80, 150, 120, 150, 500, 250, 150, 25, 30, 50, 30, 200, 70, 100, 100, 50, 100, 100, 100, 50, 100, 400, 25, 200, 800, 30, 400, 100, 100, 150, 40, 250, 300, 200, 300, 200, 800, 400, 400, 500, 450, 600, 300, 70, 100, 100, 300, 75, 500, 40, 400 )\n\ndegree_listB = c(585, 400, 300, 100, 383, 700, 80, 150, 300, 850, 200, 300, 150, 300, 300, 200, 150, 100, 150, 600, 300, 50, 300, 100, 700, 300, 100, 35, 70, 500, 150, 200, 20, 250, 100, 500, 20, 150, 90, 200, 20, 150, 30, 100, 200, 100, 60, 600, 100, 375, 50, 200, 300, 100, 100, 200, 75, 100, 220, 300, 500, 400, 100, 50)\n\n\ndegree_weights_list = list(degree_listA^-1, degree_listB^-1)\n\n\t\nafterA_probs = c(0.8414634, 0.1585366)\nafterB_probs = c(0.5250000, 0.4750000)\n\nprobs = matrix( c(afterA_probs, afterB_probs), 2,2,byrow=TRUE)\n\nsample_size = 246\n\n\n\n#Get the observed trans\nfoo = generate_state_seq(sample_size, probs=probs)\n\nstate_count = length(unique(foo))\nrec = matrix(0, state_count, state_count)\n\nfor (i in 2:length(foo)) {\n\trec[foo[i-1], foo[i]] = rec[foo[i-1], foo[i]]+1\n}\n\nS = prop.table(rec, 1)\n\n\ncnum = as.vector(table(foo))\n# Get Degree Seq by group, invert, bootstrap based on the counts in bootstrapped state_seq\n\n# deg_wt_list is a list of 1/degrees by group, so deg_list[[1]] is the degrees of state index 1 \nbs_mean_deg = unlist(lapply(lapply(deg_wt_list, mean), '^', -1)) #initialize with group means, probably not necessary\n\nfor (i in 1:length(bs_mean_deg)){\n\tbs_mean_deg[i] = cnum[i] / sum( sample(deg_wt_list[[i]], size=cnum[i], replace=TRUE) )\n} \n\n\n\n\nbs_results = c()\nsample_size = c()\nbs_mean_deg = c()\n\n\nw_2 = rds.mcmc.props(S)\n\n\n\n\nsim_transition_probs(100000, sample_size, probs)\n\n# [1] 0.0007175294 0.0007175294\n# [1] 0.004568726 0.004568726\n\napply(prop.table(rmultinom(1000000, size = 195, prob = w_2),2), 1, var)\n# 1 2 \n#0.0008414084 0.0008414084 \n\napply(prop.table(rmultinom(1000000, size = 195, prob = afterA_probs),2), 1, var)\n# 0.0006855071\n\napply(prop.table(rmultinom(1000000, size = 50, prob = afterB_probs),2), 1, var)\n# 0.004999966\n\n\n\nsim_transition_probs(10000, sample_size, probs=matrix(.5,nrow=2, ncol=2))\n#0.002080681\n\napply(prop.table(rmultinom(1000000, size = 195, prob = c(.5, .5)),2), 1, var)\n# 0.001282336\n\napply(prop.table(rmultinom(1000000, size = 50, prob = c(.5, .5)),2), 1, var)\n# 0.005005388\n\n\n\n\n\n\n#Need to sample number from each group\n# VAR[S_j(n)] ~ 2 * w_j * z_jj - w_j- w_j^2\n\nvar(rnorm(10000000, sd=sqrt(.343*246))+246*.79 ) #Something like the expected variation of count in each state\n# 84.397\n\nvar(rnorm(10000000, sd=sqrt(asym_var_count(probs)*246))+246*rds.mcmc.props(probs)[1] )\n\nsim_state_count(100000, 246, probs)\n# 83.481\n\nvar(rnorm(10000000, sd=sqrt(asym_var_count(probs)*1000))+1000*rds.mcmc.props(probs)[1] )\n\nsim_state_count(10000, 1000, probs)\n# 83.481\n\n#Lets simulate the variance of the ratio of n_ij / n_i\n#First get the number of n_i:\nsample_size = 246\nasym_var = asym_var_count(probs)\ne_hats = rds.mcmc.props(probs)\n\nn_sub_i = round(rnorm(100000, sd=sqrt(asym_var[1] * sample_size))+ sample_size*e_hats[1])\n\n#n_sub_ij = sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=afterA_probs)\n\n#var_prop = apply(prop.table(sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=afterA_probs) ), 2), 1, var )\napply(prop.table(sapply(n_sub_i, function(x) rmultinom(1, size=x, prob=afterA_probs) ), 2), 1, var )\n\n#.0007 vs .00068 --- not bad, need to check the p=c(.5, .5)\n\n\ntwo_step_var_est(100000, 300, matrix(.5,2,2))\n#[1,] 0.0008405214 0.0008405214\n#[2,] 0.0008378114 0.0008378114\n\n\nsim_transition_probs(10000, 300, matrix(.5,2,2))\n#[1] 0.0008397932 0.0008397932\n#[1] 0.0008414575 0.0008414575\n\n# Looks like variance is accurate to within ~2%\n\n\n\n# --------------------------------------------------------------------------------------------\n# --------------------------------------------------------------------------------------------\n# --------------------------------------------------------------------------------------------\n\n}\n\n# Test the percent error in the modeled variance compared to MC \npercent_errors_2_groups = function( reps=100, size=300, p_ij=c(.1, .25, .5, .75, .90) ){\n\tresults = matrix(nrow=length(p_ij), ncol=length(p_ij), dimnames=list(p_ij, p_ij))\n\t\n\tfor( i in 1:length(p_ij) ) {\n\t\tfor( j in 1:length(p_ij) ){\n\t\t\tprobs = matrix( c(1-p_ij[i], p_ij[j], p_ij[i], 1-p_ij[j]) , 2,2)\n\t\t\t#print(probs)\n\t\t\tmc = sim_transition_probs(reps, size, probs)\n\t\t\tmodel = two_step_var_est_const_sample_size(reps, size, probs)\n\t\t\tresults[i,j] = max((mc-model)/mc)\n\t\t}\n\t}\n\tresults\n}\n\n\n\n\n", "meta": {"hexsha": "2392b7b71f010aa003e491595d1ba68c34e2f6eb", "size": 18716, "ext": "r", "lang": "R", "max_stars_repo_path": "RDS/code/misc_code/new_bootstrap.r", "max_stars_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_stars_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "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": "RDS/code/misc_code/new_bootstrap.r", "max_issues_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_issues_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "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": "RDS/code/misc_code/new_bootstrap.r", "max_forks_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_forks_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "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.0479452055, "max_line_length": 873, "alphanum_fraction": 0.6598632186, "num_tokens": 6317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.6800174598786155}} {"text": "# ......................................................................................\n# .........................Exercise 3 - Discrete random variable........................\n# ......................................................................................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Examples ####\n# \n# * Example 1. ####\n# \n# The owner of the service center offered maintanace to a car dealership that set up car\n# rental company. For each car rented through it, they will receive CZK 500 from the car\n# rental company. At the same time, however, he undertook to invest CZK 800 in the\n# maintenance every day. The number of cars rented through the service center in 1 day\n# is described by the following probability function:
\n# ![Image-3.png](attachment:image-3.png)\n# \n# ** 1. a) ####\n# \n# The value of the probability function for 5 cars was difficult to read. Specify it:\n# \n\n\nx = c(0,1,2,3,4,5,6)\np = c(0.01,0.40,0.25,0.15,0.10,0,0.03)\nx\np\n\n1 - sum(p) # Computer arithmetic can be annoying here\nround(1 - sum(p), digits=2) # round to the hundredth\np[6] = round(1 - sum(p), digits=2) # the notation for x=5 is the 6th position\np\n\nplot(x, p)\n\n# Probability function\nprobability_draw = function(x,p){\n plot(x, p, # solid wheels - in actual values\n ylab='p(x)',xaxt='n',pch=19,ylim=c(0,max(p)),main=\"Probability function\") \n lines(c(min(x)-100,max(x)+100),c(0, 0))\n for(i in 1:length(x)){\n lines(c(min(x)-100,max(x)+100), c(p[i],p[i]),\n type = 'l', lty = 3, lwd=0.5) # horizontal grid\n lines(c(x[i],x[i]), c(-0.1,1.1), \n type = 'l', lty = 3, lwd=0.5) # vertical grid\n }\n par(new=TRUE) # that we want to draw in one graph\n plot(x, p*0, # empty circles - where a non-zero value is defined\n ylab='p(x)', xaxt='n', ylim=c(0,max(p)))\n axis(1, at=x,labels=x) # set values to X\n axis(4, at=p,labels=p, las=2, cex.axis=0.7, tck=-.01) # and Y\n}\n\nprobability_draw(x, p)\n\n# More on plotting in R can be found here:\n# http://www.statmethods.net/advgraphs/parameters.html or here\n# https://flowingdata.com/2015/03/17/r-cheat-sheet-for-graphical-parameters/ or\n# http://bcb.dfci.harvard.edu/~aedin/courses/BiocDec2011/2.Plotting.pdf\n# \n\n\n# ** 1. b) ####\n# \n# Determine and plot the distribution function of the random variable X, which is\n# defined as the number of rented cars.\n# \n\n\np\nF = cumsum(p)\nF\n\nplot(x, F, type=\"s\") # simplified distribution function graph\n\n\n# Function for calculating and plotting the distribution function\ndistribution_draw = function(x,p){\n F = cumsum(p)\n F_ext = c(0, F) # we stretch F by 0 at the beginning\n x_ext = c(x[1]-1, x, x[length(x)]+1) # axz both sides\n \n plot(x, F, ylab=\"F(x)\", xaxt='n', ylim=c(0,1), # empty wheels\n type='p', main=\"Distribution function\") \n par(new=TRUE) # that we want to draw in one graph\n plot(x, F_ext[1:(length(F_ext)-1)], # full wheels\n ylab=\"F(x)\", xaxt='n', ylim=c(0,1), type='p', pch=19) \n \n for(i in 1:(length(x_ext)-1)){\n lines(c(min(x)-100,max(x)+100), c(F_ext[i],F_ext[i]),\n type = 'l', lty = 3, lwd=0.5) # horizontal grid\n lines(c(x_ext[i],x_ext[i]), c(-0.1,1.1), \n type = 'l', lty = 3, lwd=0.5) # vertical grid\n lines(x_ext[i:(i+1)], c(F_ext[i],F_ext[i])) # graph - lines\n }\n axis(1, at=x,labels=x) # set values to X\n axis(4, at=F,labels=F, las=2, cex.axis=0.7, tck=-.01) # a Y\n return(F)\n}\n\ndistribution_draw(x,p)\n\n# ** 1. c) ####\n# \n# Determine the mean, variance, standard deviation, and mode of the number of cars\n# rented per day.\n# \n\n\n# Mean value\nx*p\nEX = sum(x*p)\nEX\n\n# Scattering\nEX2 = sum(x*x*p) # second general moment\nDX = EX2 - EX^2\nDX\n\n# Standard deviation\nsigma.X = sqrt(DX)\nsigma.X\n\n# Functions for calculating basic numerical characteristics\nsummary_of_RV=function(x,p){\n EX = sum(x*p)\n EX2 = sum(x*x*p) \n DX = EX2-EX^2\n sigma.X = sqrt(DX)\n # write the results to the table\n tab = rbind(EX, DX, sigma.X)\n tab.popis = c(\"mean\",\"variance\",\"st. dev.\")\n rownames(tab) = tab.popis\n return(tab)\n}\n\nsummary_of_RV(x, p)\n\n# ** 1. d) ####\n# \n# Determine the probability function and the distribution function of the random\n# variable Y, which is defined as the daily income of the service owner.\n# \n\n\ny = 500*x\ny\n\nprobability_draw(y, p)\n\n# Distribution function\ndistribution_draw(y,p)\n\n# ** 1. e) ####\n# \n# Determine the mean, standard deviation, and mode of receipt of the service owner from\n# rented cars within one day.\n# \n\n\nsummary_of_RV(y,p)\n\n# ** 1. f) ####\n# \n# Determine the probability that the service owner's income(random variable Y) from car\n# rental will exceed his expenses.\n# \n\n\n# profit\nz=500*x-800\nz\n\n# income exceeds expenses when profit is positive\nz > 0\n\np\nsum(p[z>0])\n\n# ** 1. g) ####\n# \n# Determine the mean, standard deviation, and mode of the random variable Z, which is\n# defined as the service owner's profit from rented cars in one day.\n# \n\n\nsummary_of_RV(z,p)\n\n# * Example 2 #### ####\n# \n# For the distribution function of the random variable X: $F(x)=\\begin{cases} 0 & \n# x \\leq -1 \\\\ 0.3 & -1 < x \\leq 0 \\\\ 0.7 & 0 < x \\leq 1 \\\\ 1 & -1 < x \\end{cases}$\n# \n# ** 2. a) ####\n# \n# Determine the probability function of a random variable X, its mean and standard\n# deviation.\n# \n\n\nF = c(0, 0.3, 0.7, 1)\nF\nx = c(-1,0,1)\nx\n\ndiff(F)\n\np = diff(F)\nx\np\n\nprobability_draw(x,p)\n\ndistribution_draw(x,p)\n\nsummary_of_RV(x,p)\n\n# ** 2. b) ####\n# \n# Random variable Y=1 - 3X, determine P(y), F(y), E(Y), D(Y).\n# \n\n\ny = 1 - 3*x\nprobability_draw(y,p)\n\ndistribution_draw(y,p) # Nonsensical output - what is the cause?\ny\np\n\ny\nsort(y)\nidx_sorted = order(y) # The order function returns the sorted order indexes\nidx_sorted\ny = y[idx_sorted]\np_y = p[idx_sorted]\np_y\n\ndistribution_draw(y,p_y)\n\nsummary_of_RV(y, p_y)\n\n# ** 2. c) ####\n# \n# Random variable W=$3X^2$, determine P(w), F(w), E(W), D(W).\n# \n\n\nw = 3*x*x\nw\n\nprobability_draw(w,p)\ndistribution_draw(w,p)\n\nw\nw_uniq = unique(w)\nw_uniq\nw_sorted = sort(w_uniq)\nw_sorted\n\np_w = w_sorted*0 # initialize an array of the same size\nfor(i in 1:length(w_sorted)){\n p_w[i] = sum(p[w == w_sorted[i]])\n}\np_w\n\nprobability_draw(w_sorted,p_w)\ndistribution_draw(w_sorted,p_w)\nsummary_of_RV(w_sorted,p_w)\n\n# * Example 3. ####\n# \n# There are two machines working independently in the workshop. The probability of\n# failure of the first machine is 0.2, the probability of failure of the second machine\n# is 0.3. The random variable X is defined as the number of machines that have failed at\n# the same time. Specify:\n# \n# ** 3. a) ####\n# \n# probability function of a random variable X,\n# \n\n\nx = c(0, 1, 2)\nx\np1 = 0.2\np2 = 0.3\n\np = x*0\n# we calculate the individual probabilities of the number of broken machines\np[1] = (1 - p1)*(1 - p2) # 0 broken, so both in operation\np[3] = p1*p2 # 2 so broken both\np\n1 - sum(p)\np[2] = (1 - p1)*p2 + p1*(1 - p2) # just one - either the first or the second\np\n\nsum(p)\n\nprobability_draw(x,p)\n\n# ** 3. b) ####\n# \n# distribution function of random variable X,\n# \n\n\ndistribution_draw(x,p)\n\n# ** 3. c) ####\n# \n# mean and variance of a random variable X.\n# \n\n\nsummary_of_RV(x,p)\n\n\n\n", "meta": {"hexsha": "908ec8804d5f85bef7691241eac076fa05c0ab0d", "size": 7445, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 3/T4_discrete_RV.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "Exercise 3/T4_discrete_RV.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "Exercise 3/T4_discrete_RV.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 23.0495356037, "max_line_length": 88, "alphanum_fraction": 0.6073875084, "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6800174436530195}} {"text": "rcond_post_beta <- function(y, xm, psi, beta_prior_mean, beta_prior_var){\n \n mu_beta <- beta_prior_mean\n v_beta <- diag(beta_prior_var)\n v_beta_inv <- diag(1/beta_prior_var)\n \n xtx <- t(xm)%*%xm\n \n if(length(y)>0 ){\n \n post_cov <- chol2inv(chol( v_beta_inv + (1/psi)*xtx))\n post_mean <- post_cov %*% (v_beta_inv %*% mu_beta + (1/psi)*t(xm)%*%y )\n \n }else{\n post_mean <- mu_beta\n post_cov <- v_beta\n }\n \n draw <- mvtnorm::rmvnorm(n = 1, mean = post_mean, sigma = post_cov)\n return(draw) \n}\n\ncond_post_beta_pdp <- function(beta_vec, y, xm, beta_prior_mean, beta_prior_var){\n \n eta <- xm %*% beta_vec\n eta <- ifelse(eta < -30, -30, ifelse(eta>5, 5, eta))\n \n lk <- sum(dbinom(x = y, size = 1, prob = LaplacesDemon::invlogit(eta), log = T))\n pr <- mvtnorm::dmvnorm(x = beta_vec, beta_prior_mean, diag(beta_prior_var), log = T)\n \n return(lk + pr)\n}\n\nrcond_post_psi <- function(beta, y, xm, g1, b1){\n n_k <- length(y)\n if(n_k==0){ \n shape_k <- g1\n rate_k <- b1\n }else{\n shape_k <- g1 + n_k/2\n rate_k <- .5*( sum( (y - xm %*% beta)^2 ) ) + b1\n }\n draw <- invgamma::rinvgamma(n = 1, shape = shape_k, rate = rate_k)\n return(draw)\n}\n\nrcond_post_mu_x <- function(x_ck, phi_x, lambda, tau ){\n nvec_k <- length(x_ck)\n mu_mean <- (1/(1/tau + nvec_k/phi_x))*(lambda/tau + sum(x_ck)/phi_x)\n mu_sd <- sqrt( (1/tau + nvec_k/phi_x)^(-1) )\n draw <- rnorm(n = 1, mean = mu_mean, sd = mu_sd)\n return(draw)\n}\n\nrcond_post_phi <- function(mu_x, x, g2, b2){\n n_k <- length(x)\n if(n_k==0){ \n shape_k <- g2\n rate_k <- b2\n }else{\n shape_k <- g2 + n_k/2\n rate_k <- .5*( sum( (x - mu_x )^2 ) ) + b2\n }\n phi_post <- invgamma::rinvgamma(n = 1, shape = shape_k, rate = rate_k)\n return(phi_post)\n}\n\nrcond_post_mu_trt <- function(x_ck){\n draw<-rbeta(n = 1,shape1 = 1 + sum(x_ck), \n shape2 = 1 + length(x_ck) - sum(x_ck))\n return(draw)\n}\n\ncond_post_alpha <- function(alpha, n, K, nvec){\n lik <- lgamma(alpha) - lgamma(n + alpha) + sum(lgamma(nvec + alpha/K)) - K*lgamma(alpha/K)\n pr <- invgamma::dinvgamma(x = alpha, 1, 1,log = T)\n return(lik + pr)\n}\n\ncond_post_pz <- function(gamma, y, xp, \n gamma_prior_mean,gamma_prior_var){\n \n eta <- xp %*% gamma\n eta <- ifelse(eta < -10, -10, ifelse(eta>10, 10, eta))\n p <- LaplacesDemon::invlogit(eta)\n \n lk <- sum(dbinom(x = y, size = 1, prob = p, log = T))\n pr <- mvtnorm::dmvnorm(x = gamma, gamma_prior_mean, diag(gamma_prior_var), log = T)\n \n return(lk + pr)\n}", "meta": {"hexsha": "7423beae93554faa9022f13bdd69b8e9f99c00bc", "size": 2503, "ext": "r", "lang": "R", "max_stars_repo_path": "R/conditional_posteriors.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/conditional_posteriors.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/conditional_posteriors.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": 27.5054945055, "max_line_length": 92, "alphanum_fraction": 0.5920894926, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6799251207997901}} {"text": " DGELSS Example Program Results\n\n Least squares solution\n 0.6344 0.9699 -1.4403 3.3678 3.3992\n\n Tolerance used to estimate the rank of A\n 1.00E-02\n Estimated rank of A\n 4\n\n Singular values of A\n 3.9997 2.9962 2.0001 0.9988 0.0025\n", "meta": {"hexsha": "1378e3e00497f2c1f94a081a0e2cf213ebd4b097", "size": 281, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dgelss_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/dgelss_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/dgelss_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": 21.6153846154, "max_line_length": 56, "alphanum_fraction": 0.6049822064, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6798971403647789}} {"text": "#[Network analysis](https://en.wikipedia.org/wiki/Network_theory) is a every day task in data analysis. Indeed we often need to know who is linked with who (geographical distance ? Same kind of features ?...)\n#[I graph](http://igraph.org/redirect.html) is the perfect package to represent link between objects. \n\n\n#Let's charge the Igraph package\nlibrary(\"igraph\")\n\n\n#Simulating Data : Mark of 9 students. 3 are known to be strong in Letters, 3 in Art and 3 in Math.\na=c(6,8,11,14,15,14,19,18,20)\nb=c(20,20,19,18,18,18,2,4,8)\nc=c(3,4,3,15,18,19,2,1,8)\ndata = matrix(c( a,a+1,a-sample(seq(1,3),9,replace=T) ,a-sample(seq(1,3),9,replace=T),\n b,b-sample(seq(1,3),9,replace=T),b+sample(seq(1,3),9,replace=T),c,\n c-sample(seq(1,3),9,replace=T),(b+c)/2) , 9 , 9)\ncolnames(data)=c(\"charline\", \"JP\", \"Kath\", \"Gary\", \"Conor\", \"Marion\", \"JB\", \"gui\", \"Vincent\")\nrownames(data)=c(\"french\",\"phylo\",\"latin\",\"musique\",\"art\",\"sport\",\"math\",\"stat\",\"R\")\n\n#Let's have a look to the rough data\nlibrary(xtable)\nprint(xtable(data , caption=\"rough data\", digits=0 ), type = \"latex\", include.rownames = T , \n comment=FALSE )\n\n\n#I calculte correlation between student's Marks. I Want to see who has the same kind of Mark structure\ndist=cor(data)\ndist[dist<0.5]=0\ndiag(dist)=0\n\n\n\n#Let's make the I-Graph. All the students with a correlation > 0.5 will be linked one to each other on the graph. Students with strong correlation will be closer. People with strong skills in letters, art and math will be Highlighted.\n# First I ask to Igraph to calculate the best position of each individuals, doing iterations\ng1<-graph.adjacency(dist,weighted=\"TRUE\",mode=\"undirected\")\nlay<-layout.fruchterman.reingold(grap=g1,niter=6000)\n\npng(\"#7_I_graph.png\")\npar(mar=c(0.5,0.5,0.5,0.5))\n\n# Then I make the plot. I ask to show the know structure of the population\nplot.igraph(g1, \n mark.shape=1 , \n mark.groups=list(c(1:3) , c(4:6) , c(7:9) ) , \n layout=lay,vertex.label=rownames(dist) ,\n vertex.color=\"green\" , \n vertex.size=0.5 , \n edge.arrow.size=13 , \n main=\"\")\n\n#Finally I add a legend\nlegend(\"bottomleft\", legend = c(\"Letter lovers\" , \"art lovers\" , \"math lovers\"), \n col = rainbow(3, alpha = 0.3) , \n pch = 15, bty = \"n\", pt.cex = 1.5, cex = 0.8 , \n text.col = \"black\", horiz = FALSE, inset = c(0.1, 0.1))\n\n\n#There we can see that the known structure is relevant. Nevertheless, it looks like the student JB, who is supposed to be strong in Math, is really close to people that are strong in Art. Actually he is strong in both !\n\n\n", "meta": {"hexsha": "2ca62f0c135c7eb5fd4674f09ecc2f3345fcc3fb", "size": 2629, "ext": "r", "lang": "R", "max_stars_repo_path": "OLD_GALLERY_RSCRIPT/#7_I_graph.r", "max_stars_repo_name": "JedStephens/R-graph-gallery", "max_stars_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 447, "max_stars_repo_stars_event_min_datetime": "2016-10-05T14:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:20:42.000Z", "max_issues_repo_path": "OLD_GALLERY_RSCRIPT/#7_I_graph.r", "max_issues_repo_name": "JedStephens/R-graph-gallery", "max_issues_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2016-10-20T14:45:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T19:15:22.000Z", "max_forks_repo_path": "OLD_GALLERY_RSCRIPT/#7_I_graph.r", "max_forks_repo_name": "JedStephens/R-graph-gallery", "max_forks_repo_head_hexsha": "a7a65d2f66372ea3724cf6e930d3c4b209f44dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172, "max_forks_repo_forks_event_min_datetime": "2015-12-01T15:34:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:37:06.000Z", "avg_line_length": 43.8166666667, "max_line_length": 234, "alphanum_fraction": 0.659566375, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6798667112982723}} {"text": "## Nesse script vamos gerar dados segundo uma binomial negativa e\n## vamos ajustar alguns modelos aos dados e criticá-los\n\n#########\n# preparação\nlibrary(rstan)\nrstan_options(auto_write = TRUE)\noptions(mc.cores = 4)\n\nset.seed(666)\n\n########\n# Simulando os dados\nN <- 100\nsfactor <- 5 ## Var(X) = sfactor * E[X]\nmu <- 10\nX <- rnbinom(N, size = mu/(sfactor - 1), mu = mu)\nhist(X, probability = TRUE, main = \"Ovos de dragão (por macho)\")\n\nmean(X)\nvar(X)\n\ndragonEgg.data <- list(N = N, x = X)\n## \npoisson.code = \"\ndata{\n int N;\n int x[N];\n}\nparameters{\n real lambda;\n}\nmodel{\n target += poisson_lpmf(x | lambda);\n target += gamma_lpdf(lambda | 1, 1);\n}\ngenerated quantities{\n int x_rep[N];\n for(i in 1:N) x_rep[i] = poisson_rng(lambda);\n}\n\"\n\nfit.poisson <- stan(model_code = poisson.code, data = dragonEgg.data)\npoisson.replicas <- extract(fit.poisson, 'x_rep')$x_rep\n\npar(mfrow = c(2, 1))\n\nhist(X, probability = TRUE, col = \"red\", main = \"Os dados\")\nabline(v = mean(X), lwd = 3, lty = 2)\nhist(as.vector(poisson.replicas), probability = TRUE, \n main = \"Replicatas \\n modelo Poisson\", xlab = expression(x^{rep}))\nabline(v = mean(X), lwd = 3, lty = 2)\n\npar(mfrow = c(1, 1))\n\n# Como nosso modelo \"prevê\" a média?\nmedias.poisson <- rowMeans(poisson.replicas)\nhist(medias.poisson, probability = TRUE, xlab = expression(bar(x)), main = \"Médias \\n modelo Poisson\")\nabline(v = mean(X), lwd = 3, lty = 2)\n\n# E a variância?\n\nvariancias.poisson <- apply(poisson.replicas, 1, var)\nhist(variancias.poisson, probability = TRUE,\n main = \"Variâncias \\n modelo Poisson\", xlab = expression(hat(v)),\n xlim = c(min(variancias.poisson), 1.5*var(X)))\nabline(v = var(X), lwd = 3, lty = 2)\n\n## Veredito: o modelo não captura corretamente a variabilidade dos dados\n\n## Vamos tentar um modelo hierárquico, mais complexo\n\npoissonBinomial.code = \"\ndata{\n int N;\n int x[N];\n}\nparameters{\n real p;\n real lambda;\n}\nmodel{\n target += poisson_lpmf(x | lambda * p );\n target += beta_lpdf(p | 2, 2);\n target += gamma_lpdf(lambda | 1, 1);\n}\ngenerated quantities{\n int M_rep[N];\n int x_rep[N];\n for(i in 1:N){\n M_rep[i] = poisson_rng(lambda);\n }\n for(i in 1:N){\n x_rep[i] = binomial_rng(M_rep[i], p);\n } \n}\n\"\n\nfit.poissonBinomial <- stan(model_code = poissonBinomial.code, data = dragonEgg.data)\nprint(fit.poissonBinomial, pars = c('p', 'lambda') )\npoissonBinomial.replicas <- extract(fit.poissonBinomial, 'x_rep')$x_rep\n\n\npar(mfrow = c(2, 1))\n\nhist(X, probability = TRUE, col = \"red\", main = \"Os dados\")\nabline(v = mean(X), lwd = 3, lty = 2)\nhist(as.vector(poissonBinomial.replicas), xlab = expression(x^{rep}), \n probability = TRUE, main = \"Replicatas \\n modelo Poisson-binomial\")\nabline(v = mean(X), lwd = 3, lty = 2)\n\n# \"Previsão\" da média pelo modelo Poisson-binomial\n\npar(mfrow = c(1, 1))\n\nmedias.poissonBinomial <- rowMeans(poissonBinomial.replicas)\nhist(medias.poissonBinomial, probability = TRUE,\n xlab = expression(bar(x)), main = \"Médias \\n modelo Poisson-binomial\")\nabline(v = mean(X), lwd = 3, lty = 2)\n\n\n# Mais uma vez, vamos olhar a variância\n\nvariancias.poissonBinomial <- apply(poissonBinomial.replicas, 1, var)\nhist(variancias.poissonBinomial, probability = TRUE,\n main = \"Variâncias \\n modelo Poisson-binomial\", xlab = expression(hat(v)),\n xlim = c(min(variancias.poisson), 1.5*var(X)))\nabline(v = var(X), lwd = 3, lty = 2)\n\n## Resultado: o modelo ainda é ruim. \n\n# Vamos tentar agora um modelo com uma estrutura hierárquica diferente\n\npoissonGamma.code = \"\ndata{\n int N;\n int x[N];\n}\nparameters{\n real alpha;\n real beta;\n real lambda[N];\n}\nmodel{\n target += poisson_lpmf(x | lambda);\n target += gamma_lpdf(lambda | alpha, beta);\n target += exponential_lpdf(alpha | 1);\n target += exponential_lpdf(beta | 1);\n}\ngenerated quantities{\n int x_rep[N];\n for(i in 1:N){\n x_rep[i] = poisson_rng(lambda[i]);\n }\n}\n\"\n\nfit.poissonGamma <- stan(model_code = poissonGamma.code, data = dragonEgg.data)\nprint(fit.poissonGamma, pars = c('alpha', 'beta') )\npoissonGamma.replicas <- extract(fit.poissonGamma, 'x_rep')$x_rep\n\npar(mfrow = c(2, 1))\n\nhist(X, probability = TRUE, col = \"red\", main = \"Os dados\")\nabline(v = mean(X), lwd = 3, lty = 2)\nhist(as.vector(poissonGamma.replicas), xlab = expression(x^{rep}),\n probability = TRUE, main = \"Replicatas \\n modelo Poisson-gama\")\nabline(v = mean(X), lwd = 3, lty = 2)\n\n# \"Previsão\" da média pelo modelo Poisson-Gamma\n\npar(mfrow = c(1, 1))\n\nmedias.poissonGamma <- rowMeans(poissonGamma.replicas)\nhist(medias.poissonGamma, probability = TRUE,\n xlab = expression(bar(x)), main = \"Médias \\n modelo Poisson-Gama\")\nabline(v = mean(X), lwd = 3, lty = 2)\n\n\n# Mais uma vez, vamos olhar a variância\n\nvariancias.poissonGamma <- apply(poissonGamma.replicas, 1, var)\nhist(variancias.poissonGamma, probability = TRUE, xlab = expression(hat(v)) ,\n main = \"Variâncias \\n modelo Poisson-Gama\", xlim = c(min(variancias.poisson), 1.5*var(X)))\nabline(v = var(X), lwd = 3, lty = 2)\n\n# Intervalos\nquantile(as.vector(poisson.replicas), probs = c(.025, .975))\nquantile(as.vector(poissonBinomial.replicas), probs = c(.025, .975))\nquantile(as.vector(poissonGamma.replicas), probs = c(.025, .975))\nqnbinom(p = c(.025, .975), size = mu/(sfactor - 1), mu = mu)", "meta": {"hexsha": "92cf7c88e147b94050089ec9eff372193e5dac89", "size": 5372, "ext": "r", "lang": "R", "max_stars_repo_path": "code/problema_1.r", "max_stars_repo_name": "lucasmoschen/stats_modelling", "max_stars_repo_head_hexsha": "8e170c0596588898502935dae3a52bbe79ac6194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-02-12T14:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T14:38:28.000Z", "max_issues_repo_path": "code/problema_1.r", "max_issues_repo_name": "lucasresck/statistical_modelling", "max_issues_repo_head_hexsha": "992daef109da69e36b713d595595f71d134be786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-31T19:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-31T19:00:40.000Z", "max_forks_repo_path": "code/problema_1.r", "max_forks_repo_name": "lucasresck/statistical_modelling", "max_forks_repo_head_hexsha": "992daef109da69e36b713d595595f71d134be786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-27T20:16:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T02:10:38.000Z", "avg_line_length": 28.1256544503, "max_line_length": 103, "alphanum_fraction": 0.6692107223, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6797252004574109}} {"text": "##########\nplot.hdr2d<-function(x,prob=c(.025,.25,.5,.75,.975),bw=c(5,5),\n cols=gray( ((length(prob)-1):1)/length(prob)), \n xlim=range(x[,1]),ylim=range(x[,2]),...) \n{\n\n #adapted from package hdrcde by Rob J Hyndman and Jochen Einbeck\n\n plot(c(0,0),xlim=xlim,ylim=ylim,type=\"n\",...)\n add.hdr2d(x,prob,bw,cols) \n}\n\n#########\n\n#########\nadd.hdr2d<-function(x,prob=c(.025,.25,.5,.75,.975),bw=c(5,5),\n cols=gray( ((length(prob)-1):1)/length(prob) )) \n{\n\n require(ash)\n den <- ash2(bin2(x,nbin=round(rep(.5*sqrt(dim(x)[1]),2)) ), bw)\n fxy <- interp.2d(den$x,den$y,den$z,x[,1],x[,2])\n falpha <- quantile(sort(fxy), prob)\n index <- (fxy==max(fxy))\n mode <- c(x[index,1],x[index,2])\n .filled.contour(den$x,den$y,den$z,levels=c(falpha,1e10),col=cols ) \n\n}\n\n\n##########\nfilledcontour<-function(x,y,z,nlevels=10,col=gray( (nlevels:0)/nlevels ),\n levels=pretty(range(z),nlevels) ) \n{\n .filled.contour(x,y,z,levels=c(levels,1e10),col=col ) \n} \n##########\n\n\n#########\ninterp.2d<- function(x, y, z, x0, y0)\n{\n # Bilinear interpolation of function (x,y,z) onto (x0,y0).\n # Taken from Numerical Recipies (second edition) section 3.6.\n # Called by hdr.info.2d\n # Vectorized version of old.interp.2d. \n # Contributed by Mrigesh Kshatriya (mkshatriya@zoology.up.ac.za)\n\n nx <- length(x)\n ny <- length(y)\n n0 <- length(x0)\n z0 <- numeric(length = n0)\n xr <- diff(range(x))\n yr <- diff(range(y))\n xmin <- min(x)\n ymin <- min(y)\n j <- ceiling(((nx - 1) * (x0 - xmin))/xr)\n k <- ceiling(((ny - 1) * (y0 - ymin))/yr)\n j[j == 0] <- 1\n k[k == 0] <- 1\n j[j == nx] <- nx - 1\n k[k == ny] <- ny - 1\n v <- (x0 - x[j])/(x[j + 1] - x[j])\n u <- (y0 - y[k])/(y[k + 1] - y[k]) \n AA <- z[cbind(j, k)]\n BB <- z[cbind(j + 1, k)]\n CC <- z[cbind(j + 1, k + 1)]\n DD <- z[cbind(j, k + 1)]\n z0 <- (1 - v)*(1 - u)*AA + v*(1 - u)*BB + v*u*CC + (1 - v)*u*DD\n return(z0)\n}\n#########\n", "meta": {"hexsha": "8fef9e8d55e238ef600c80f68b1d6ecee6f04f56", "size": 1976, "ext": "r", "lang": "R", "max_stars_repo_path": "static/stat572/pr/hdr2d.r", "max_stars_repo_name": "UrbanStudy/stat2019_website", "max_stars_repo_head_hexsha": "9d41d5caf4ece4c62bf0c301eb8c90429b17ce7d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-29T12:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T12:51:19.000Z", "max_issues_repo_path": "static/stat572/pr/hdr2d.r", "max_issues_repo_name": "UrbanStudy/stat2019_website", "max_issues_repo_head_hexsha": "9d41d5caf4ece4c62bf0c301eb8c90429b17ce7d", "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": "static/stat572/pr/hdr2d.r", "max_forks_repo_name": "UrbanStudy/stat2019_website", "max_forks_repo_head_hexsha": "9d41d5caf4ece4c62bf0c301eb8c90429b17ce7d", "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": 27.0684931507, "max_line_length": 73, "alphanum_fraction": 0.5111336032, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6794963832838711}} {"text": "# File name: mcpi_pbdr.r\n# Description: Calculate pi using Monte Carlo\n# Run: mpiexec -np 8 Rscript --vanilla mcpi_pbdr.r\n\n# Load pbdMPI and initialize the communicator\nlibrary(pbdMPI, quiet = TRUE)\ninit()\n\n#Load mcpi() function (on each rank)\nsource(\"mcpi.r\")\n\n# Number of total points to use\nn.pts <- 1e7\n# Number of points per rank\nn.ranks <- comm.size()\nn.pts.rank <- ceiling(n.pts / n.ranks)\n\ncomm.print(paste('running pbdMPI version with n.pts = ',n.pts,' and nranks = ',n.ranks,' (',n.pts.rank,' pts per rank) \\n'))\n\ntm.comp.st = Sys.time()\n\n# Compute pi() on each rank\npi.rank <- mcpi(n.pts.rank)\n\n# Use reduce() to total across ranks\npi.approx <- reduce(pi.rank, op=\"sum\") / n.ranks\n\ntm.comp = as.numeric(Sys.time() - tm.comp.st, units=\"secs\")\n\npi.err <- abs(pi - pi.approx)/pi\n\n# Output from RANK 0 since reduce() will dump only to 0 by default\ncomm.print(paste('approximate value of pi is: ',pi.approx,'\\n'))\ncomm.print(paste(' relative error: ',pi.err,'\\n'))\n\ncomm.print(paste(' computational time = ',tm.comp,'\\n'))\n\n# Wrap up\nfinalize()\n", "meta": {"hexsha": "84d9873347f93269879b7165303e4dc4305fd3b4", "size": 1063, "ext": "r", "lang": "R", "max_stars_repo_path": "Lecture/R/cmda3634/mcpi_pbdr.r", "max_stars_repo_name": "liweichen6/CMDA3634", "max_stars_repo_head_hexsha": "d4722b1af264d30d0c92f9ac772f04be918bc105", "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": "Lecture/R/cmda3634/mcpi_pbdr.r", "max_issues_repo_name": "liweichen6/CMDA3634", "max_issues_repo_head_hexsha": "d4722b1af264d30d0c92f9ac772f04be918bc105", "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": "Lecture/R/cmda3634/mcpi_pbdr.r", "max_forks_repo_name": "liweichen6/CMDA3634", "max_forks_repo_head_hexsha": "d4722b1af264d30d0c92f9ac772f04be918bc105", "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.575, "max_line_length": 124, "alphanum_fraction": 0.6707431797, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6794201033507227}} {"text": "# ......................................................................................\n# ...........Exercise 5 - Selected distributions of a discrete random variable..........\n# ......................................................................................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Overview of distributions and their functions ####\n# \n# * Introduction: Probability, Cumulative Probability(Distribution) and Quantile ####\n# functions\n# \n# ** Probability function ####\n# \n# - starts with the letter **d**: $p = P(X = x)$: p=d...(x,...)\n# \n# ** Cumulative Probability(Distribution Function) ####\n# \n# - starts with the letter **p**: $p = P(X \\leq x)$:p=p...(x,...)\n# \n# - note that Cumulative probability in R is with the alternative definition $P(X \\leq\n# t)$\n# \n# - for our distribution function $F(t) = P(X=1)=P(X>0)=1 - P(X<=0)\n1 - ppois(1 - 1, lt)\n\n# probability function graph\n# theoretically up to an infinite number of particles can be emitted,\n# from a certain value the probability is negligible\nx = 0:10 \np = dpois(x, lt) # probability function values for x\nplot(x, p)\n\n# * Example 3. ####\n# \n# A friend sends you to the cellar to bring 4 bottled beers - two 10˚ and two 12˚. You\n# don't know where to turn the light on, so you take 4 bottles blindly. How likely were\n# you to comply with the requirement if you knew that there were a total of 10 10˚ and 6\n# 12˚ in the base?\n# \n\n\n# X... number of 10 ° beers among 4 selected\n# X~H(N=16, M=10, n=4)\n\nx = 2\nN = 16\nM = 10\nn = 4\n\n# P(X=2)\ndhyper(x, M, N - M, n)\n\n# graph of probability function\nx = 0:4 # all possible implementations of NV X.\np = dhyper(x, M, N - M, n) # values of the probability function for x\nplot(x, p)\n\n# * Example 4. ####\n# \n# On average, there are 15 certain microorganisms in one milliliter of a perfectly mixed\n# solution. Determine the probability that there will be less than 5 of these\n# micro-organisms in a test tube if a sample of 1/2 milliliter is randomly selected.\n# \n\n\n# X... number of microorganisms in 0.5 ml solution\n# X~Po(lt=15/2)\n\nlambda = 15\nt = 1/2\nlt = lambda*t # Poisson distribution parameter\n\n# P(X<5)=P(X<=4)\nppois(5 - 1, lt)\n# or\nppois(5,lt) - dpois(5,lt)\n\n# graph of probability function\n# in theory there may be an infinite number of microorganisms in solution,\n# from a certain value the probability is negligible\nx = 0:20 \np = dpois(x, lt) # values of the probability function for x\nplot(x, p)\n\n# * Example 5. ####\n# \n# Throw 15 coins on the table. What is the probability that the number of coins lying\n# face up is from 8 to 15?\n# \n\n\n# X... number of coins that fall face up out of a total of 15 coins\n# X~Bi(n=15, p=0.5)\n\nn = 15\np = 0.5\n\n# P(8<=X<=15)=P(X<=15) - P(X<8)=P(X<=15) - P(X<=7)\npbinom(15, n, p) - pbinom(7, n, p) \n\n# otherwise: P(8<=X<=15)=P(X>7)=1-P(X<=7)\n1 - pbinom(7, n, p)\n\n# graph of probability function\nx = 0:15 # all possible implementations of NV X.\np = dbinom(x, n, p) # values of the probability function for x\nplot(x, p)\n\n# * Example 6. ####\n# \n# The probability that we will call the studio of the radio station that has just\n# announced a telephone competition is 0.08. What is the probability that we will manage\n# to get in on the 4th attempt at the most?\n# \n\n\n# X... number of attempts before we call the radio studio\n# X~NB(k=1, p=0.08) or G(0.08)\n\nx = 4\nk = 1\np = 0.08\n\n# P(X<=4)\npnbinom(x - k, k, p)\n\n# graph of probability function\n# theoretically we can make infinitely many attempts,\n# from a certain value the probability is negligible\nx = 1:40 \np = dnbinom(x - k, k, p) # probability function values for x\nplot(x, p)\n\n# * Example 7. ####\n# \n# In average 10% of the components produce at the factory are defective. What is the\n# probability that if we select thirty components from the daily production, at least\n# two will be defective?\n# \n\n\n# X... number of defective parts out of 30 selected\n# X~Bi(n=30, p=0.1)\n\nn = 30\np = 0.1\n\n# P(X>=2)=1 - P(X<2)=1 - P(X<=1)\n1 - pbinom(1, n, p)\n\n# or P(X>=2) all except 0 and 1\n1 - (dbinom(0, n, p) + dbinom(1, n, p))\n\n# graph of probability function\nx = 0:30 # all possible implementations of NV X.\np = dbinom(x, n, p) # values of the probability function for x\nplot(x,p)\n\n# * Example 8. ####\n# \n# There are 200 parts in stock. 10% of them are defective. What is the probability that\n# if we select thirty parts from the warehouse, at least two will be defective?\n# \n\n\n# X... number of defective parts out of 30 selected from 200\n# X~H(N=200, M=20, n=30)\n\nN = 200 \nM = 20 \nn = 30\n\n# P(X>=2)=1 - P(X<2)=1 - P(X<=1)\n1 - phyper(2 - 1, M, N - M, n)\n\n# graph of probability function\nx = 0:30 # all possible implementations of NV X.\np = dhyper(x, M, N - M, n) # probability function values for x\nplot(x, p)\n\n# * Example 9. ####\n# \n# In a company, it was found that some illegal software was installed on 33% of\n# computers. Determine the probability and distribution function of the number of\n# computers with illegal software among the three computers inspected.\n# \n\n\n# X... number of computers with illegal software out of 3 checked\n# X~Bi(n=3, p=0.33)\n\nn = 3\np = 0.33\n\n# probabilistic function\nx = 0:3 # all possible implementations of NV X\np = dbinom(x, n, p) # probability function values for x\n\np = round(p, 3) # rounding probabilities to 3 des. places\np[4] = 1 - sum(p[1:3]) # completion of the last value by 1\n\ntab = rbind(x, p) # Create probability function table\nrownames(tab) = c(\"x\", \"P(x)\")\ntab\n\n# probability function graph\nplot(x, p)\n\n# distribution function\ncumsum(p) # simplified distribution function listing\n\n\n# * Example 10. ####\n# \n# Sportka is a lottery game in which the bettor bets six numbers out of forty-nine,\n# which he expects to fall in a future draw. To participate in the game, it is necessary\n# to choose at least one combination of 6 numbers (always 6 numbers per column of 49\n# numbers) and use crosses to mark picked numbers. You can bet multiple times by filling\n# multiple columns. The bettor wins if he guesses at least three numbers from the drawn\n# six numbers. What is the probability that in order for the bettor to win, he will have\n# to fill in:\n# \n\n\n# First the probability that we get in one column\n\n# Y... number of guessed numbers in 6 drawn from 49\n# Y~H(N=49, M=6, n=6)\n\nN = 49\nM = 6\nn = 6\n\n# P-st guess at least 3 numbers in one column\n# P(Y>=3)=1 - P(Y<3)=1 - P(Y<=2)\npp = 1 - phyper(3 - 1, M, N - M, n)\npp\n\n# ** a) ####\n# \n# just three columns,\n# \n\n\n# X… the number of columns a bettor will have to fill in order to win\n# X~NB(k=1, p=pp)\n\n# a) P(X=3)\nk = 1\np = pp\n\ndnbinom(3 - k, k, pp)\n\n# ** b) ####\n# \n# at least 5 columns,\n# \n\n\n# b) P(X>=5)=1 - P(X<5)=1 - P(X<=4)\n\n1 - pnbinom(5 - k - 1, k, pp)\n\n# ** c) ####\n# \n# less than 10 columns,\n# \n\n\n# c) P(X<10)=P(X<=9)\npnbinom(10 - k - 1, k, pp)\n\n# * d) ####\n# \n# more than 5 and at most 10 columns?\n# \n\n\n# P(5=0.7\nqnbinom(0.7, k, p) + k\n\n\n\n", "meta": {"hexsha": "0d321939338f42b7c4b40bbc201ff846abbd6336", "size": 15491, "ext": "r", "lang": "R", "max_stars_repo_path": "Exercise 5/T7_selected_DRV.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "Exercise 5/T7_selected_DRV.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "Exercise 5/T7_selected_DRV.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 25.1069692058, "max_line_length": 88, "alphanum_fraction": 0.6324962882, "num_tokens": 5165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6791742381028439}} {"text": "#basics\n\nmax(x,na.rm=TRUE) #Find the maximum value in the vector x, exclude missing values \nmin(x, na.rm=TRUE) \nmean(x,na.rm=TRUE) \nmedian(x,na.rm=TRUE) \nsum(x, na.rm=TRUE) \nvar(x,na.rm=TRUE) #produces the variance covariance matrix \nsd(x,na.rm=TRUE) #standard deviation \nmad(x,na.rm=TRUE) #(median absolute deviation) \nfivenum(x,na.rm=TRUE) #Tukey five numbers min, lower hinge, median, upperhinge, max \ntable(x) #frequency counts of entries, ideally the entries are factors (although it works with integers or even reals) \n\nabs(x) #takes the absolute value of x\nlog(x,base = y) #Takes the log of x with base y; if base is not specified, returns the natural log\nexp(x) #returns the exponential of x\nsqrt(x) #Returns the square root of x\nfactorial(x) #Returns the factorial of x (x!)\nchoose(x, y) #Returns the number of possible combinations when drawing y elements at a time from x possibilities\nround(x, digits = y) #Rounds x to y places\nfloor(x) #rounds down to the nearest int\nceiling(x) #rounds up to the nearest int\nsignif(x, digits = y) #rounds to that specified number of significant digits\n", "meta": {"hexsha": "0728eb93f3a2f9203bf6ab99b6f533eb17f3bd93", "size": 1099, "ext": "r", "lang": "R", "max_stars_repo_path": "statistics/math.r", "max_stars_repo_name": "thezorb/rBible", "max_stars_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "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": "statistics/math.r", "max_issues_repo_name": "thezorb/rBible", "max_issues_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "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": "statistics/math.r", "max_forks_repo_name": "thezorb/rBible", "max_forks_repo_head_hexsha": "19c5d1c8e3a4fc1a35ea7041f539b5c20587e6c3", "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.7916666667, "max_line_length": 119, "alphanum_fraction": 0.7470427662, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6790086181090724}} {"text": "fibonacci_step <- function(a, b) {\n list(b, a + b)\n}\n\ngross <- 0\nlst <- list(1, 2)\nwhile (lst[[1]] < 4e6) {\n if (lst[[1]] %% 2 == 0) {\n gross <- gross + lst[[1]]\n }\n lst <- do.call(fibonacci_step, lst)\n}\n\ncat(gross, \"\\n\")\n", "meta": {"hexsha": "e6f800153217d325e83c03eaaad73f2da475218c", "size": 241, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/pe_0002.r", "max_stars_repo_name": "shanedrabing/project-euler", "max_stars_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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/pe_0002.r", "max_issues_repo_name": "shanedrabing/project-euler", "max_issues_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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/pe_0002.r", "max_forks_repo_name": "shanedrabing/project-euler", "max_forks_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "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.0666666667, "max_line_length": 39, "alphanum_fraction": 0.4771784232, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6787602027141433}} {"text": "# 4E1\n\n# The likelihood is y_i ~ Normal(mu, sigma)\n\n# 4E2\n\n# There are 2 parameters\n\n# 4E3\n\n# Bayes' Theorem:\n# p(a | b) = p(b | a) p(a) / p(b)\n\n# Model:\n# y_i ~ Normal(mu, sigma)\n# mu ~ Normal(0, 10)\n# sigma ~ Exponential(1)\n\n# pr(y_i | mu, sigma) = Normal(y_i | mu, sigma)\n# pr(mu) = Normal(mu | 0, 10)\n# pr(sigma) = Exponential(sigma | 1)\n\n# So:\n\n# pr(mu, sigma | y_i ) = (pr(y_i | mu, sigma) * pr(mu) * pr(sigma))\n# / ( integral(pr(y_i | mu, sigma)\n# * pr(mu) * pr(sigma))d y )\n\n# pr(mu, sigma | y_i ) = (Normal(y | mu, sigma)\n# * Normal(mu | 0, 10) *\n# * Exp(sigma | 1))\n# / integral(Normal(y | mu, sigma)\n# * Normal(0, 10)\n# * Exp(1)) dmu dsigma\n\n# Yeah I don't understand this.\n\n# 4E4\n\n# The linear model is u_i = a + b * x_i\n\n# 4E5\n\n# 3 parameters, a, b, sigma in the posterior.\n# The mean is defined by a and b, as such isn't a parameter.\n\n# 4M1\n\n# Model:\n# y_i ~ Normal(mu, sigma)\n# mu ~ Normal(0, 10)\n# sigma ~ Exponential(1)\n\n# Recall: The prior predictive simulation is plugging in the prior parameter\n# samples into the *likelihood estimator*.\n\n# So:\n\n# Likelihood estimator\n\nsize <- 1e4\n\nlikelihood <- function(mu_samples, sigma_samples) {\n\t rnorm(size, mu_samples, sigma_samples)\n}\n\nmu_samples <- rnorm(size, 0, 10)\nsigma_samples <- rexp(size, 1)\n\nprior_predictive_samples <- likelihood(mu_samples, sigma_samples)\ndens(prior_predictive_samples)\n\n# Note that we end up sampling through layers when doing Posterior pred sim.\n\n# 4M4\n# y_i ~ dnorm(mu, sigma)\n# mu ~ dnorm(0, 10)\n# sigma ~ dexp(1)\n\n# 4M3\n# y ~ Normal(mu, sigma)\n# mu = a + b*x\n# a ~ Normal(0, 10)\n# b ~ Uniform(0, 1),\n# sigma ~ Exponential(1)\n\n# 4M4\n# Measure student heights for 3 years. Linear regression: height vs year.\n# h_i ~ dnorm(mu_i, sigma)\n# mu_i = a + b * ( year_i - year_bar)\n# a <- dnorm(100, 20)\n# b <- dunif(5, 20)\n# sigma <- dunif(0, 15)\n\n# prior-pd:\nplot(NULL, xlim=c(0, 3), ylim=c(50, 250), xlab=\"year\", ylab=\"height\")\nN <- 100\nyear_bar <- 2\na_sample <- rnorm(N, 100, 20)\nb_sample <- log_normal(N, 5, 20)\nsigma_sample <- runif(N, 0, 8)\n\nfor (i in 1:N) curve(\n\ta[i] + b[i] * (x - year_bar),\n\tfrom=0,\n\tto=3,\n\tadd=TRUE,\n\tcol=col.alpha('black', .2)\n)\n\n# 4M7\nlibrary(rethinking)\ndata(Howell1); d <- Howell1; d2 <- d[ d$age >= 18, ]\n\nm4.3_revised <- quap(\n alist(\n # likelihood\n height ~ dnorm(mu, sigma),\n # Linear predictor\n mu <- alpha + beta * ( weight),\n # priors\n alpha ~ dnorm(178, 20),\n beta ~ dlnorm(0, 1),\n sigma ~ dunif(0, 50)\n ), data=d2\n)\n\n# > vcov(m4.3_revised)\n# alpha beta sigma\n# alpha 3.601407563 -0.0784370308 0.0093616751\n# beta -0.078437031 0.0017437116 -0.0002043995\n# sigma 0.009361675 -0.0002043995 0.0365751541\n\n\n# > vcov(m4.3)\n# alpha beta sigma\n# alpha 7.306632e-02 -4.238715e-08 6.151697e-05\n# beta -4.238715e-08 1.757593e-03 -2.517741e-05\n# sigma 6.151697e-05 -2.517741e-05 3.654026e-02\n\n\n\nanalyze <- m4_7analyze(model) {\n\tweight.seq <- seq(from=25, to=70, by=1)\n\tmu_revised <- link(model, data=data.frame(weight=weight.seq))\n\tmu_revised.mean <- apply(mu_revised, 2, mean)\n\tmu_revised.pi <- apply(mu_revised, 2, PI, prob=.89)\n\n\n\theights <- sim(model, data=list(weight=weight.seq))\n\theights.pi <- apply(heights, 2, PI, prob=.89)\n\n\tplot(\n\t\td2$height ~ d2$weight,\n\t\txlim=range(d2$weight),\n\t\tcol=col.alpha(rangi2, .8)\n\t)\n\n\tlines(weight.seq, mu_revised.mean)\n\tshade(mu_revised.pi, weight.seq)\n\tshade(heights.pi, weight.seq)\n}\n", "meta": {"hexsha": "2bb37a3344edbbc703dbcb800f128fea5cd2c0d7", "size": 3567, "ext": "r", "lang": "R", "max_stars_repo_path": "chapter_4/code.r", "max_stars_repo_name": "MannySchneck/statistical-relearning-code", "max_stars_repo_head_hexsha": "495e4b738d88c4b6197f679b4a90ee13e9cc0bf6", "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": "chapter_4/code.r", "max_issues_repo_name": "MannySchneck/statistical-relearning-code", "max_issues_repo_head_hexsha": "495e4b738d88c4b6197f679b4a90ee13e9cc0bf6", "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": "chapter_4/code.r", "max_forks_repo_name": "MannySchneck/statistical-relearning-code", "max_forks_repo_head_hexsha": "495e4b738d88c4b6197f679b4a90ee13e9cc0bf6", "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": 21.8834355828, "max_line_length": 76, "alphanum_fraction": 0.6007849734, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.678760201549968}} {"text": "simulate_bayesian = function(steps, phi, I0) {\n discrete_pchisq = diff(pchisq(0:steps, df=6))\n beta = function(t, tau) {\n return(phi * discrete_pchisq[tau])\n }\n # simulate a sequence of incident cases\n I = I0\n expected = I0\n expected_conditional = I0\n for (t in 2:steps) {\n I = c(I, 0) # so I[t] = 0\n expected = c(expected, 0)\n expected_conditional = c(expected_conditional, 0)\n for (tau in 1:(t - 1)) {\n I[t] = I[t] + (rpois(1, lambda=beta(t, tau)) * I[t - tau])\n expected[t] = expected[t] + beta(t, tau) * expected[t - tau]\n expected_conditional[t] = expected_conditional[t] + beta(t, tau) * I[t - tau]\n }\n }\n return(list(\"I\"=I, \"expected\"=expected, \"expected_conditional\"=expected_conditional,\n \"omega\"=discrete_pchisq))\n}\n\nsimulate_impartial = function(steps, beta, tau1, tau2, I0) {\n \"\n Simulate Cerón's impartial model.\n \n Parameters\n ----------\n steps : numeric\n Number of steps in the simulation.\n beta : numeric vector\n Series where beta[t] is the expected number of people an infectious patient\n will infect in step t.\n tau1 : numeric\n Expected number of days since exposure to infection onset.\n tau2 : numeric\n Expected number of days a patient remains infectious.\n I0 : numeric\n Number of intial just-infectious cases.\n \"\n # initialize simulated vectors to be returned\n E = 0\n N = I0\n I = I0\n expected_I = I0\n expected_E = 0\n expected_N = I0\n # carry out simulation and append to those vectors\n for (t in 1:(steps - 1)) {\n I = c(I, rbinom(1, size=E[t], prob=1 / tau1))\n E = c(E, E[t] - I[t + 1] + rpois(1, lambda=beta[t] * N[t]))\n N = c(N, N[t] + I[t + 1] - rbinom(1, size=N[t], prob=1 / tau2))\n # track expected values\n expected_I = c(expected_I, expected_E[t] / tau1)\n expected_E = c(expected_E, expected_E[t] - expected_I[t + 1] + expected_N[t] * beta[t])\n expected_N = c(expected_N, expected_I[t + 1] + expected_N[t] * (1 - (1 / tau2)))\n }\n # calculate theoretical values\n R = beta * tau2\n f_inc = dgeom(1:steps - 1, p=1 / tau1)\n f_inf = dgeom(1:steps - 1, p=1 / tau2)\n omega = NULL\n for (tau in 1:steps) {\n omega = c(omega, 0) # so omega[tau] = 0\n for (tau_prime in 0:(tau - 1)) {\n omega[tau] = omega[tau] +\n pgeom(tau_prime - 1, p=1 / tau2, lower.tail=FALSE) *\n dgeom(tau - tau_prime - 1, p=1 / tau1)\n }\n }\n omega = omega / tau2\n # alternative tau calculation\n omega_alt = rep(0, length=steps)\n prob1 = dgeom((-1):(2 * steps), p=1/tau1)\n prob2 = dgeom((-1):(2 * steps), p=1/tau2)\n for(i in 1:(steps + 1)){\n for(j in 1:(steps + 1)){\n if(i + j - 2 < steps){\n # omega_alt[i+j-1] = omega_alt[i+j-1] + dgeom(i-2, p=1/tau1) *\n # (dgeom(2*j - 2, p=1/tau2) + dgeom(2*j - 3, p=1/tau2))\n omega_alt[i+j-1]=omega_alt[i+j-1]+prob1[i]*(prob2[2*j]+prob2[2*j-1])\n }\n } \n }\n # supress starting 0\n omega_alt = c(omega_alt[2:steps], 0)\n return(list(\n \"I\"=I, \"E\"=E, \"N\"=N, \"expected_I\"=expected_I, \"R\"=R, \"f_inc\"=f_inc,\n \"f_inf\"=f_inf, \"steps\"=steps, \"tau1\"=tau1, \"tau2\"=tau2, \"omega\"=omega,\n \"omega_alt\"=omega_alt\n ))\n}\n\nsimulate_inseparable_beta = function(steps, phi, tau0, I0) {\n t0 = floor(steps / 2)\n discrete_pchisq = diff(pchisq(0:steps, df=6))\n beta = function(t, tau) {\n if (t <= t0) {\n return(phi * discrete_pchisq[tau])\n } else {\n if (tau > tau0) {\n return(0)\n } else {\n return (phi * discrete_pchisq[tau] / pchisq(tau0, df=6))\n }\n }\n }\n omega = function(t, tau) {\n if (t <= t0) {\n return(discrete_pchisq[tau])\n } else {\n if (tau > tau0) {\n return(0)\n } else {\n return (discrete_pchisq[tau] / pchisq(tau0, df=4))\n }\n }\n }\n # simulate a sequence of incident cases\n I = I0\n expected = I0\n expected_conditional = I0\n for (t in 2:steps) {\n I = c(I, 0) # so I[t] starts at 0\n expected = c(expected, 0)\n expected_conditional = c(expected_conditional, 0)\n for (tau in 1:(t - 1)) {\n I[t] = I[t] + (rpois(1, lambda=beta(t, tau)) * I[t - tau])\n expected[t] = expected[t] + beta(t, tau) * expected[t - tau]\n expected_conditional[t] = expected_conditional[t] + beta(t, tau) * I[t - tau]\n }\n }\n return(list(\"I\"=I, \"expected\"=expected, \"expected_conditional\"=expected_conditional,\n \"omega\"=omega))\n}", "meta": {"hexsha": "8ccbd69716ed1f44fac3ec8d8faa0cd701c9a966", "size": 4388, "ext": "r", "lang": "R", "max_stars_repo_path": "simulations/generators.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "simulations/generators.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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/generators.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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.2647058824, "max_line_length": 91, "alphanum_fraction": 0.5811303555, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.678657842157052}} {"text": "#' Compute the squared coherence spectrum of two timeseries.\n#'\n#' @param t1 Sampling times of timeseries 1.\n#' @param x1 Value of timeseries 1 at each sample time.\n#' @param t2 Sampling times of timeseries 2.\n#' @param x2 Value of timeseries 2 at each sample time.\n#' @param omega Angular frequencies to evaluate periodogram at.\n#' @param demeaned Whether timeseries has already been de-meaned.\n#' @param standardized Whether timeseries has already been standardized.\n#'\n#' @return Values of squared coherence spectrum at angular frequencies specified.\n#'\n#' @examples\n#' squared.coherence.spectrum(1:10, sin(1:10), 1:10, cos(1:10), 2*pi/1:10, FALSE, FALSE)\n#'\n#' @export\nsquared.coherence.spectrum <- function(t1, x1, t2, x2, omega,\n demeaned = FALSE, standardized = FALSE) {\n\n ## De-mean and standardize, if not already done. ##\n if (!demeaned) {\n x1 <- x1 - mean(x1)\n x2 <- x2 - mean(x2)\n }\n if (!standardized) {\n x1 <- x1 / sd(x1)\n x2 <- x2 / sd(x2)\n }\n\n tau1 <- tau(t1, omega)\n tau2 <- tau(t2, omega)\n\n a1 <- periodogram.component(t1, x1, omega, tau1, \"cos\")\n a2 <- periodogram.component(t2, x2, omega, tau2, \"cos\")\n b1 <- periodogram.component(t1, x1, omega, tau1, \"sin\")\n b2 <- periodogram.component(t2, x2, omega, tau2, \"sin\")\n\n co.spectrum <- a1*a2 + b1*b2\n quad.spectrum <- a1*b2 - a2*b1\n\n cross.amplitude.spectrum.squared <- co.spectrum^2 + quad.spectrum^2\n\n power.spectrum1 <- 0.5 * (a1^2 + b1^2)\n power.spectrum2 <- 0.5 * (a2^2 + b2^2)\n\n cross.amplitude.spectrum.squared / (power.spectrum1 * power.spectrum2)\n\n}\n", "meta": {"hexsha": "89bbfc48329f9916095e3a0df85e52d2fb496a36", "size": 1643, "ext": "r", "lang": "R", "max_stars_repo_path": "R/squared.coherence.spectrum.r", "max_stars_repo_name": "dwysocki/cross-spectral-analysis", "max_stars_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-06T12:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T12:41:16.000Z", "max_issues_repo_path": "R/squared.coherence.spectrum.r", "max_issues_repo_name": "dwysocki/cross-spectral-analysis", "max_issues_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-12T03:17:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-12T03:17:50.000Z", "max_forks_repo_path": "R/squared.coherence.spectrum.r", "max_forks_repo_name": "dwysocki/cross-spectral-analysis", "max_forks_repo_head_hexsha": "854d0fabee3e5c32dba7152bae18e6ae0a20e646", "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.5306122449, "max_line_length": 88, "alphanum_fraction": 0.6342057212, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6786578257676292}} {"text": "library(shiny)\nlibrary(rsconnect)\nlibrary(ggplot2)\n\n#############################################################\n# Set the baseline parameters\n#############################################################\nbase_sI <- .2\nbase_gL <- .01\nbase_gA <- .02\nbase_delta <- .05\nbase_alpha <- .3\nbase_A <- 1\nbase_kystar <- base_sI/(base_gL+base_gA+base_delta)\nbase_K <- base_kystar^(1/(1-base_alpha))\nbase_timeT <- 50\n\n#############################################################\n# Define UI ----\n#############################################################\nui <- fluidPage(\n withMathJax(),\n titlePanel(\"Basic Solow Model\"),\n \n sidebarLayout(\n sidebarPanel(\n \n h4(\"Set parameters\"),\n actionButton(\"reset\", \"Reset to baseline\"),\n sliderInput(\"alt_sI\", h6('New capital share of GDP \\\\(s_I\\\\)'),\n min = 0, max = 1, value = base_sI),\n sliderInput(\"alt_gL\", h6(\"Population growth rate \\\\(gL\\\\)\"),\n min = -.1, max = .1, value = base_gL),\n sliderInput(\"alt_gA\", h6(\"Productivity gorwth rate \\\\(gA\\\\)\"),\n min = -.1, max = .1, value = base_gA),\n sliderInput(\"alt_delta\", h6(\"Depreciation rate \\\\(\\\\delta\\\\)\"),\n min = 0, max = 1, value = base_delta),\n sliderInput(\"alt_alpha\", h6(\"Capital elasticity \\\\(\\\\alpha\\\\)\"),\n min = 0, max = 1, value = base_alpha),\n sliderInput(\"alt_K\", h6(\"Initial capital stock \\\\(K_0\\\\)\"),\n min = 0, max = 10, value = base_K,step = 0.1),\n sliderInput(\"alt_A\", h6(\"Initial Productivity \\\\(A_0\\\\)\"),\n min = 0, max = 10, value = base_A, step = 0.1),\n sliderInput(\"timeT\", h6(\"Number of periods\"),\n min = 0, max = 300, value = base_timeT, step = 1)\n ), # end sidebar panel\n \n mainPanel(\n \n tabsetPanel(type = \"tabs\",\n tabPanel(\"K/Y ratio\",\n br(),\n p(\"The baseline is that the economy is on a BGP, so the actual K/Y is constant. \n As you adjust the parameters to the left, there may be a new BGP, or actual K/Y may\n not be on the BGP any more. Black graphs the actual path of K/Y, blue the baseline BGP,\n and green is the new BGP based on your choice of parameters.\"),\n br(),\n p(\"Be sure you understand why some adjustments to parameters create a new BGP, and why\n some adjustments only push actual K/Y off of the BGP.\"),\n plotOutput(\"kygraph\",width = \"100%\") ),\n tabPanel(\"Log GDP p.c.\", \n br(),\n p(\"This has the same idea the K/Y ratio. Black is the actual path of GDP per capita. \n Green is the BGP from the parameters you set, and blue is the original BGP.\"),\n br(),\n plotOutput(\"lnygraph\",width = \"100%\") ),\n tabPanel(\"Growth rate\", \n br(),\n p(\"The colors work the same with the growth rate of GDP per capita. Make sure you \n understand how this growth rate is related to the path of log GDP per capita.\"),\n br(),\n plotOutput(\"gygraph\",width = \"100%\") ),\n tabPanel(\"K/Y dynamics\", \n br(),\n p(\"This graph is different. It shows the relationship of the growth rate in K/Y and\n the level of K/Y. The negative slope established the stability of the Solow model.\n Changes in some parameters shift the theoretical curves here, implying different\n steady state K/Y ratios where the growth rate is zero.\"),\n br(),\n p(\"The black dots indicate the actual K/Y ratio and growth rate over time. In the \n baseline, all these dots are at the steady state point. If you adjust parameters\n you'll see these spread out and show you how K/Y and the growth rate of K/Y evolved. \n See how they follow the green path based on the new BGP.\"),\n br(),\n plotOutput(\"gkygraph\",width = \"100%\") )\n ) # end tabset\n\n ) # end main panel\n ) # end ui\n)\n#############################################################\n# Define server logic ----\n#############################################################\nserver <- function(input, output, session) {\n\n # Reset parameters\n observeEvent(input$reset, {\n updateSliderInput(session,'alt_sI',value = base_sI)\n updateSliderInput(session,'alt_gL',value = base_gL)\n updateSliderInput(session,'alt_gA',value = base_gA)\n updateSliderInput(session,'alt_delta',value = base_delta)\n updateSliderInput(session,'alt_alpha',value = base_alpha)\n updateSliderInput(session,'alt_K',value = base_K)\n updateSliderInput(session,'alt_A',value = base_A)\n updateSliderInput(session,'timeT',value = base_timeT)\n })\n \n # Simple function to calculate the new steady state K/Y ratio for display\n output$kystar <- renderText(\n { \n paste(\"K/Y*:\", \n input$alt_sI/(input$alt_delta+input$alt_gA+input$alt_gL)) \n }\n )\n \n # Function to combine alternative and baseline inputs, generate dataframe\n # containing time series of outcomes\n GraphData <- reactive({\n t <- c(0:input$timeT) # vector of periods up to input time\n df <- data.frame(t) # create dataframe to hold outcomes\n alt_kystar <- input$alt_sI/(input$alt_delta+input$alt_gA+input$alt_gL) # alt ss KY\n alt_ky <- (input$alt_K/input$alt_A)^(1-input$alt_alpha) ## actual starting KY\n \n # Formula to fill in per-period actual KY ratio\n df$ky <- alt_kystar*(1-exp(-(1-input$alt_alpha)*(input$alt_delta+input$alt_gA+input$alt_gL)*df$t)) + alt_ky*exp(-(1-input$alt_alpha)*(input$alt_delta+input$alt_gA+input$alt_gL)*df$t)\n \n df$kyalt <- alt_kystar # fill df with alt ss KY\n df$kybase <- base_kystar # fill df with base ss KY\n \n # Fill df with series on log GDP per capita\n df$lny <- (input$alt_alpha/(1-input$alt_alpha))*df$ky + log(input$alt_A) + input$alt_gA*df$t\n df$lnyalt <- (input$alt_alpha/(1-input$alt_alpha))*df$kyalt + log(input$alt_A) + input$alt_gA*df$t\n df$lnybase <- (base_alpha/(1-base_alpha))*df$kybase + log(base_A) + base_gA*df$t\n \n # Fill df with series on growth rate of GDP per capita\n df$gky <- (1-input$alt_alpha)*(input$alt_sI/df$ky-input$alt_gL -input$alt_gA- input$alt_delta)\n df$gy <- (input$alt_alpha/(1-input$alt_alpha))*df$gky + input$alt_gA\n df$gyalt <- input$alt_gA\n df$gybase <- base_gA\n \n df$tick <- df$ky # for graphing purposes later\n return(df)\n })\n \n output$kygraph <- renderPlot(\n {\n ggplot(GraphData(), aes(t,value,colour=variable)) +\n geom_line(aes(y = ky, color = \"black\"),size=1) + \n geom_line(aes(y = kybase, color=\"blue\"), linetype=\"dashed\",size=1) +\n geom_line(aes(y = kyalt, color=\"green\"), linetype=\"dashed\",size=1) +\n xlab(\"Time\") +\n ylab(\"Capital/output ratio\") +\n ylim(0, 5) +\n theme_light() +\n ggtitle(\"Capital/output ratio over time\") + \n scale_color_identity(name = \"Models\",\n breaks = c(\"black\", \"green\", \"blue\"),\n labels = c(\"Actual\", \"New BGP\", \"Old BGP\"),\n guide = \"legend\")\n }\n ) # end ky graph\n \n output$lnygraph <- renderPlot(\n {\n ggplot(GraphData(), aes(t,value,colour=variable)) +\n geom_line(aes(y = lny, color = \"black\"),size=1) + \n geom_line(aes(y = lnybase, color=\"blue\"), linetype=\"dashed\",size=1) +\n geom_line(aes(y = lnyalt, color=\"green\"), linetype=\"dashed\",size=1) +\n xlab(\"Time\") +\n ylab(\"Log GDP per capita\") +\n ylim(0, 3) +\n theme_light() +\n ggtitle(\"GDP per capita over time\") + \n scale_color_identity(name = \"Models\",\n breaks = c(\"black\", \"green\", \"blue\"),\n labels = c(\"Actual\", \"New BGP\", \"Old BGP\"),\n guide = \"legend\")\n }\n ) # end lny graph\n \n \n output$gygraph <- renderPlot(\n {\n ggplot(GraphData(), aes(t,value,colour=variable)) +\n geom_line(aes(y = gy, color = \"black\"),size=1) + \n geom_line(aes(y = gybase, color=\"blue\"), linetype=\"dashed\",size=1) +\n geom_line(aes(y = gyalt, color=\"green\"), linetype=\"dashed\",size=1) +\n xlab(\"Time\") +\n ylab(\"Growth rate of GDP p.c.\") +\n theme_light() +\n ylim(-.05, .07) +\n ggtitle(\"Growth rate of GDP p.c. over time\") + \n scale_color_identity(name = \"Models\",\n breaks = c(\"black\", \"green\", \"blue\"),\n labels = c(\"Actual\", \"New BGP\", \"Old BGP\"),\n guide = \"legend\")\n }\n ) # end gy graph\n\n output$gkygraph <- renderPlot(\n {\n tick <- seq(0,6,.1) # arbitrary kal values\n df <- data.frame(tick) # create dataframe\n df$gky <- (1-input$alt_alpha)*(input$alt_sI/df$tick-input$alt_gL -input$alt_gA- input$alt_delta)\n df$gkybase <- (1-base_alpha)*(base_sI/df$tick-base_gL -base_gA- base_delta)\n alt_kystar = (input$alt_sI/(input$alt_gL + input$alt_gA + input$alt_delta))\n \n ggplot(df, aes(x=tick)) +\n geom_line(aes(y = gky, color = \"green\"),size=1) + \n geom_line(aes(y = gkybase, color=\"blue\"), linetype=\"dashed\",size=1) +\n geom_point(data=GraphData(),y=GraphData()$gky, color=\"black\") +\n geom_hline(yintercept=0, linetype=\"dotted\", color = \"red\") +\n geom_vline(xintercept=base_kystar, linetype=\"dotted\", color = \"red\") +\n geom_vline(xintercept=alt_kystar, linetype=\"dotted\", color = \"red\") +\n xlab(\"K/Y ratio\") +\n ylab(\"Growth rate of K/Y\") +\n theme_light() +\n ylim(-.1,.15) +\n ggtitle(\"Growth rate of K/Y vs. K/Y\") + \n scale_color_identity(name = \"Models\",\n breaks = c(\"green\", \"blue\"),\n labels = c(\"New BGP\", \"Old BGP\"),\n guide = \"legend\")\n }\n ) # end gky graph\n \n \n} # end server\n\n# Run the app ----\nshinyApp(ui = ui, server = server)", "meta": {"hexsha": "7bee581271334d2bc712d5ef5bf23cf9104be1dd", "size": 10535, "ext": "r", "lang": "R", "max_stars_repo_path": "code/TestBasic/app.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/TestBasic/app.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "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/TestBasic/app.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 45.6060606061, "max_line_length": 186, "alphanum_fraction": 0.5316563835, "num_tokens": 2708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6786537754431939}} {"text": "\n# intersects line x+t*v with G*xu))\n # par(mfrow=c(2,1)); plot(ff); plot(ffcs)\n # pos now is: center of xx[ux] andxx[ux+1]\n xn = 0.5*(xx[,ux] + xx[,ux+1]) \n \n X[,zi] = xn\n }\n return(X)\n}\n\n# compute hr steps\n# nsteps\nhr_unif <- function(G,h,X,nsteps) {\n \n cs = 0\n XX = vector('list',length(nsteps))\n \n ii = 1;\n for(nsi in nsteps){\n stepsi = nsi-cs;\n for( zi in 1:stepsi ){\n X = hrstep_unif(G,h,X)\n }\n XX[[ii]] = X;\n ii = ii+1\n cs = nsi;\n }\n return(XX);\n}\n\nhr <- function(G,h,f,X,nsteps,ns1d) {\n \n cs = 0\n XX = vector('list',length(nsteps))\n \n ii = 1;\n for(nsi in nsteps){\n stepsi = nsi-cs;\n for( zi in 1:stepsi ){\n X = hrstep_01(G,h,f,X,ns1d)\n }\n XX[[ii]] = X;\n ii = ii+1\n cs = nsi;\n }\n return(XX);\n}\n\n\n\n\n", "meta": {"hexsha": "ca9cd10a4e00e96aa7fd5bff780202a36c36e0f2", "size": 3038, "ext": "r", "lang": "R", "max_stars_repo_path": "mcmc/hr.r", "max_stars_repo_name": "lithom/hs2_R", "max_stars_repo_head_hexsha": "47b30359de5f10bb1183f1baccf0db0065c537d0", "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": "mcmc/hr.r", "max_issues_repo_name": "lithom/hs2_R", "max_issues_repo_head_hexsha": "47b30359de5f10bb1183f1baccf0db0065c537d0", "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": "mcmc/hr.r", "max_forks_repo_name": "lithom/hs2_R", "max_forks_repo_head_hexsha": "47b30359de5f10bb1183f1baccf0db0065c537d0", "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.8421052632, "max_line_length": 133, "alphanum_fraction": 0.5579328506, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6786537731300383}} {"text": "# Utilities - basics\n\n# 1. Mathematical\n# round: round the values to 0 decimal places by default\n\n# The errors vector has already been defined for you\nerrors <- c(1.9, -2.6, 4.0, -9.5, -3.4, 7.3)\n\n# Sum of absolute rounded values of errors\nsum(abs(round(errors)))\n\n# 2. Data\n# seq(): Generate sequences, by specifying the from, to, and by arguments.\n# rep(): Replicate elements of vectors and lists.\n# sort(): Sort a vector in ascending order. Works on numerics, but also on character strings and logicals.\n# rev(): Reverse the elements in a data structures for which reversal is defined.\n# str(): Display the structure of any R object.\n# append(): Merge vectors or lists.\n# is.*(): Check for the class of an R object.\n# as.*(): Convert an R object from one class to another.\n# unlist(): Flatten (possibly embedded) lists to produce a vector.\n\n# The linkedin and facebook lists have already been created for you\nlinkedin <- list(16, 9, 13, 5, 2, 17, 14)\nfacebook <- list(17, 7, 5, 16, 8, 13, 14)\n\n# Convert linkedin and facebook to a vector: li_vec and fb_vec\nli_vec <- unlist(linkedin)\nfb_vec <- unlist(facebook)\n\n# Append fb_vec to li_vec: social_vec\nsocial_vec <- append(li_vec, fb_vec)\n\n# Sort social_vec\nrev(sort(social_vec))\n\n# Fix me - had to switch the two functions into the correct order\nrep(seq(1, 7, by = 2), times = 7)\n\n# Create first sequence: seq1\nseq1 <- seq(1, 500, by = 3)\n\n# Create second sequence: seq2\nseq2 <- seq(1200, 900, by = -7)\n\n# Calculate total sum of the sequences\nsum(append(seq1, seq2))\n", "meta": {"hexsha": "af5a6131cbdedf83fc596f325b65dfbe204df3e1", "size": 1519, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DataAnalyst/Basics/utilities-basics.r", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/utilities-basics.r", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/utilities-basics.r", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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.6458333333, "max_line_length": 106, "alphanum_fraction": 0.7083607637, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6785963668810601}} {"text": "#' Function to return the magnificent seven statistics for a given data series\n#' @param x A dataframe containing a vector of date values in the first column and vector of numeric flow values in the second column.\n#' @param yearType A charcter of either \"water\" or \"calendar\" indicating whether to use water years or calendar years, respectively.\n#' @param digits A numeric. Number of digits to round indice values\n#' @return data.frame of calculated statistics\n#' @details This is a function to compute the 7 statistics of daily streamflow\n#' used by Archfield et al., under revision (June 2013). \n#' @importFrom lubridate month\n#' @importFrom lubridate year\n#' @importFrom lmom .samlmu\n#' @export\n#' @examples\n#' x<-sampleData[c(\"date\",\"discharge\")]\n#' magSeven <- calc_magnifSeven(x)\ncalc_magnifSeven<-function(x,yearType = \"water\",digits=3) {\n \n #Check data inputs\n x <- validate_data(x,yearType = yearType)\n \n #calculate some stuff for use later\n x$month_val <- lubridate::month(x$date)\n \n #Compute L-moment ratios for time series so consistent in function\n complmom <- lmom::.samlmu(x$discharge)\n complmom[2] = complmom[2] / complmom[1]\n complmom = round(complmom, digits=2)\n lam1<-complmom[1]\n tau2<-complmom[2]\n tau3<-complmom[3]\n tau4<-complmom[4]\n \n #Compute AR(1) correlation coefficienct\n calc_ar1v<-calc_ar1(x,yearType = yearType,digits=digits)\n \n get_seasonality_vars <- get_seasonality(x, yearType = yearType)\n amplitude<-get_seasonality_vars[1]\n phase<-get_seasonality_vars[2]\n \n\n #Combine all indices into 1 dataframe and return\n magnif7 <- data.frame(indice = c(\"lam1\",\"tau2\",\"tau3\",\"tau4\",\"ar1\",\"amplitude\",\"phase\"),\n statistic = c(lam1,tau2,tau3,tau4,calc_ar1v,amplitude,phase),\n stringsAsFactors = F)\n\n magnif7$statistic <- round(magnif7$statistic,digits=digits)\n \n return(magnif7)\n}\n", "meta": {"hexsha": "28dbf934ac6d76f3895ae72d80b6972499c22f7e", "size": 2056, "ext": "r", "lang": "R", "max_stars_repo_path": "R/calc_magnifSeven.r", "max_stars_repo_name": "jds485/EflowStats", "max_stars_repo_head_hexsha": "79851fcbb22a076be19804f081ffdbb82d6acdfe", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2015-08-26T22:28:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T08:57:44.000Z", "max_issues_repo_path": "R/calc_magnifSeven.r", "max_issues_repo_name": "jds485/EflowStats", "max_issues_repo_head_hexsha": "79851fcbb22a076be19804f081ffdbb82d6acdfe", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 135, "max_issues_repo_issues_event_min_datetime": "2015-01-14T01:20:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T01:53:09.000Z", "max_forks_repo_path": "R/calc_magnifSeven.r", "max_forks_repo_name": "jds485/EflowStats", "max_forks_repo_head_hexsha": "79851fcbb22a076be19804f081ffdbb82d6acdfe", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2015-01-13T22:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:53.000Z", "avg_line_length": 41.9591836735, "max_line_length": 134, "alphanum_fraction": 0.6546692607, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6785637042025501}} {"text": "# Function definitions for the normal-inverse-gamma distribution.\n# The parameters of the distribution (mu, lambda, alpha, beta) are as defined here:\n# https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution\n\n# NOTE: The functions below require the function definitions in invgamma.r\n\ndnorminvgamma <- function(x, sigma2, mu, lambda, alpha, beta) {\n # The pdf of the normal-inverse-gamma distribution at x (mean) and sigma2 (variance).\n return(dnorm(x, mu, sqrt(sigma2 / lambda)) * dinvgamma(sigma2, alpha, beta));\n}\n\nrnorminvgamma <- function(n, mu, lambda, alpha, beta) {\n # Draw n samples from the normal-inverse-gamma distribution.\n # Returns a matrix where each column contains a (x, sigma2) sample.\n sigma2 = rinvgamma(n, alpha, beta); # Sample sigma^2 from the inverse-gamma\n x = rnorm(n, mu, sqrt(sigma2 / lambda)); # Sample x from the normal\n return(t(matrix(c(x, sigma2), nrow=n, ncol=2)));\n}\n", "meta": {"hexsha": "4524a00dee079c3c1168b0adee201fb9da176340", "size": 934, "ext": "r", "lang": "R", "max_stars_repo_path": "norminvgamma.r", "max_stars_repo_name": "cscheffler/rdistributions", "max_stars_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "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": "norminvgamma.r", "max_issues_repo_name": "cscheffler/rdistributions", "max_issues_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "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": "norminvgamma.r", "max_forks_repo_name": "cscheffler/rdistributions", "max_forks_repo_head_hexsha": "a649d455bb4c58974656b5e224e7dc84941525df", "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.1578947368, "max_line_length": 89, "alphanum_fraction": 0.7152034261, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6784801963758307}} {"text": "#' winddir\n#'\n#' @description Calculate meteorological wind direction from cartesian components u and v.\n#' \n#' @param u numeric U zonal component (m/s) .\n#' @param v numeric V meridian component (m/s).\n#' @return wind direction provenience\n#' @author Istituto per la Bioeconomia CNR Firenze Italy Alfonso Crisci \\email{alfonso.crisci@@ibe.cnr.it}\n#' @keywords Meteorological Wind direction \n#' \n#' \n#' @export\n\nwinddir <- function(u, v) {\n (180 / pi) * atan(u/v) + ifelse(v>0,180,ifelse(u>0,360,0))\n}", "meta": {"hexsha": "8a4052a9b387a7ced073eabc2025abde22fb5861", "size": 522, "ext": "r", "lang": "R", "max_stars_repo_path": "R/winddir.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/winddir.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/winddir.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": 32.625, "max_line_length": 108, "alphanum_fraction": 0.6724137931, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6780933643676668}} {"text": "#!/usr/bin/Rscript\n# Copyright © 2016 Martin Ueding \n# Licensed under the MIT license.\n\niterapply = function(start, func, length) {\n result = numeric(length)\n result[1] = start\n for (i in 2:length) {\n result[i] = func(result[i - 1])\n }\n return(result)\n}\n\nget_next_x = function(x, alpha) {\n epsilon = runif(1)\n return (alpha * x + (1 - alpha) * epsilon)\n}\n\ngenerate_series = function(alpha) {\n return (iterapply(0, function(x) { return (get_next_x(x, alpha)) }, 100000))\n}\n\nxs = generate_series(0.1)\nhist(xs, freq=FALSE)\n\nxs = generate_series(0.3)\nhist(xs, freq=FALSE)\n\nxs = generate_series(0.7)\nhist(xs, freq=FALSE)\n\nxs = generate_series(0.9)\nhist(xs, freq=FALSE)\n", "meta": {"hexsha": "afe15f1883478b8c47c0982f43bc60cad627248b", "size": 717, "ext": "r", "lang": "R", "max_stars_repo_path": "04/pseudo-random.r", "max_stars_repo_name": "martin-ueding/exercides-2016", "max_stars_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": "04/pseudo-random.r", "max_issues_repo_name": "martin-ueding/exercides-2016", "max_issues_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": "04/pseudo-random.r", "max_forks_repo_name": "martin-ueding/exercides-2016", "max_forks_repo_head_hexsha": "a16a5a8bd9b0acd5f84ef5156e0a220c7ceb27e7", "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": 21.0882352941, "max_line_length": 80, "alphanum_fraction": 0.6513249651, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6780933539871561}} {"text": "##' @title\n##' Regression Metrics Parameters\n##'\n##' @description\n##' Documentation for shared parameters of functions that compute regression\n##' metrics.\n##'\n##' @param actual \\code{[numeric]} The ground truth numeric vector.\n##' @param predicted \\code{[numeric]} The predicted numeric vector, where each\n##' element in the vector is a prediction of the corresponding elements in\n##' \\code{actual}.\n##' @name regression_params\n##' @include helper-functions.r\nNULL\n\n\n##' @title\n##' Explained Variance\n##'\n##'\n##' @description\n##'\n##' \\code{mtr_explained_variance} computes explained variance, also known as\n##' explained variation, which is interpreted as the percentage of variation in\n##' one numeric vector explained by another. The best possible score is 1.0,\n##' lower values are worse.\n##'\n##' @inheritParams regression_params\n##' @importFrom stats var\n##' @seealso \\code{\\link{mtr_r2}}\n##' @return A numeric scalar output\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, -0.5, 2, 7)\n##' pred <- c(2.5, 0.0, 2, 8)\n##' mtr_explained_variance(act, pred)\n##'\n##' act <- c(1.1, 1.9, 3.0, 4.4, 5.0, 5.6)\n##' pred <- c(0.9, 1.8, 2.5, 4.5, 5.0, 6.2)\n##' mtr_explained_variance(act, pred)\n##'\n##' @export\nmtr_explained_variance <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n\n exp_var <- 1 - (var(actual - predicted) / var(actual))\n exp_var\n}\n\n\n##' @title\n##' Max Error\n##'\n##'\n##' @description\n##'\n##' \\code{mtr_max_error} computes the maximum residual error, a metric that\n##' captures the worst error between the predicted value and the true value.\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, 2, 7, 1)\n##' pred <- c(9, 2, 7, 1)\n##' mtr_max_error(act, pred)\n##'\n##'\n##' @export\nmtr_max_error <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n me <- max(abs(actual - predicted), na.rm = TRUE)\n me\n}\n\n\n\n##' @title\n##' Mean Absolute Error\n##'\n##'\n##' @description\n##'\n##' \\code{mtr_mean_absolute_error} is a measure of difference between the\n##' predicted value and the true value.\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name mae\n##' @examples\n##'\n##' act <- c(3, -0.5, 2, 7)\n##' pred <- c(2.5, 0.0, 2, 8)\n##' mtr_mean_absolute_error(act, pred)\n##' mtr_mae(act, pred)\n##'\n##'\n##' @export\nmtr_mean_absolute_error <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n mae <- mean(abs(actual - predicted), na.rm = TRUE)\n mae\n}\n\n\n##' @export\n##' @rdname mae\nmtr_mae <- mtr_mean_absolute_error\n\n\n\n##' @title\n##' Mean Squared Error\n##'\n##'\n##'\n##' @description test\n##'\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name mse\n##' @export\n##'\n##'\n##'\n##' @export\n##'\n##'\n##'\n##'\n##' @export\nmtr_mean_squared_error <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n mse <- mean((actual - predicted)^2, na.rm = TRUE)\n mse\n}\n\n##' @export\n##' @rdname mse\nmtr_mse <- mtr_mean_squared_error\n\n\n\n##' @title\n##' Root Mean Squared Error Function\n##'\n##'\n##' @description test\n##'\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, -0.5, 2, 7)\n##' pred <- c(2.5, 0.0, 2, 8)\n##' mtr_mean_squared_error(act, pred)\n##'\n##'\n##' @export\nmtr_root_mean_squared_error <- function(actual, predicted) {\n sqrt(mtr_mean_squared_error(actual, predicted))\n}\n\n\n\n##' @title\n##' Mean Squared Log Error\n##'\n##'\n##'\n##' @description test\n##'\n##'\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @name msle\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, 5, 2.5, 7)\n##' pred <- c(2.5, 5, 4, 8)\n##' mtr_mean_squared_log_error(act, pred)\n##'\n##'\n##' @export\nmtr_mean_squared_log_error <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n msle <- mtr_mean_squared_error(log1p(actual), log1p(predicted))\n msle\n}\n\n\n##' @export\n##' @rdname msle\nmtr_msle <- mtr_mean_squared_log_error\n\n\n\n\n##' @title\n##' Median Absolute Error\n##'\n##'\n##'\n##' @description test\n##'\n##'\n##' @details test\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @importFrom stats median\n##' @return A numeric scalar output\n##' @name mdae\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, -0.5, 2, 7)\n##' pred <- c(2.5, 0.0, 2, 8)\n##' mtr_median_absolute_error(act, pred)\n##'\n##'\n##' @export\nmtr_median_absolute_error <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n mdae <- median(abs(actual - predicted), na.rm = TRUE)\n mdae\n}\n\n\n##' @export\n##' @rdname mdae\nmtr_mdae <- mtr_median_absolute_error\n\n\n\n##' @title R2 Score\n##'\n##'\n##'\n##' @description test\n##'\n##'\n##'\n##'\n##' @inheritParams regression_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(3, -0.5, 2, 7)\n##' pred <- c(2.5, 0.0, 2, 8)\n##' mtr_r2(act, pred)\n##'\n##'\n##' @export\nmtr_r2 <- function(actual, predicted) {\n\n check_equal_length(actual, predicted)\n\n if (length(predicted) < 2) {\n warning(\"R^2 is not applicable for less than two instances\", call. = FALSE)\n return(NA_real_)\n }\n\n numerator <- sum((actual - predicted) ^ 2)\n denominator <- sum((actual - mean(actual)) ^ 2)\n\n zero_numerator <- numerator == 0\n zero_denominator <- denominator == 0\n\n if (zero_numerator || zero_denominator) return(0)\n\n r2 <- 1 - numerator / denominator\n r2\n}\n", "meta": {"hexsha": "d28422c203b06ac1a6fe7ee2db9253909859a2bd", "size": 5584, "ext": "r", "lang": "R", "max_stars_repo_path": "R/regression.r", "max_stars_repo_name": "maiing/metrics", "max_stars_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "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/regression.r", "max_issues_repo_name": "maiing/metrics", "max_issues_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "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/regression.r", "max_forks_repo_name": "maiing/metrics", "max_forks_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "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": 18.6133333333, "max_line_length": 83, "alphanum_fraction": 0.625, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6780917048798001}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\nrm(list=ls(all=TRUE))\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\ncat(\"Stan version:\", stan_version(), \"\\n\")\r\nstanmodelcode <- \"\r\n\r\n\r\n#### define GP function\r\nfunctions {\r\n\r\nreal normal_generalized_poisson_log(int y, real theta, real lambda, real sigob) { \r\n return (log(theta) \r\n + (y - 1) * log(theta + y * lambda) \r\n - lgamma(y + 1) \r\n - y * lambda \r\n - theta)*(y<=200)\r\n +(normal_lpdf(y|theta,sigob))*(y>200);\r\n\r\n } \r\n\r\n}\r\n\r\n\r\n#### define our data, integer value\r\ndata {\r\nint N;\r\nint y[N];\r\nreal E[N];\r\n}\r\n\r\n\r\n#### define parameters \r\nparameters {\r\n\r\nreal lambda;\r\nreal u;\r\nreal b7;\r\nreal sig2;\r\nvector[N] e;\r\nreal sigob;\r\n}\r\n\r\n\r\n#### define some parameters which is the function of other parameters \r\ntransformed parameters {\r\nvector[N] mu;\r\n\r\n### define the mean function\r\n\r\n\r\nmu[1] <- y[1]; ## not tested\r\n\r\n for (n in 2:N) {\r\n\t\r\n mu[n] <- (mu[n-1]^b7)*exp(u+e[n]); \r\n\t \r\n\t }\r\n\r\n}\r\n\r\n\r\n\r\n##### define piror and likelihood function\r\nmodel {\r\nlambda~uniform(-1,1);\r\nu ~ normal(0.2,0.1);\r\nb7 ~ normal(0.98,0.1);\r\nsig2 ~ gamma(1,1); \r\ne~normal(0,sig2);\r\nsigob ~ uniform(100,1100);\r\n\r\nfor (j in 1:N) {\r\n\r\ny[j] ~ normal_generalized_poisson( mu[j]*E[j], lambda, sigob);\r\n}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n#### calculate DIC\r\ngenerated quantities {\r\nvector[N] log_lik;\r\nreal dev; // deviance\r\n\r\n\r\n for (n in 1:N){\r\n log_lik[n] <- normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n dev <- 0;\r\n for ( n in 1:N ) {\r\n dev <- dev + (-2) * normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\"\r\n\r\n\r\n###### \r\n\r\n\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covid19modelrisk/output/forecast\")\r\n\r\n## y=read.csv(\"COVID-19_confirmed__Germany.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Italy.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Japan.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Spain.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__US.csv\")\r\n y=read.csv(\"COVID-19_confirmed_Australia.csv\")\r\n\r\ny=y[,2]\r\n\r\n\r\n\r\n\r\nE=rep(1,length(y))\r\n\r\nN=length(y)\r\ndat <- list(N = N, y = y,E=E)\r\n\r\n\r\n#### initial values\r\ninits =list(list(lambda=0,u=0.2,b7=0.98,sig2=0.0005,e=rep(0.01,N),sigob=1000)) ### 134\r\n\r\n\r\nfit <- stan(model_code = stanmodelcode, model_name = \"example\",init =inits,\r\ndata = dat, warmup=10000,iter = 100000, chains = 1, seed=999,thin=1)\r\nprint(fit,digits = 4)\r\n\r\n\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################### trace plot\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nk=6\r\n\r\npdf(paste(\"M9_\",abn[k],\"_p1.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"u\",\"b7\",\"lambda\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\npdf(paste(\"M9_\",abn[k],\"_p2.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"sigob\",\"sig2\"), inc_warmup = T, nrow = 2, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n################## plot 30/45/60/ length(y)\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M9_\",abn[k],\"_30.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=30\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M9_\",abn[k],\"_45.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=45\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M9_\",abn[k],\"_60.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=60\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M9_\",abn[k],\"_all.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n######## log plot ####################################################\r\n\r\nk=1\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\ny=log(y)\r\nEpars_m=log(Epars_m)\r\nEpars_9=log(Epars_9)\r\nEpars_5=log(Epars_5)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/plot\")\r\n\r\npdf(paste(\"M9_\",abn[k],\"_log.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M9 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n#####################################################################################################################################################\r\n###################################### forecast ###################################\r\n\r\nGP.r <- function(L, s)\r\n{\r\n\r\nv=0\r\nLp=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nsLp=Lp\r\n\r\n# calculate the vector of cum pmf\r\nv=1\r\nwhile((sLp<0.9999999) & ((L + v * s )> 0)) \r\n{Lp1=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nLp=c(Lp,Lp1)\r\nsLp=sLp+Lp1\r\nv=v+1\r\n}\r\n\r\ncsLp=c(cumsum(Lp),1) ##### add a max for it \r\nx=length(Lp)\r\n\r\n# first check if you are in the first interval\r\n\r\nU = runif(1)\r\nB = FALSE\r\ni = 1\r\n \r\nwhile(B == FALSE) { \r\n \r\n if(U > csLp[i]) ### U may greater than max of csLp if do not set 1\r\n { i=i+1}\r\n else\r\n {X=i-1\r\n B=TRUE} \r\n\r\n}\r\n\r\nreturn(X)\r\n\r\n}\r\n\r\n################################################ as.data.frame(fit@sim[[1]][[1]])[1,]\r\n\r\nP=20\r\nMu=matrix(,nrow=90000,ncol=P)\r\nX=matrix(,nrow=90000,ncol=P)\r\n\r\n\r\nlambda_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,1]\r\nu_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,2]\r\nb7_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,3]\r\nsig2_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,4]\r\n\r\n\r\nset.seed(999)\r\n\r\nfor (r in 1:90000){\r\n\r\n\r\n\r\nMu[r,1]=y[length(y)]\r\nfor (s in 1:(P-1) ){\r\n\r\ne=rnorm(1,0,sig2_p[r])\r\n\r\nMu[r,s+1]=(Mu[r,s]^b7_p[r])*exp(u_p[r]+e)\r\n}}\r\n\r\n\r\n\r\nsigob=1000\r\nfor (r in 1:90000){\r\nfor (s in 1:P ){\r\n\r\nX[r,s]=rnorm(1,Mu[r,s], sigob)\r\n\r\n\r\n}}\r\n\r\n\r\n#for (r in 1:90){\r\n#for (s in 1:P ){\r\n#X[r,s]=GP.r(Mu[r,s]*(1-lambda_p[r]), lambda_p[r])\r\n#}}\r\n\r\n#X=Mu\r\n\r\n\r\nXm=apply(X,2,mean)\r\n\r\nX5 <- apply( X , 2 , quantile, probs=0.05 )\r\n\r\nX9 <- apply( X , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\nZm=c(y,Xm)\r\nZ5=c(y,X5)\r\nZ9=c(y,X9)\r\n\r\n\r\nk=3\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nm=length(Zm)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/forecast\")\r\npdf(paste(\"M9_\",abn[k],\"_F.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Z9[1:m]), Z5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Z9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Z5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###########################################################################################################################\r\n\r\n\r\n\r\nn=length(y)\r\n\r\n\r\nu=0.2\r\nb7=0.98\r\n\r\nx=c()\r\nx[1]=100\r\nfor (i in 1:(n-1) ){\r\n\r\nx[i+1]=(x[i]^b7)*exp(u)\r\n}\r\nx=round(x)\r\nx\r\n\r\n\r\n\r\nplot(y,ylim=c(min(y,x),max(y,x)))\r\npar(new=TRUE)\r\nplot(x,col=\"red\",ylim=c(min(y,x),max(y,x)))\r\n\r\n\r\n\r\n\r\n\r\n\r\n#############################################################\r\n##### GM\r\n\r\nu=0.25\r\nb7=0.98\r\n\r\n\r\n\r\n##### IT\r\n\r\nu=0.25\r\nb7=0.98\r\n\r\n\r\n##### JP\r\nu=0.21\r\nb7=0.98\r\n\r\n\r\n\r\n##### SP\r\nu=0.25\r\nb7=0.98\r\n\r\n\r\n##### UK\r\nu=0.25\r\nb7=0.98\r\n\r\n\r\n\r\n##### US\r\nu=0.3\r\nb7=0.98\r\n\r\n\r\n\r\n##### AU\r\nu=0.2\r\nb7=0.98\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ba33d1e9ffea2b406c545fc0b615900687f5f948", "size": 13050, "ext": "r", "lang": "R", "max_stars_repo_path": "R/M9 run.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M9 run.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M9 run.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 22.0439189189, "max_line_length": 178, "alphanum_fraction": 0.5367816092, "num_tokens": 4823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6780808384598348}} {"text": "\nibp = function(n, a) {\n\n dishes = max(1, rpois(1, a))\n diners = data.frame(dish = seq(dishes), diners = rep(1, dishes))\n buffet = list(buffet = diners, choices = list(seq(dishes)))\n\n for (j in seq(n - 1)) {\n buffet = arrival(buffet, a)\n }\n buffet\n }\n\narrival = function(b, a) {\n config = b$buffet\n existing_choices = b$choices\n j = length(existing_choices) + 1\n n = nrow(config)\n\n num_new_dishes = rpois(1, a / j)\n new_dishes =\n if (num_new_dishes > 0) {\n (n + 1):(n + num_new_dishes)\n } else {\n numeric(0)\n }\n\n probs = sapply(config$diners, function(n) { n / j })\n selection = rbinom(n, 1, prob = probs) == 1\n choices = list(c(as.integer(row.names(config[selection,])), new_dishes))\n diners = with(config, replace(diners, selection, diners[selection] + 1))\n\n buffet = data.frame(\n dish = seq(n + num_new_dishes)\n , diners = c(diners, rep(1, num_new_dishes))\n )\n\n list(buffet = buffet, choices = c(existing_choices, choices))\n }\n\nibp_matrix = function(buffet) {\n dishes = do.call(max, buffet$choices)\n index = function(j) { as.numeric(seq(dishes) %in% j) }\n rows = lapply(buffet$choices, index)\n\n do.call(rbind, rows)\n }\n\n", "meta": {"hexsha": "706d10b93fd5dc8b6c6be6de4979a6f4a23973e5", "size": 1214, "ext": "r", "lang": "R", "max_stars_repo_path": "indian-buffet-process/src/ibp.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": "indian-buffet-process/src/ibp.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": "indian-buffet-process/src/ibp.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": 24.7755102041, "max_line_length": 77, "alphanum_fraction": 0.6046128501, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6779552459500073}} {"text": "# boot.r - very simple code used to generate the 500 bootstrap\r\n# samples from the lab 1 exercise.\r\n\r\n\r\nlab2bigd <- lab2bigr <- rep(0,500)\r\na <- lab1$Y[1:10] # data from group A\r\nb <- lab1$Y[11:20] # data from group B\r\n\r\nfor (i in 1:500) {\r\n ma <- mean(sample(a,10,repl=T));\r\n mb <- mean(sample(b,10,repl=T))\r\n \r\n lab2bigd[i] <- mb - ma;\r\n lab2bigr[i] <- mb/ma;\r\n }\r\n \r\nlab2bigd <- sort(lab2bigd)\r\nlab2bigr <- sort(lab2bigr)\r\n \r\n ", "meta": {"hexsha": "2e34b4b5a3db213eb40fe3dbd1bfab5a3a53607d", "size": 457, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/boot.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/boot.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/boot.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.85, "max_line_length": 65, "alphanum_fraction": 0.5689277899, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.6778636431926431}} {"text": "#' Converts a correlation metric (rho) to a z-score\n#'\n#' @param rho A Pearson's r\n#' @return A z-score\nfisher_r2z = function(rho) 0.5 * log((1 + rho)/(1 - rho))\n\n#' Tests for significant correlations in a population\n#'\n#' @param mat A sample matrix with [obs x samples]\n#' @return A matrix with p-values\ntest = function(mat, self=0) {\n mat = as.matrix(mat)\n n = ncol(mat)\n p.mat = matrix(NA, n, n, dimnames=dimnames(mat)[c(2,2)])\n diag(p.mat) = self\n for (i in 1:(n - 1))\n for (j in (i + 1):n)\n p.mat[i,j] = p.mat[j,i] = cor.test(mat[,i], mat[,j])$p.value\n p.mat\n}\n\n#' Tests for significant changes in correlation between two populations\n#'\n#' TODO: all stat tests should return a data.frame\n#'\n#' @param x A sample matrix with [obs x variables]\n#' @param y A samples matrix with [obs x variables]\n#' @param return_cor Return cor matrices of x and y (default: FALSE)\n#' @param pad Pad cor(x/y) assuming zero correlation\n#' @return A symmetric matrix of p-values [variables x variables]\ndiff_test = function(x, y, return_cor=FALSE, pad=FALSE) {\n if (pad) {\n cboth = narray::stack(list(x=cor(x), y=cor(y)), along=3, fill=0)\n corx = cboth[,,\"x\"]\n cory = cboth[,,\"y\"]\n } else {\n narray::intersect(x, y, along=2)\n corx = cor(x)\n cory = cor(y)\n }\n delta_cor = cory - corx\n\n za = fisher_r2z(corx)\n zb = fisher_r2z(cory)\n\n na = narray::rrep(apply(x, 2, function(x) sum(!is.na(x))), ncol(x))\n nb = narray::rrep(apply(y, 2, function(x) sum(!is.na(x))), ncol(y))\n\n se = sqrt((1/(na-3))+(1/(nb-3)))\n z = (za-zb)/se\n\n pval = 2*pnorm(-abs(z))\n\n if (return_cor)\n list(x=corx, y=cory, delta_cor = delta_cor, p.value = pval)\n else\n list(delta_cor = delta_cor, p.value = pval)\n}\n", "meta": {"hexsha": "2b46fd107de66e46beb5a78a059692844adaf42d", "size": 1809, "ext": "r", "lang": "R", "max_stars_repo_path": "stats/correlation.r", "max_stars_repo_name": "mschubert/ebits", "max_stars_repo_head_hexsha": "e9c4a3d883fb9fbcbfd4689becca0fe2e5cbdbe5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-20T12:36:29.000Z", "max_issues_repo_path": "stats/correlation.r", "max_issues_repo_name": "mschubert/ebits", "max_issues_repo_head_hexsha": "e9c4a3d883fb9fbcbfd4689becca0fe2e5cbdbe5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2017-01-14T14:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T15:49:11.000Z", "max_forks_repo_path": "stats/correlation.r", "max_forks_repo_name": "mschubert/ebits", "max_forks_repo_head_hexsha": "e9c4a3d883fb9fbcbfd4689becca0fe2e5cbdbe5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-04-18T19:06:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-18T19:06:36.000Z", "avg_line_length": 30.6610169492, "max_line_length": 72, "alphanum_fraction": 0.5914870094, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6774336817681904}} {"text": "counting_sort <- function(arr, minval, maxval) {\n r <- arr\n z <- 1\n for(i in minval:maxval) {\n cnt = sum(arr == i)\n while(cnt > 0) {\n r[z] = i\n z <- z + 1\n cnt <- cnt - 1\n }\n }\n r\n}\n\n# 140+1 instead of 140, since random numbers generated\n# by runif are always less than the given maximum;\n# floor(a number at most 140.9999...) is 140\nages <- floor(runif(100, 0, 140+1))\nsorted <- counting_sort(ages, 0, 140)\nprint(sorted)\n", "meta": {"hexsha": "f5970ba46cbfcb990d27d14241beda76c3c3561e", "size": 451, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.r", "max_stars_repo_name": "mullikine/RosettaCodeData", "max_stars_repo_head_hexsha": "4f0027c6ce83daa36118ee8b67915a13cd23ab67", "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/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.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/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.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": 21.4761904762, "max_line_length": 54, "alphanum_fraction": 0.5875831486, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6773558881750212}} {"text": "# Calculating a Confidence Interval From a Normal Distribution\r\nn<-50\r\na<-27.3\r\ns<-12.1\r\n# we will use a 99% confidence level and wish to find the confidence interval\r\nmargin <- qnorm(0.995)*s/sqrt(n)\r\nleft_i <- a-margin\r\nright_i <- a+margin\r\nprint(\"Confidence interval is\")\r\nprint(left_i)\r\nprint(right_i)", "meta": {"hexsha": "d7d978bafbeb2613c34bbafa09215843e1fbb323", "size": 307, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.2/Ex5_2.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.2/Ex5_2.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.2/Ex5_2.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 27.9090909091, "max_line_length": 79, "alphanum_fraction": 0.7198697068, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6773507661076472}} {"text": "# Program to find the H.C.F of two input number\n# define a function\nhcf <- function(x, y) {\n# choose the smaller number\nif(x > y) {\nsmaller = y\n} else {\nsmaller = x\n}\nfor(i in 1:smaller) {\nif((x %% i == 0) && (y %% i == 0)) {\nhcf = i\n}\n}\nreturn(hcf)\n}\n# take input from the user\nnum1 = as.integer(readline(prompt = \"Enter first number: \"))\nnum2 = as.integer(readline(prompt = \"Enter second number: \"))\nprint(paste(\"The H.C.F. of\", num1,\"and\", num2,\"is\", hcf(num1, num2)))", "meta": {"hexsha": "cf2e3420e33e1efd0f7ac9908d5ad58050b272ba", "size": 471, "ext": "r", "lang": "R", "max_stars_repo_path": "program_to_find_GCD.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "program_to_find_GCD.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "program_to_find_GCD.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": 23.55, "max_line_length": 69, "alphanum_fraction": 0.6220806794, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6773152779484963}} {"text": "#Simulate positions for n=8 sities\r\npos <- read.table(\"optimaltransport.ascii\",header=F)\r\np = nrow(pos)\r\nset.seed(345)\r\npar(mfrow=c(1,1))\r\nplot(pos)\r\ndev.copy2pdf(file=\"../doc/example_trav_sale.pdf\")\r\n\r\n#Calculate pairwise distances between cities\r\nd = as.matrix((dist(pos,diag=TRUE,upper=TRUE)))\r\n#Convert to vector in order to access many components at a time\r\nd = as.vector(d)\r\n\r\n#Perform neighbor search, simulated annealing\r\n#Random inizialization\r\n#We implement the fact that the distribution must start and finish at home town\r\ntheta = c(1, sample(2:p,p-1), 1)\r\n\r\n#Convert sequential pairs into index in the d-vector\r\nind = (theta[-p]-1)*p+theta[-1]\r\n#Calculate total distance of order\r\nV = sum(d[ind])\r\nVseq = V\r\nNumit=50000\r\nfor(i in 1:Numit)\r\n{\r\n tau = 100/i\r\n #tau = 1/log(i+1)\r\n #tau <- (0.8 + i/Numit/10)*tau\r\n #we never change the position of index=1 (home)\r\n ind2 = sample(2:p,2,replace=F)\r\n theta2 = theta\r\n theta2[ind2[1]] = theta[ind2[2]]\r\n theta2[ind2[2]] = theta[ind2[1]]\r\n ind2 = (theta2[-p]-1)*p+theta2[-1]\r\n V2 = sum(d[ind2])\r\n prob = exp((V-V2)/tau)\r\n u = runif(1)\r\n if(u= x) / pos\n ) # true pos. rate\n false_pos <- sapply(\n probabilities,\n function(x) sum(neg_probs >= x) / neg\n )\n if (is.null(model.name)) {\n result <- data.frame(true_pos, false_pos)\n } else {\n result <- data.frame(true_pos, false_pos, model.name)\n }\n\n result %>% add_row(true_pos = 0, false_pos = 0) %>% arrange(false_pos, true_pos)\n}\n\n# this function calculates precision and recall\ncalc_PR <- function(probabilities, known_truth, model.name = NULL) {\n outcome <- as.numeric(factor(known_truth)) - 1\n pos <- sum(outcome) # total known positives\n pos_probs <- outcome * probabilities # probabilities for known positives\n neg_probs <- (1 - outcome) * probabilities # probabilities for known negatives\n recall <- sapply(\n probabilities,\n function(x) sum(pos_probs >= x) / pos\n )\n precision <- sapply(\n probabilities,\n function(x) sum(pos_probs >= x) / (sum(pos_probs >= x) + sum(neg_probs >= x))\n )\n if (is.null(model.name)) {\n result <- data.frame(precision, recall)\n } else {\n result <- data.frame(precision, recall, model.name)\n }\n\n result %>% arrange(recall, desc(precision))\n}\n# set seed to reproduce the given results\nset.seed(1234)\n\n# simulate predictor values for 2 different outcomes\n# predictors will be normally distributed\n# two classes are balanced at time 1\noutcome1 <- data.frame(predictor = rnorm(1000, mean = -5, sd = 5), outcome = 1, time = 1)\noutcome2 <- data.frame(predictor = rnorm(1000, mean = 5, sd = 5), outcome = 2, time = 1)\noutcome1 %>% rbind(outcome2) -> df_t1\n\n# two classes are imbalanced at time 2\noutcome1 <- outcome1 %>% mutate(time = 2)\noutcome2 <- data.frame(predictor = rnorm(50, mean = 5, sd = 5), outcome = 2, time = 2)\noutcome1 %>% rbind(outcome2) -> df_t2\n\n# combine the two datasets\nrbind(df_t1, df_t2) -> anim_data\n\n# make an animation with distributions of linear predictors\np_dist <- ggplot(anim_data) +\n geom_density(aes(x = predictor, fill = factor(outcome), stat(count)), alpha = 0.7, color = NA) +\n geom_hline(yintercept = 0, color = \"black\", size = 0.5, linetype = 2) +\n scale_x_continuous(limits = c(-30, 30)) +\n scale_fill_manual(values = c(\"#C04A56\", \"#3D8CF1\")) +\n transition_states(time, transition_length = 1, state_length = 1) +\n ggtitle(\" \") + # adding an emtpy title to align y axis with ROC plot\n theme_cowplot() +\n theme(legend.position = \"none\")\n\n# calculate ROC curves and AUC values\nanim_data %>%\n mutate(probabilities = exp(predictor) / (1 + exp(predictor))) %>% # calculate probabilities for linear predictors\n group_by(time) %>%\n do(results = calc_ROC(\n probabilities = .$probabilities, # calculate TP rate and FP rate for every possible cutoff\n known_truth = .$outcome\n )) %>%\n group_by(time) %>%\n do(as.data.frame(.$results)) %>% # store output from calc_ROC() in the data frame\n mutate(delta = false_pos - lag(false_pos)) %>% # calculate AUC values\n mutate(AUC = sprintf(\"%.3f\", sum(delta * true_pos, na.rm = T))) -> ROC\n\n# reverse factor in `AUC` variable so the AUC values match to the timing of the animation\nROC$AUC <- fct_inorder(ROC$AUC)\n\n# calculate precision-recall curves\nanim_data %>%\n mutate(probabilities = exp(predictor) / (1 + exp(predictor))) %>% # calculate probabilities for linear predictors\n group_by(time) %>%\n do(results = calc_PR(\n probabilities = .$probabilities, # calculate precision and recall\n known_truth = .$outcome\n )) %>%\n group_by(time) %>%\n do(as.data.frame(.$results)) -> PR\n\n# make an animation with ROC curves\np_ROC <- ggplot(data = ROC, aes(x = false_pos, y = true_pos)) +\n geom_line(size = 1) +\n geom_abline(intercept = 0, slope = 1) +\n transition_states(AUC, transition_length = 1, state_length = 1) +\n labs(title = \"AUC = {closest_state}\") +\n scale_x_continuous(name = \"false positive rate\") +\n scale_y_continuous(name = \"true positive rate\") +\n theme_cowplot()\n\n# make an animation with precision-recall curves\np_PR <- ggplot(data = PR, aes(x = recall, y = precision)) +\n geom_line(size = 1) +\n transition_states(time, transition_length = 1, state_length = 1) +\n scale_x_continuous(limits = c(0, 1)) +\n scale_y_continuous(limits = c(0, 1)) +\n ggtitle(\" \") + # adding an emtpy title to align y axis with ROC plot\n theme_cowplot()\n\n# save each animation as individual frames\n# each frame will be saved as a PNG image\np_dist_gif <- animate(p_dist,\n device = \"png\",\n width = 400,\n height = 400,\n renderer = file_renderer(\"../animations/gganim_imbalance\", prefix = \"p_dist\", overwrite = TRUE)\n)\np_ROC_gif <- animate(p_ROC,\n device = \"png\",\n width = 400,\n height = 400,\n renderer = file_renderer(\"../animations/gganim_imbalance\", prefix = \"p_ROC\", overwrite = TRUE)\n)\np_PR_gif <- animate(p_PR,\n device = \"png\",\n width = 400,\n height = 400,\n renderer = file_renderer(\"../animations/gganim_imbalance\", prefix = \"p_PR\", overwrite = TRUE)\n)\n\n# stitch animations together\n# read the first image (frame) of each animation\na <- image_read(p_dist_gif[[1]])\nb <- image_read(p_ROC_gif[[1]])\nc <- image_read(p_PR_gif[[1]])\n# combine the two images into a single image\ncombined <- image_append(c(a, b, c))\nnew_gif <- c(combined)\nfor (i in 2:100) { # combine images frame by frame\n a <- image_read(p_dist_gif[[i]])\n b <- image_read(p_ROC_gif[[i]])\n c <- image_read(p_PR_gif[[i]])\n combined <- image_append(c(a, b, c))\n new_gif <- c(new_gif, combined)\n}\n\n# make an animation of the combined images\ncombined_gif <- image_animate(new_gif)\n# save as gif\nimage_write(combined_gif, \"../animations/imbalance.gif\")\n", "meta": {"hexsha": "c7fa6e06b74a2f039b520fff3e05d42f50405b4f", "size": 6155, "ext": "r", "lang": "R", "max_stars_repo_path": "ROC_animation/R/animate_imbalance.r", "max_stars_repo_name": "mkalutkiewicz/open_projects", "max_stars_repo_head_hexsha": "78baafde020474c31d78b4a310c23e807a0cb630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 235, "max_stars_repo_stars_event_min_datetime": "2018-11-18T04:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:18:03.000Z", "max_issues_repo_path": "ROC_animation/R/animate_imbalance.r", "max_issues_repo_name": "mkalutkiewicz/open_projects", "max_issues_repo_head_hexsha": "78baafde020474c31d78b4a310c23e807a0cb630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-29T18:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T16:42:27.000Z", "max_forks_repo_path": "ROC_animation/R/animate_imbalance.r", "max_forks_repo_name": "mkalutkiewicz/open_projects", "max_forks_repo_head_hexsha": "78baafde020474c31d78b4a310c23e807a0cb630", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2018-11-19T18:53:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:06:34.000Z", "avg_line_length": 36.4201183432, "max_line_length": 115, "alphanum_fraction": 0.6904955321, "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6770456977539009}} {"text": "\n\n\n#' @title Create objects of type '\"BasicBayesian\"'.\n#' @description\n#' A Basic Bayesian Object is with following conditional dependency structure: \n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{X|theta \\sim F(theta)}\n#' Where H(gamma) is usually called \"the prior distribution\", F(theta) is called \"the observation distribution\". Objects of type \"LinearGaussianGaussian\", \"GaussianGaussian\", \"GaussianInvWishart\", \"GaussianNIW\", \"GaussianNIG\", \"CatDirichlet\" and \"CatDP\" are all \"BasicBayesian\"s.\n#' \n#' @seealso \\code{\\link{LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{CatDP}} for Categorical-DP conjugate structure ...\n#' @param ENV The environment where you want to create the BasicBayesian object\n#' @return An object of class \"BasicBayesian\".\n#' @export\nBasicBayesian <- function(ENV=parent.frame()){\n object <- new.env(parent = ENV)\n \n object$gamma <- list()\n object$H <- character(0)\n object$F <- character(0)\n\n class(object) <- c(\"BasicBayesian\",\"BayesianBrick\")\n return(object)\n\n}\n\n#' @title Get sample sufficient statistics\n#' @description\n#' This is a generic function that will generate the sufficient statistics of a given Bayesian bricks object. i.e. \\cr\n#' for the model structure:\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' get the sufficient statistics T(x). \\cr\n#' For a given sample set x, each row of x is an observation, and a Bayesian bricks object obj. \\code{sufficientStatistics()} return the sufficient statistics for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item SA = \\eqn{sum_{i=1:N} A_i^T Sigma^{-1} A_i}\n#' \\item SAx = \\eqn{sum_{i=1:N} A_i^T Sigma^{-1} (x_i-b_i)}\n#' }\n#' See \\code{?sufficientStatistics.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the row sums of the samples.\n#' }\n#' See \\code{?sufficientStatistics.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known. \\cr\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the sample scatter matrix centered on the mean vector.\n#' }\n#' See \\code{?sufficientStatistics.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the row sums of the samples.\n#' \\item S: the uncentered sample scatter matrix.\n#' }\n#' See \\code{?sufficientStatistics.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item SXx: covariance of X and x\n#' \\item SX: the uncentered sample scatter matrix.\n#' \\item Sx: the variance of x\n#' }\n#' See \\code{?sufficientStatistics.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' The sufficient statistics of CatDirichlet object can either be x itself, or the counts of the unique labels in x.\\cr\n#' See \\code{?sufficientStatistics.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' The sufficient statistics of CatDP object can either be x itself, or the counts of the unique labels in x.\\cr\n#' See \\code{?sufficientStatistics.CatDP} for details.\n#' }\n#' \\subsection{class(obj)=\"DP\"}{\n#' Where\n#' \\deqn{pi|alpha \\sim DP(alpha,U)}\n#' \\deqn{z|pi \\sim Categorical(pi)}\n#' \\deqn{theta_z|psi \\sim H0(psi)}\n#' \\deqn{x|theta_z,z \\sim F(theta_z)}\n#' The sufficient statistics of \"DP\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"DP\".\n#' See \\code{?sufficientStatistics.DP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP\"}{\n#' Where\n#' \\deqn{G|gamma \\sim DP(gamma,U)}\n#' \\deqn{pi_j|G,alpha \\sim DP(alpha,G), j = 1:J}\n#' \\deqn{z|pi_j \\sim Categorical(pi_j)}\n#' \\deqn{k|z,G \\sim Categorical(G),\\textrm{ if z is a sample from the base measure G}}\n#' \\deqn{theta_k|psi \\sim H0(psi)}\n#' The sufficient statistics of \"HDP\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"HDP\".\n#' See \\code{?sufficientStatistics.HDP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP2\"}{\n#' Where\n#' \\deqn{G |eta \\sim DP(eta,U)}\n#' \\deqn{G_m|gamma,G \\sim DP(gamma,G), m = 1:M}\n#' \\deqn{pi_{mj}|G_m,alpha \\sim DP(alpha,G_m), j = 1:J_m}\n#' \\deqn{z|pi_{mj} \\sim Categorical(pi_{mj})}\n#' \\deqn{k|z,G_m \\sim Categorical(G_m),\\textrm{ if z is a sample from the base measure} G_m}\n#' \\deqn{u|k,G \\sim Categorical(G),\\textrm{ if k is a sample from the base measure} G}\n#' \\deqn{theta_u|psi \\sim H0(psi)}\n#' \\deqn{x|theta_u,u \\sim F(theta_u)}\n#' The sufficient statistics of \"HDP2\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"HDP2\".\n#' See \\code{?sufficientStatistics.HDP2} for details.\n#' }\n#'\n#' @seealso \\code{\\link{sufficientStatistics.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{sufficientStatistics.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{sufficientStatistics.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{sufficientStatistics.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{sufficientStatistics.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{sufficientStatistics.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{sufficientStatistics.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj a \"BayesianBrick\" object used to select a method.\n#' @param x a set of samples.\n#' @param ... further arguments passed to or from other methods.\n#' @return An object of corresponding sufficient statistics class, such as \"ssGaussian\"\n#' @export\n#' @examples\n#' x <- rGaussian(10,mu = 1,Sigma = 1)\n#' obj <- GaussianNIW() #an GaussianNIW object\n#' sufficientStatistics(obj=obj,x=x)\nsufficientStatistics <- function(obj,x,...) UseMethod(\"sufficientStatistics\")\n\n#' @title Get weighted sample sufficient statistics\n#' @description\n#' This is a generic function that will generate the weighted sufficient statistics of a given \"BayesianBrick\" object. That is, for the model structure:\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' get the weighted sufficient statistics T(x).\n#' For a given sample set x, each row of x is an observation, the sample weights w, and a Bayesian bricks object obj. \\code{sufficientStatistics_Weighted()} return the weighted sufficient statistics for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item SA = \\eqn{sum_{i=1:N} w_i A_i^T Sigma^{-1} A_i}\n#' \\item SAx = \\eqn{sum_{i=1:N} w_i A_i^T Sigma^{-1} (x_i-b_i)}\n#' }\n#' See \\code{?sufficientStatistics.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the row sums of the samples.\n#' }\n#' See \\code{?sufficientStatistics_Weighted.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known. \\cr\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the sample scatter matrix centered on the mean vector.\n#' }\n#' See \\code{?sufficientStatistics_Weighted.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item xsum: the row sums of the samples.\n#' \\item S: the uncentered sample scatter matrix.\n#' }\n#' See \\code{?sufficientStatistics_Weighted.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' The sufficient statistics are:\n#' \\itemize{\n#' \\item N: the effective number of samples.\n#' \\item SXx: covariance of X and x\n#' \\item SX: the uncentered sample scatter matrix.\n#' \\item Sx: the variance of x\n#' }\n#' See \\code{?sufficientStatistics_Weighted.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' The sufficient statistics of CatDirichlet object can either be x itself, or the counts of the unique labels in x.\\cr\n#' See \\code{?sufficientStatistics_Weighted.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' The sufficient statistics of CatDP object can either be x itself, or the counts of the unique labels in x.\\cr\n#' See \\code{?sufficientStatistics_Weighted.CatDP} for details.\n#' }\n#' \\subsection{class(obj)=\"DP\"}{\n#' Where\n#' \\deqn{pi|alpha \\sim DP(alpha,U)}\n#' \\deqn{z|pi \\sim Categorical(pi)}\n#' \\deqn{theta_z|psi \\sim H0(psi)}\n#' \\deqn{x|theta_z,z \\sim F(theta_z)}\n#' The sufficient statistics of \"DP\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"DP\".\n#' See \\code{?sufficientStatistics_Weighted.DP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP\"}{\n#' Where\n#' \\deqn{G|gamma \\sim DP(gamma,U)}\n#' \\deqn{pi_j|G,alpha \\sim DP(alpha,G), j = 1:J}\n#' \\deqn{z|pi_j \\sim Categorical(pi_j)}\n#' \\deqn{k|z,G \\sim Categorical(G),\\textrm{ if z is a sample from the base measure G}}\n#' \\deqn{theta_k|psi \\sim H0(psi)}\n#' The sufficient statistics of \"HDP\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"HDP\".\n#' See \\code{?sufficientStatistics_Weighted.HDP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP2\"}{\n#' Where\n#' \\deqn{G |eta \\sim DP(eta,U)}\n#' \\deqn{G_m|gamma,G \\sim DP(gamma,G), m = 1:M}\n#' \\deqn{pi_{mj}|G_m,alpha \\sim DP(alpha,G_m), j = 1:J_m}\n#' \\deqn{z|pi_{mj} \\sim Categorical(pi_{mj})}\n#' \\deqn{k|z,G_m \\sim Categorical(G_m),\\textrm{ if z is a sample from the base measure } G_m}\n#' \\deqn{u|k,G \\sim Categorical(G),\\textrm{ if k is a sample from the base measure } G_m}\n#' \\deqn{theta_u|psi \\sim H0(psi)}\n#' \\deqn{x|theta_u,u \\sim F(theta_u)}\n#' The sufficient statistics of \"HDP2\" object is the same sufficient statistics of the \"BasicBayesian\" inside the \"HDP2\".\n#' See \\code{?sufficientStatistics_Weighted.HDP2} for details.\n#' }\n#' @seealso \\code{\\link{sufficientStatistics_Weighted.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{sufficientStatistics_Weighted.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{sufficientStatistics_Weighted.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{sufficientStatistics_Weighted.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{sufficientStatistics_Weighted.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{sufficientStatistics_Weighted.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{sufficientStatistics_Weighted.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj a \"BayesianBrick\" object used to select a method.\n#' @param x a set of samples.\n#' @param w numeric, sample weights.\n#' @param ... further arguments passed to or from other methods.\n#' @return An object of corresponding sufficient statistics class, such as \"ssGaussian\"\n#' @export\n#' @examples\n#' \\donttest{\n#' x <- rGaussian(10,mu = 1,Sigma = 1)\n#' w <- runif(10)\n#' obj <- GaussianNIW() #an GaussianNIW object\n#' sufficientStatistics_Weighted(obj=obj,x=x,w=w)\n#' }\nsufficientStatistics_Weighted <- function(obj,x,w,...) UseMethod(\"sufficientStatistics_Weighted\")\n\n#' @title update the prior distribution with sufficient statistics\n#' @description update the prior distribution with sufficient statistics\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return None, or an error message if the update fails.\nposterior_bySufficientStatistics <- function(obj,...) UseMethod(\"posterior_bySufficientStatistics\")\n\n#' @title update the prior distribution with sufficient statistics\n#' @description\n#' This is a generic function that will update the prior distribution of a \"BayesianBrick\" object by adding information of the observation's sufficient statistics. i.e. for the model structure:\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' update gamma to gamma_posterior by adding the information of x to gamma.\\cr\n#' For a given sample set x or it's sufficient statistics ss, and a Bayesian bricks object obj, \\code{posterior()} will update the posterior parameters in obj for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{posterior()} will update m and S in obj.\n#' See \\code{?posterior.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{posterior()} will update m and S in obj.\n#' See \\code{?posterior.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{posterior()} will update v and S in obj.\n#' See \\code{?posterior.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{posterior()} will update m, k, v and S in obj.\n#' See \\code{?posterior.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{posterior()} will update m, V, a and b in obj.\n#' See \\code{?posterior.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{posterior()} will update alpha in obj.\n#' See \\code{?posterior.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{posterior()} will update alpha in obj.\n#' See \\code{?posterior.CatDP} for details.\n#' }\n#' \\subsection{class(obj)=\"DP\"}{\n#' Where\n#' \\deqn{pi|alpha \\sim DP(alpha,U)}\n#' \\deqn{z|pi \\sim Categorical(pi)}\n#' \\deqn{theta_z|psi \\sim H0(psi)}\n#' \\deqn{x|theta_z,z \\sim F(theta_z)}\n#' \\code{posterior()} will update alpha and psi in obj.\n#' See \\code{?posterior.DP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP\"}{\n#' Where\n#' \\deqn{G|gamma \\sim DP(gamma,U)}\n#' \\deqn{pi_j|G,alpha \\sim DP(alpha,G), j = 1:J}\n#' \\deqn{z|pi_j \\sim Categorical(pi_j)}\n#' \\deqn{k|z,G \\sim Categorical(G),\\textrm{ if z is a sample from the base measure G}}\n#' \\deqn{theta_k|psi \\sim H0(psi)}\n#' \\code{posterior()} will update gamma, alpha and psi in obj.\n#' See \\code{?posterior.HDP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP2\"}{\n#' Where\n#' \\deqn{G |eta \\sim DP(eta,U)}\n#' \\deqn{G_m|gamma,G \\sim DP(gamma,G), m = 1:M}\n#' \\deqn{pi_{mj}|G_m,alpha \\sim DP(alpha,G_m), j = 1:J_m}\n#' \\deqn{z|pi_{mj} \\sim Categorical(pi_{mj})}\n#' \\deqn{k|z,G_m \\sim Categorical(G_m),\\textrm{ if z is a sample from the base measure } G_m}\n#' \\deqn{u|k,G \\sim Categorical(G),\\textrm{ if k is a sample from the base measure} G}\n#' \\deqn{theta_u|psi \\sim H0(psi)}\n#' \\deqn{x|theta_u,u \\sim F(theta_u)}\n#' \\code{posterior()} will update eta, gamma, alpha and psi in obj.\n#' See \\code{?posterior.HDP2} for details.\n#' }\n#'\n#' @seealso \\code{\\link{posterior.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{posterior.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{posterior.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{posterior.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{posterior.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{posterior.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{posterior.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return None, or an error message if the update fails.\n#' @export\nposterior <- function(obj,...) UseMethod(\"posterior\")\n\n#' @title update the prior distribution with sufficient statistics\n#' @description update the prior distribution with sufficient statistics\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... other parameters.\n#' @return None, or an error message if the update fails.\nposteriorDiscard_bySufficientStatistics <- function(obj,...) UseMethod(\"posteriorDiscard_bySufficientStatistics\")\n\n#' @title update the prior distribution with sufficient statistics\n#' @description\n#' Contrary to posterior(), posteriorDiscard() a generic function that will update the prior distribution of a \"BayesianBrick\" object by removing the information provided by the observation's sufficient statistics. i.e. for the model structure:\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' update gamma to gamma_posterior by removing the information of x from gamma.\n#' For a given sample set x or it's sufficient statistics ss, and a Bayesian bricks object obj, \\code{posteriorDiscard()} will update the posterior parameters in obj for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{posteriorDiscard()} will update m and S in obj.\n#' See \\code{?posteriorDiscard.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{posteriorDiscard()} will update m and S in obj.\n#' See \\code{?posteriorDiscard.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{posteriorDiscard()} will update v and S in obj.\n#' See \\code{?posteriorDiscard.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{posteriorDiscard()} will update m, k, v and S in obj.\n#' See \\code{?posteriorDiscard.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n# X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{posteriorDiscard()} will update m, V, a and b in obj.\n#' See \\code{?posteriorDiscard.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{posteriorDiscard()} will update alpha in obj.\n#' See \\code{?posteriorDiscard.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{posteriorDiscard()} will update alpha in obj.\n#' See \\code{?posteriorDiscard.CatDP} for details.\n#' }\n#' \\subsection{class(obj)=\"DP\"}{\n#' Where\n#' \\deqn{pi|alpha \\sim DP(alpha,U)}\n#' \\deqn{z|pi \\sim Categorical(pi)}\n#' \\deqn{theta_z|psi \\sim H0(psi)}\n#' \\deqn{x|theta_z,z \\sim F(theta_z)}\n#' \\code{posteriorDiscard()} will update alpha and psi in obj.\n#' See \\code{?posteriorDiscard.DP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP\"}{\n#' Where\n#' \\deqn{G|gamma \\sim DP(gamma,U)}\n#' \\deqn{pi_j|G,alpha \\sim DP(alpha,G), j = 1:J}\n#' \\deqn{z|pi_j \\sim Categorical(pi_j)}\n#' \\deqn{k|z,G \\sim Categorical(G),\\textrm{ if z is a sample from the base measure } G}\n#' \\deqn{theta_k|psi \\sim H0(psi)}\n#' \\code{posteriorDiscard()} will update gamma, alpha and psi in obj.\n#' See \\code{?posteriorDiscard.HDP} for details.\n#' }\n#' \\subsection{class(obj)=\"HDP2\"}{\n#' Where\n#' \\deqn{G |eta \\sim DP(eta,U)}\n#' \\deqn{G_m|gamma,G \\sim DP(gamma,G), m = 1:M}\n#' \\deqn{pi_{mj}|G_m,alpha \\sim DP(alpha,G_m), j = 1:J_m}\n#' \\deqn{z|pi_{mj} \\sim Categorical(pi_{mj})}\n#' \\deqn{k|z,G_m \\sim Categorical(G_m),\\textrm{ if z is a sample from the base measure } G_m}\n#' \\deqn{u|k,G \\sim Categorical(G),\\textrm{ if k is a sample from the base measure } G}\n#' \\deqn{theta_u|psi \\sim H0(psi)}\n#' \\deqn{x|theta_u,u \\sim F(theta_u)}\n#' \\code{posteriorDiscard()} will update eta, gamma, alpha and psi in obj.\n#' See \\code{?posteriorDiscard.HDP2} for details.\n#' }\n#'\n#' @seealso \\code{\\link{posteriorDiscard.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{posteriorDiscard.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{posteriorDiscard.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{posteriorDiscard.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{posteriorDiscard.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{posteriorDiscard.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{posteriorDiscard.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return None, or an error message if the update fails.\n#' @export\nposteriorDiscard <- function(obj,...) UseMethod(\"posteriorDiscard\")\n\n#' @title Get the Maximum A Posteriori(MAP) estimate of a \"BayesianBrick\" object\n#' @description\n#' This is a generic function that will generate the MAP estimate of a given \"BayesianBrick\" object. For the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' MAP estimate of theta is theta_MAP = argmax_theta p(theta|gamma,x).\n#' For a given Bayesian bricks object obj, the MAP estimate will be:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{MAP()} will return the MAP estimate of z.\n#' See \\code{?MAP.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{MAP()} will return the MAP estimate of mu.\n#' See \\code{?MAP.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{MAP()} will return the MAP estimate of Sigma.\n#' See \\code{?MAP.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{MAP()} will return the MAP estimate of mu and Sigma.\n#' See \\code{?MAP.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{MAP()} will return the MAP estimate of beta and sigma^2.\n#' See \\code{?MAP.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{MAP()} will return the MAP estimate of pi.\n#' See \\code{?MAP.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{MAP()} will return the MAP estimate of pi.\n#' See \\code{?MAP.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{MAP.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{MAP.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{MAP.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{MAP.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{MAP.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{MAP.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{MAP.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return A list of the MAP estimates\n#' @export\nMAP <- function(obj,...) UseMethod(\"MAP\")\n\n#' @title Get the Mean Posterior Estimate(MPE) of a \"BayesianBrick\" object\n#' @description\n#' This is a generic function that will generate the MPE estimate of a given \"BayesianBrick\" object. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' MPE estimate of theta is theta_MPE = E(theta|gamma,x), E() is the expectation function.\n#' For a given Bayesian bricks object obj, the MPE estimate will be:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{MPE()} will return the MPE estimate of z.\n#' See \\code{?MPE.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{MPE()} will return the MPE estimate of mu.\n#' See \\code{?MPE.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{MPE()} will return the MPE estimate of Sigma.\n#' See \\code{?MPE.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{MPE()} will return the MPE estimate of mu and Sigma.\n#' See \\code{?MPE.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{MPE()} will return the MPE estimate of beta and sigma^2.\n#' See \\code{?MPE.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{MPE()} will return the MPE estimate of pi.\n#' See \\code{?MPE.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{MPE()} will return the MPE estimate of pi.\n#' See \\code{?MPE.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{MPE.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{MPE.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{MPE.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{MPE.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{MPE.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{MPE.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{MPE.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return A list of MPE estimates\n#' @export\nMPE <- function(obj,...) UseMethod(\"MPE\")\n\n#' @title Get the density from the posterior distribution.\n#' @description\n#' This is a generic function that will generate the the density value of the posterior distribution. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' get the probability density/mass from the distribution \\eqn{theta \\sim H(gamma)}.\n#' For a given Bayesian bricks object obj and an observation of theta, \\code{dPosterior()} will calculate the density value for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{dPosterior()} will return p(theta|m,S)\n#' See \\code{?dPosterior.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{dPosterior()} will return p(mu|m,S)\n#' See \\code{?dPosterior.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{dPosterior()} will return p(Sigma|v,S)\n#' See \\code{?dPosterior.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{dPosterior()} will return p(mu,Sigma|m,k,v,S)\n#' See \\code{?dPosterior.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{dPosterior()} will return p(beta,sigma^2|m,V,a,b)\n#' See \\code{?dPosterior.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{dPosterior()} will return p(pi|alpha)\n#' See \\code{?dPosterior.CatDirichlet} for details.\n#' }\n#' @seealso \\code{\\link{dPosterior.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{dPosterior.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{dPosterior.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{dPosterior.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{dPosterior.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{dPosterior.CatDirichlet}} for Categorical-Dirichlet conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return numeric, the density value\n#' @export\ndPosterior <- function(obj,...) UseMethod(\"dPosterior\")\n\n#' @title Generate random samples from the posterior distribution\n#' @description\n#' This is a generic function that will generate random samples from the posterior distribution. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' generate random sampels of theta from the distribution \\eqn{theta \\sim H(gamma)}.\n#' For a given Bayesian bricks object obj, \\code{rPosterior()} will generate random samples for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{rPosterior()} will generate random samples from Gaussian(m,S)\n#' See \\code{?rPosterior.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{rPosterior()} will generate random samples from Gaussian(m,S)\n#' See \\code{?rPosterior.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{rPosterior()} will generate random samples from InvWishart(v,S)\n#' See \\code{?rPosterior.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{rPosterior()} will generate random samples from NIW(m,k,v,S)\n#' See \\code{?rPosterior.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{rPosterior()} will generate random samples from NIG(m,V,a,b)\n#' See \\code{?rPosterior.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{rPosterior()} will generate random samples from Dirichlet(alpha)\n#' See \\code{?rPosterior.CatDirichlet} for details.\n#' }\n#' @seealso \\code{\\link{rPosterior.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{rPosterior.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{rPosterior.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{rPosterior.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{rPosterior.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{rPosterior.CatDirichlet}} for Categorical-Dirichlet conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return numeric, the density value\n#' @export\nrPosterior <- function(obj,...) UseMethod(\"rPosterior\")\n\n#' @title Get the marginal likelihood of a \"BayesianBrick\" object\n#' @description\n#' This is a generic function that will generate the marginal likelihood of a set of observations conditioned on a given \"BayesianBrick\" object. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' Marginal likelihood is p(x|gamma), p() is the probability density/mass function for continuous/discrete x.\n#' For a given Bayesian bricks object obj and a sample set x, \\code{marginalLikelihood_bySufficientStatistics()} will calculate the marginal likelihood for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|m,S,A,b,Sigma)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|m,S,Sigma)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|mu,v,S)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|m,k,v,S)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x,X|m,V,a,b)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|alpha)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{marginalLikelihood_bySufficientStatistics()} will return p(x|alpha)\n#' See \\code{?marginalLikelihood_bySufficientStatistics.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{marginalLikelihood_bySufficientStatistics.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{marginalLikelihood_bySufficientStatistics.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return numeric, the marginal likelihood\n#' @export\nmarginalLikelihood_bySufficientStatistics <- function(obj,...) UseMethod(\"marginalLikelihood_bySufficientStatistics\")\n\n#' @title Get the marginal likelihood of a \"BayesianBrick\" object\n#' @description\n#' This is a generic function that will generate the marginal likelihood of a set of observations conditioned on a given \"BayesianBrick\" object. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' Marginal likelihood is p(x|gamma), p() is the probability density/mass function for continuous/discrete x.\n#' For a given Bayesian bricks object obj and a sample set x, \\code{marginalLikelihood()} will calculate the marginal likelihood for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{marginalLikelihood()} will return p(x|m,S,A,b,Sigma)\n#' See \\code{?marginalLikelihood.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{marginalLikelihood()} will return p(x|m,S,Sigma)\n#' See \\code{?marginalLikelihood.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{marginalLikelihood()} will return p(x|mu,v,S)\n#' See \\code{?marginalLikelihood.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{marginalLikelihood()} will return p(x|m,k,v,S)\n#' See \\code{?marginalLikelihood.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{marginalLikelihood()} will return p(x,X|m,V,a,b)\n#' See \\code{?marginalLikelihood.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{marginalLikelihood()} will return p(x|alpha)\n#' See \\code{?marginalLikelihood.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{marginalLikelihood()} will return p(x|alpha)\n#' See \\code{?marginalLikelihood.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{marginalLikelihood.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{marginalLikelihood.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{marginalLikelihood.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{marginalLikelihood.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{marginalLikelihood.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{marginalLikelihood.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{marginalLikelihood.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return numeric, the marginal likelihood\n#' @export\nmarginalLikelihood <- function(obj,...) UseMethod(\"marginalLikelihood\")\n\n#' @title Get the density value of the posterior predictive distribution\n#' @description\n#' This is a generic function that will generate the the density value of the posterior predictive distribution. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' get the probability density/mass of the posterior predictive distribution of a new sample x_new: p(x_new|gamma).\n#' For a given Bayesian bricks object obj and a new sample x, \\code{dPosteriorPredictive()} will calculate the marginal likelihood for different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{dPosteriorPredictive()} will return p(x|m,S,A,b,Sigma)\n#' See \\code{?dPosteriorPredictive.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{dPosteriorPredictive()} will return p(x|m,S,Sigma)\n#' See \\code{?dPosteriorPredictive.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{dPosteriorPredictive()} will return p(x|mu,v,S)\n#' See \\code{?dPosteriorPredictive.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{dPosteriorPredictive()} will return p(x|m,k,v,S)\n#' See \\code{?dPosteriorPredictive.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{dPosteriorPredictive()} will return p(x,X|m,V,a,b)\n#' See \\code{?dPosteriorPredictive.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{dPosteriorPredictive()} will return p(x|alpha)\n#' See \\code{?dPosteriorPredictive.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{dPosteriorPredictive()} will return p(x|alpha)\n#' See \\code{?dPosteriorPredictive.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{dPosteriorPredictive.LinearGaussianGaussian}} for Linear Gaussian and Gaussian conjugate structure, \\code{\\link{dPosteriorPredictive.GaussianGaussian}} for Gaussian-Gaussian conjugate structure, \\code{\\link{dPosteriorPredictive.GaussianInvWishart}} for Gaussian-Inverse-Wishart conjugate structure, \\code{\\link{dPosteriorPredictive.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{dPosteriorPredictive.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{dPosteriorPredictive.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{dPosteriorPredictive.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param ... further arguments passed to or from other methods.\n#' @return numeric, the density value\n#' @export\ndPosteriorPredictive <- function(obj,...) UseMethod(\"dPosteriorPredictive\")\n\n#' @title Generate random samples from the posterior predictive distribution\n#' @description\n#' This is a generic function that will generate random samples from the posterior predictive distribution. i.e. for the model structure: \\cr\n#' \\deqn{theta|gamma \\sim H(gamma)}\n#' \\deqn{x|theta \\sim F(theta)}\n#' generate x_new from the posterior predictive distribution of x|gamma.\n#' For a given Bayesian bricks object obj, \\code{rPosteriorPredictive()} will generate random samples from different model structures:\n#' \\subsection{class(obj)=\"LinearGaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(A z + b, Sigma)}\n#' \\deqn{z \\sim Gaussian(m,S)}\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|m,S,A,b,Sigma\n#' See \\code{?rPosteriorPredictive.LinearGaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianGaussian\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{mu \\sim Gaussian(m,S)}\n#' Sigma is known.\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|m,S,Sigma\n#' See \\code{?rPosteriorPredictive.GaussianGaussian} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianInvWishart\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' mu is known.\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|mu,v,S\n#' See \\code{?rPosteriorPredictive.GaussianInvWishart} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIW\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(mu,Sigma)}\n#' \\deqn{Sigma \\sim InvWishart(v,S)}\n#' \\deqn{mu \\sim Gaussian(m,Sigma/k)}\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|m,k,v,S\n#' See \\code{?rPosteriorPredictive.GaussianNIW} for details.\n#' }\n#' \\subsection{class(obj)=\"GaussianNIG\"}{\n#' Where\n#' \\deqn{x \\sim Gaussian(X beta,sigma^2)}\n#' \\deqn{sigma^2 \\sim InvGamma(a,b)}\n#' \\deqn{beta \\sim Gaussian(m,sigma^2 V)}\n#' X is a row vector, or a design matrix where each row is an obervation.\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x,X|m,V,a,b\n#' See \\code{?rPosteriorPredictive.GaussianNIG} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDirichlet\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim Dirichlet(alpha)}\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|alpha\n#' See \\code{?rPosteriorPredictive.CatDirichlet} for details.\n#' }\n#' \\subsection{class(obj)=\"CatDP\"}{\n#' Where\n#' \\deqn{x \\sim Categorical(pi)}\n#' \\deqn{pi \\sim DirichletProcess(alpha)}\n#' \\code{rPosteriorPredictive()} will generate samples from the distribution of x|alpha\n#' See \\code{?rPosteriorPredictive.CatDP} for details.\n#' }\n#' @seealso \\code{\\link{rPosteriorPredictive.GaussianNIW}} for Gaussian-NIW conjugate structure, \\code{\\link{rPosteriorPredictive.GaussianNIG}} for Gaussian-NIG conjugate structure, \\code{\\link{rPosteriorPredictive.CatDirichlet}} for Categorical-Dirichlet conjugate structure, \\code{\\link{rPosteriorPredictive.CatDP}} for Categorical-DP conjugate structure ...\n#' @param obj A \"BayesianBrick\" object used to select a method.\n#' @param n integer, specify the number of samples to be generated.\n#' @param ... further arguments passed to or from other methods.\n#' @return a matrix or vector or list of random samples, depends on the type of 'obj'.\n#' @export\nrPosteriorPredictive <- function(obj,n,...) UseMethod(\"rPosteriorPredictive\")\n\n\n\n#' Print the content of an BasicBayesian object\n#' @param x An object of the target type.\n#' @param ... other parameters passed to print.\n#' @return None.\n#' @export\nprint.BasicBayesian <- function(x,...){\n cat(\"Prior distribution: \",x$H,\"\\n\")\n cat(\"Observation distribution: \",x$F,\"\\n\") \n cat(\"Parameters for prior distribution:\\n\")\n print(x$gamma)\n}\n\n#' a internal version of \"is\", only for this package\n#' @param object an object to be test with\n#' @param class2 the class you want to test\n#' @return logical, return TRUE if 'class2' is in 'class(object)'.\n#' @noRd\n.is <- function(object,class2){\n isTRUE(class2 %in% class(object))\n}\n\n#' log multivariate gamma function\n#' @param a numeric, a numeric vector to be evaluated.\n#' @param p numeric, the dimension.\n#' @return numeric, the log value of the multivariate gamma function.\n#' @noRd\n.lmvgamma <- function(a,p){\n sapply(a,function(ai){\n p*(p-1)/4*log(pi)+ sum(lgamma(ai+(1-(1:p))/2))\n },simplify = TRUE)\n}\n\n#' determinant of a matrix\n#' @param m numeric or matrix. When m is a numeric vector, it's treated as a diagonal matrix.\n#' @return logical, return TRUE if 'class2' is in 'class(object)'.\n#' @noRd\n.det <- function(m){\n if(is.matrix(m)){\n base::det(m)\n }else if(is.vector(m)){\n base::prod(m)\n }\n}\n\n#' @title log sum exp\n#' @description For each row l of a matrix x, calculate log(sum(exp(l))).\n#' @param x matrix, the values in x a all logged. If x is a numeric vector, it will be converted to a matrix with 1 row.\n#' @return numeric, the logsumexp of each row of x.\n#' @export\n#' @examples\n#' \\donttest{\n#' ## Normalize the rows of x to make them sum up to 1\n#' x <- matrix(runif(6,-1000,-20),nrow=2)\n#' x <- x-logsumexp(x)\n#' x <- exp(x)\n#' rowSums(x)\n#' }\nlogsumexp <- function(x){\n if(is.vector(x)) x <- matrix(x,nrow =1L)\n else if(!is.matrix(x)) x <- as.matrix(x)\n x <- as.matrix(x)\n a <- apply(x,1,max)\n log(rowSums(exp(x-a)))+a\n}\n\n#' @title Inverse of a positive definite symmetric matrix\n#' @description Use Cholesky decomposition to calculate the inverse of S, where \\eqn{S = A'A}, A is a upper diagonal matrix. inv(S) = inv(A)inv(A)'.\n#' @param S a symmetric positive definitive matrix.\n#' @param returnUpper logical, return inv(A) if returnUpper=TRUE,return inv(S) if returnUpper=FALSE, default FALSE.\n#' @return A matrix, the inverse of \"S\".\n#' @export\n#' @examples\n#' Sigma = matrix(c(2,1,1,2),2,2) # some positive definite symmetric matrix\n#' pdsInverse(Sigma) # get inv(Sigma)\n#' pdsInverse(Sigma,returnUpper=TRUE) # get inv(A), where Sigma=A'A, A is upper triangle\npdsInverse <- function(S,returnUpper=FALSE){\n if(missing(S)) stop(\"'S' not specified!\")\n if(length(S)==1L){\n if(returnUpper==FALSE)\n return(1/S)\n else\n return(sqrt(1/S))\n }else{\n A <- chol(S) #Cholesky decomposition S=A'A\n Ai <- backsolve(A,diag(nrow(S))) #A_i = A^(-1)\n if(returnUpper==FALSE)\n return(crossprod(t(Ai)))\n else\n return(Ai)\n }\n}\n\n#' @title determinant of a positive definite symmetric matrix\n#' @description Use Cholesky decomposition to calculate the determinant of S, where \\eqn{S = A'A}, A is a upper diagonal matrix. det(S) = det(A)*det(A).\n#' @param S a symmetric positive definitive matrix.\n#' @param LOG logical, return log(det(S)) if TRUE, return det(S) if FALSE, default FALSE.\n#' @return A matrix, the determinant of \"S\".\n#' @export\n#' @examples\n#' Sigma = matrix(c(1.3,1,1,2),2,2) # some positive definite symmetric matrix\n#' pdsDeterminant(Sigma) # get inv(Sigma)\n#' pdsDeterminant(Sigma,LOG=TRUE) # get inv(Sigma)\n#' pdsInverse(Sigma,returnUpper=TRUE) # get inv(A), where Sigma=A'A, A is upper triangle\npdsDeterminant <- function(S,LOG=FALSE){\n if(missing(S)) stop(\"'S' not specified!\")\n if(length(S)==1L){\n return(S)\n }else{\n A <- chol(S) #Cholesky decomposition S=A'A\n if(LOG){\n return(sum(log(diag(A))*2))\n }else{\n return(prod(diag(A))^2)\n }\n }\n}\n\n#' @title additional release questions\n#' @description This is a list of additional questions you want devtools::release() to ask when releasing your package.\nrelease_questions <- function(){\n c(\"Have you run 'R CMD build PACKAGE_FOLDER' and 'R CMD check PACKAGE_VERSION.tar.gz' before the release?\",\n \"Have you removed underscores '_' in \\\\text{...}? For exmple \\\\text{G_m} is not allowed!!\",\n \"Have you set the correct version number?\",\n \"Have you removed the irrelevant code blocks, such as 'if(FALSE){...}', from your R files?\",\n \"Have you add all the files in ./R folder to DESCRIPTION?\",\n \"Have you removed the unfinished examples from the vignette?\",\n \"Have you add all the references to README and function documentation?\",\n \"Have you replaced all of the dontrun{} with donttest{}?\",\n \"Have you rebuilt README.md from README.raw.md, using publish_markdown.r? Note that you have to rebuild README.md whenever you modified README.raw.md.\",\n \"Have you removed all the par() settings in the examples? Check your documentations by run \\\"grep 'par(' ./man/*\\\" from the terminal.\"\n )\n}\n", "meta": {"hexsha": "ef1688399cc8e72cadf1c5f990163c7a0b30554b", "size": 55915, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Bayesian_Bricks.r", "max_stars_repo_name": "chenhaotian/Bayesian-Bricks", "max_stars_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-04T09:43:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T13:54:37.000Z", "max_issues_repo_path": "R/Bayesian_Bricks.r", "max_issues_repo_name": "chenhaotian/Bayesian-Bricks", "max_issues_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "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/Bayesian_Bricks.r", "max_forks_repo_name": "chenhaotian/Bayesian-Bricks", "max_forks_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T18:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T18:13:09.000Z", "avg_line_length": 47.9545454545, "max_line_length": 818, "alphanum_fraction": 0.7042832871, "num_tokens": 16235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6770456906647382}} {"text": "#' Find Basic Feasible Solutions\n#' \n#' @param A\n#' Coefficient matrix of the convex set.\n#' @param b\n#' Right hand side.\n#' \n#' @return\n#' A 'bfs' object.\n#' \n#' @export\nfind.bfs <- function(A, b)\n{\n combs <- combn(ncol(A), nrow(A))\n len.out <- ncol(combs)\n \n bfs <- vector(mode=\"list\", length=len.out)\n indices <- vector(mode=\"list\", length=len.out)\n \n for (ind in 1:len.out)\n {\n columns <- combs[, ind]\n \n B <- A[, columns]\n \n if (det(B) == 0)\n {\n bfs[[ind]] <- \"Not defined\"\n indices[[ind]] <- columns\n next\n }\n \n # B^{-1}b\n bfs[[ind]] <- solve(B, b)\n indices[[ind]] <- columns\n }\n \n ret <- list(bfs=bfs, indices=indices, n=ncol(A))\n class(ret) <- \"bfs\"\n ret\n}\n\n\n\n#' Find Extreme Points\n#'\n#' Find extreme points.\n#' \n#' @param bfs\n#' A bfs object, returned from \\code{find.bfs()}.\n#' \n#' @return \n#' An 'ep' class object.\n#' \n#' @export\nfind.ep <- function(bfs)\n{\n if (class(bfs) != \"bfs\")\n stop(\"Argument 'bfs' must be a 'bfs' object.\")\n \n eps <- list()\n epsind <- 1L\n \n for (ind in 1:length(bfs$bfs))\n {\n Binv_b <- bfs$bfs[[ind]]\n \n inds <- bfs$indices[[ind]]\n \n if (is.character(Binv_b))\n next\n else if (all(Binv_b >= 0))\n {\n sol <- rep(0, bfs$n)\n sol[inds] <- Binv_b\n \n eps[[epsind]] <- sol\n epsind <- epsind + 1L\n }\n }\n \n class(eps) <- \"ep\"\n eps\n}\n\n\n\noptimize_lp <- function(z, ep, optfun)\n{\n if (class(ep) != \"ep\")\n stop(\"Argument 'ep' must be of class 'ep'\")\n \n z <- c(z, rep(0, length(ep[[1]])-length(z)))\n# if (length(z) != length(ep[[1]]))\n# stop(\"Objective function coefficients 'z' must match the number of coefficients of the ep's\")\n \n if (class(optfun) != \"function\")\n stop(\"Argument 'optfun' must be a function of a single variable\")\n \n zfun <- function(x) crossprod(z, x)\n vals <- sapply(ep, zfun)\n op <- optfun(vals)\n at <- which(op == vals)\n \n \n optimum <- list(optimum=op, soln=ep[[at]])\n class(optimum) <- \"lp_solution\"\n \n optimum\n}\n\n\n\n#' Optimize Linear Programming Problem\n#' \n#' Given a set of extreme points and the coefficients of an\n#' objective function\n#' \n#' @param z\n#' The coefficients of the objective function, including zeros from\n#' slack variables if applicable.\n#' @param ep\n#' A set of extreme points (the output of \\code{find.ep()}).\n#' \n#' @name optimize\n#' @rdname optimize\n#' @export\nminimize <- function(z, ep)\n{\n optimum <- optimize_lp(z=z, ep=ep, optfun=min)\n optimum$type <- \"minimum\"\n \n optimum\n}\n\n\n\n#' @rdname optimize\n#' @export\nmaximize <- function(z, ep)\n{\n optimum <- optimize_lp(z=z, ep=ep, optfun=max)\n optimum$type <- \"maximum\"\n \n optimum\n}\n\n\n", "meta": {"hexsha": "74244226a598934b3b5e9d5e099bb0498371b351", "size": 2666, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bfs.r", "max_stars_repo_name": "wrathematics/lptools", "max_stars_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-09-14T00:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-14T00:58:45.000Z", "max_issues_repo_path": "R/bfs.r", "max_issues_repo_name": "wrathematics/lptools", "max_issues_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "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/bfs.r", "max_forks_repo_name": "wrathematics/lptools", "max_forks_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "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": 17.8926174497, "max_line_length": 98, "alphanum_fraction": 0.5723930983, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6769448424486297}} {"text": "sigmoid <- function(x) {\n if (x < 0.0) {\n z <- exp(x)\n return(z / (1.0 + z))\n }\n return(1.0 / (1.0 + exp(-x)))\n}\n", "meta": {"hexsha": "603aa852e663ec3e663d25c5b3352f250ee3f9fc", "size": 136, "ext": "r", "lang": "R", "max_stars_repo_path": "m2cgen/interpreters/r/sigmoid.r", "max_stars_repo_name": "Symmetry-International/m2cgen", "max_stars_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2161, "max_stars_repo_stars_event_min_datetime": "2019-01-13T02:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:24:09.000Z", "max_issues_repo_path": "m2cgen/interpreters/r/sigmoid.r", "max_issues_repo_name": "Symmetry-International/m2cgen", "max_issues_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 380, "max_issues_repo_issues_event_min_datetime": "2019-01-17T15:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:59:20.000Z", "max_forks_repo_path": "m2cgen/interpreters/r/sigmoid.r", "max_forks_repo_name": "Symmetry-International/m2cgen", "max_forks_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-02-13T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:45:46.000Z", "avg_line_length": 17.0, "max_line_length": 33, "alphanum_fraction": 0.3676470588, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6766461348626733}} {"text": "library(deSolve)\nlibrary(ggplot2)\nlibrary(reshape2)\n\n\nsis_ode <- function(times,x,parms){\n with(as.list(c(parms,x)),{\n # ODEs\n SH<-nH-x[[1]] #Calculate SH as nH-IH\n SL<-(1-nH)-x[[2]] #Calculate SL as nL-IL\n dIH <-+(betaHH*IH+betaHL*IL)*SH-gamma*IH\n dIL <-+(betaLH*IH+betaLL*IL)*SL-gamma*IL\n \n der<-c(dIH,dIL)\n list(der)\n })\n}\n\nparms <- c(betaHH=10,betaHL=0.1,betaLH=0.1,betaLL=1,gamma=1,nH=0.2)\nx <- c(IH=0.00001,IL=0.001)\ntimes <-seq(0,15,1)\nsis_out <- as.data.frame(lsoda(x,times,sis_ode,parms))\n\nsis_out_long <- melt(sis_out,\"time\") #Collapse dataset from \"wide\" to \"long\" format for plotting\nggplot(sis_out_long,aes(x=time,y=value,colour=variable,group=variable)) + geom_line(lwd=2) +\n labs(x=\"Time (Years)\",y=\"Proportion of Population\",color=\"Risk Group\")\n", "meta": {"hexsha": "ea66d144dc95ff24fcee2716d526f2f0af7a1525", "size": 788, "ext": "r", "lang": "R", "max_stars_repo_path": "models/keeling_rohani_2008/program_3_1_sis.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "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": "models/keeling_rohani_2008/program_3_1_sis.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "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": "models/keeling_rohani_2008/program_3_1_sis.r", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 29.1851851852, "max_line_length": 96, "alphanum_fraction": 0.6624365482, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6766098033218058}} {"text": "REBOL [\r\n title: \"Linear algebra package\"\r\n doc: {\r\n\tA simple implementation of a linear algebra package doing the most simple things.\r\n\t\r\n\tRemember that matrixes are stored as a list of rows and vectors as a list\r\n\t}\r\n]\r\n\r\nff-matrix: func [ A ][ new-line/all A on ]\r\n\r\nswap-rows: func [ M i1 i2] [ swap at M i1 at M i2 ]\r\nvector-mult: func [ x1 x2 /local s ] [\r\n s: 0.0\r\n ;foreach x x1 [ s: s + ( x * first+ x2 ) ]\r\n repeat i length? x1 [ s: s + ( ( pick x1 i ) * pick x2 i ) ]\r\n s\r\n]\r\n;vector-sum: func [ v /local sum ] [ sum: 0 forall v [ sum: sum + first v ] sum ]\r\nvector-sum: func [ v /local sum ] [ sum: 0. repeat i length? v [ sum: sum + pick v i ] sum ]\r\n\r\n;mult-vector-scalar: func [ v s ][ map-each t v [ t * s ]]\r\nmult-vector-scalar: func [ v s ][ v: copy v repeat i length? v [ poke v i s * pick v i ] v ]\r\n\r\nnegate-vector: func [ v ][ v: copy v forall v [ v/1: negate v/1 ] v ]\r\nnegate-matrix: func [ A ][ A: copy A forall A [ A/1: negate-vector A/1 ] A ]\r\n\r\n;add-vector-scalar: func [ v s /local res][ map-each x v [ s + x ] ]\r\nadd-vector-scalar: func [ v s ][ v: copy v repeat i length? v [ poke v i s + pick v i ] v ]\r\n\r\n;add-vector-vector: func [ v w ][ map-each t v [ t + first+ w ]]\r\nadd-vector-vector: func [ v w ][ v: copy v repeat i length? v [ poke v i (pick w i) + pick v i ] v ]\r\n\r\n;add-mult-vector-vector: func [ v a1 w a2 ][ map-each t v [ t * a1 + ( a2 * first+ w )]]\r\nadd-mult-vector-vector: func [ v a1 w a2 ][ v: copy v repeat i length? v [ poke v i (a1 * pick v i ) + ( a2 * pick w i ) ] v ]\r\n\r\nadd-matrix-matrix: func [ A B /local result ][\r\n result: copy []\r\n foreach x A [\r\n\tappend/only result add-vector-vector x first+ B\r\n ]\r\n]\r\n\r\nsub-matrix-matrix: func [ A B /local result ][\r\n add-matrix-matrix A negate-matrix B\r\n]\r\n\r\nsub-matrix-matrix: func [ A B ][\r\n add-matrix-matrix A negate-matrix B\r\n]\r\n\r\nmult-matrix-vector-ol: func [ M x /local n ret ] [\r\n n: length? M\r\n ret: make block! n\r\n foreach y M [\r\n\tappend ret vector-mult y x\r\n ]\r\n]\r\nmult-matrix-vector: func [ M x /local n ret ] [\r\n M: copy M\r\n repeat i length? M [ poke M i vector-mult pick M i x ]\r\n M\r\n]\r\nmult-matrix-matrix: func [\r\n A B\r\n /A-transposed {Use if first matrix is a transposed version of what it should be}\r\n /B-transposed {Use if first matrix is a transposed version of what it should be}\r\n /symmetric {Use if you know the result is symetric, to be implemented}\r\n /local\r\n\tC\r\n][\r\n n: length? A\r\n unless B-transposed [B: transpose-matrix B]\r\n if A-transposed [A: transpose-matrix A]\r\n C: make block! n\r\n foreach x B [ append/only C mult-matrix-vector A x ]\r\n C: transpose-matrix C\r\n]\r\n\r\nmult-matrix-scalar: func [ A k /local result ][\r\n result: copy []\r\n foreach x A [\r\n\tappend/only result mult-vector-scalar x k\r\n ]\r\n result\r\n]\r\n\t\r\n\r\nrand-vector: func [ n /local v ] [ v: make block! n loop n [ append v ( random 1000. ) - 500. ] v ]\r\n\r\nrand-matrix: func [ n /local A ] [\r\n A: make block! n\r\n loop n [ append/only A rand-vector n ]\r\n A\r\n]\r\n\r\nmult-add-vectors: func [\r\n r1 [ block! ] {Row}\r\n k1 [number!] {multiplicator}\r\n r2 [ block! ] {Row}\r\n k2 [number!] {multiplicator}\r\n /local \r\n r n\r\n] [\r\n r: make block! n: length? r1\r\n repeat i n [\r\n\tappend r r1/:i * k1 + ( r2/:i * k2 )\r\n ]\r\n r\r\n]\r\nmult-row: func [ r k ] [ map-each x copy r [ x * k ] ]\r\n\r\nform-matrix: func [ 'M\r\n /local\r\n r ret\r\n] [\r\n ret: reform [ M \":\" ]\r\n foreach r get M [ repend ret reform [ tab form r newline ] ]\r\n]\r\n\r\nget-col: func [\r\n M { The matrix}\r\n c {The column index}\r\n /local\r\n\tret\r\n\tn\r\n ] [\r\n n: length? M\r\n ret: make block! n\r\n foreach x M [ append ret x/:c ]\r\n ret\r\n]\r\n\r\nget-cols: func [\r\n M { The matrix}\r\n from {The first column}\r\n to {The last column}\r\n /local\r\n\tret\r\n\tn\r\n ] [\r\n n: length? M\r\n ret: make block! n\r\n foreach x M [ append/only ret copy/part at x from to - from + 1 ]\r\n ret\r\n]\r\n\r\ntranspose-matrix: func [A /local ret m ] [\r\n ret: make block! n: length? A/1\r\n m: length? A\r\n \r\n repeat i n [\r\n\tappend/only ret new-line/all get-col A i off\r\n ]\r\n new-line/all ret on\r\n]\r\n\r\ninverse-matrix: func [ A /local Ainv ][\r\n linear-eq-solve A eye length? A\r\n]\r\ndeterminant-definition: func [\r\n {Calculates the determinant using the definitioin of such, very time\r\n consuming and memory hungry}\r\n A\r\n /local\r\n\tsum B mult n val\r\n\r\n] [\r\n if 1 = n: length? A [ return first first A ]\r\n mult: 1\r\n sum: 0\r\n repeat i n [\r\n\tB: copy/deep A\r\n\tf: B/:i/1\r\n\tremove at B i\r\n\tforall B [ remove first B ]\r\n\tsum: sum + ( mult * f * determinant B )\r\n\tmult: negate mult\r\n ]\r\n sum\r\n]\r\n\r\ndeterminant: func [\r\n A\r\n /local\r\n][\r\n A: forward-decomposition/mult A\r\n d: diag first A\r\n m: second A forall d [ m: m * first d ]\r\n m\r\n]\r\n\r\neye: func [ n /local B Bi ] [\r\n Bi: make block! n\r\n B: make block! n\r\n loop n [ append Bi 0. ]\r\n loop n [ append/only B copy Bi ]\r\n repeat i n [ B/:i/:i: 1. ]\r\n B\r\n]\r\n\r\ndiag: func [ A\r\n /local \r\n\tret \r\n] [\r\n n: length? A\r\n ret: make block! n\r\n either block? A/1 [\r\n\trepeat i n [ append ret A/:i/:i ]\r\n ][\r\n\tzeros: make block! n loop n [ append zeros 0. ]\r\n\tloop n [ append/only ret copy zeros ]\r\n\trepeat i n [ ret/:i/:i: A/:i ]\r\n ]\r\n ret\r\n]\r\n\t\r\n\r\nforward-decomposition: func [\r\n {Does forward decomposition, adds an eye matrix in case A is nxn}\r\n\r\n A [ block! ] \r\n /mult\r\n\r\n /local x n row B m\r\n][ \r\n A: copy/deep A\r\n n: length? A\r\n m: 1\r\n\r\n if n = length? first A [\r\n\tB: eye n\r\n\tforeach row A [ append row first+ B ]\r\n ]\r\n\r\n x: make block! n\r\n ; Forward substitutioin\r\n repeat i n [\r\n\t; Find the row with largest pivot element and move the row to the first row\r\n\tfor j i + 1 n 1 [\r\n\t if ( abs A/:j/:i ) > abs A/:i/:i [ m: negate m swap-rows A i j ]\r\n\t]\r\n\t; Now we should have the row with the best diagonal on row i\r\n\t; \r\n\td-element: negate A/:i/:i\r\n\r\n\tfor j i + 1 n 1 [\r\n\t A/:j: mult-add-vectors\tA/:j\t 1\r\n\t\t\t\t\tA/:i\t A/:j/:i / d-element\r\n\t A/:j/:i: 0. ; In case there are numerical rests\r\n\t]\r\n ]\r\n either mult [ reduce [ A m ] ] [ A ]\r\n]\r\n\r\nlinear-eq-solve: func [\r\n {Solves the linear equation y = A x \r\n y = [ y/1 y/2 ... y/n ]\r\n A = [ [ A11 A12 ... A1n ] [ A21 A22 ... A2n ] ... [1An An2 ... Ann] ]\r\n x = [ x/1 x/2 ... x/n ]\r\n }\r\n\r\n A [ block! ] { Block of size n x n }\r\n y [ block! ] { Block of size n }\r\n\r\n /local x n row\r\n][ \r\n A: copy/deep A\r\n foreach row A [ append row first+ y ]\r\n A: forward-decomposition A\r\n n: length? A\r\n ; Backward substitution\r\n ; print {Backward substitution}\r\n for i n 1 -1 [\r\n\t;Normalize row i\r\n\t; print [ \"pre normalize row\" i \"multiplied with\" 1 / A/:i/:i ] print form-matrix A\r\n\trow: A/:i: mult-row A/:i 1 / A/:i/:i\r\n\t; print [ \"Normalized row\" i ] print form-matrix A\r\n\r\n\r\n\trepeat j i - 1 [\r\n\t A/:j: mult-add-vectors A/:j 1 row negate A/:j/:i\r\n\t ; print [ \"Reduced row\" j ] print form-matrix A\r\n\t]\r\n ]\r\n either block? y/1 [\r\n\tget-col A n + 1 \r\n ][\r\n\tget-cols A n + 1 length? A/1\r\n ]\r\n]\r\n\r\n\r\n\r\n; Tests\r\n; Linear algebra\r\nif all [value? 'debug-linalg debug-linalg ] [\r\n A: [ [ 1 2 ]\r\n\t [ 2 3 ] \r\n ]\r\n x-solved: [ 2 3 ]\r\n y: mult-matrix-vector A x-solved\r\n\r\n print form-matrix A\r\n print form-matrix y\r\n\r\n x: linear-eq-solve A y\r\n print form-matrix x\r\n print either x = x-solved [ {Solved correctly} ] [ {Not a correct solution} ]\r\n\r\n A: rand-matrix 8\r\n x-solve: rand-vector 8\r\n y: mult-matrix-vector A x-solve\r\n x: linear-eq-solve A y\r\n print form-matrix x-solve\r\n print form-matrix x\r\n print either x = x-solved [ {Solved correctly} ] [ {Not a correct solution} ]\r\n\r\n print [ {\\n\\t\\Determinant\\n\r\n\t}]\r\n A: [ [ 1 1 ] [ 2 2] ]\r\n print [ \"Determinant of \\n\" form-matrix A ]\r\n det: determinant A\r\n print [ \"is\" det ]\r\n either det = 0 [ print \"OK\" ] [ print \"Error!\" ]\r\n\r\n A: [ [ 1 1 5 ] [ 2 2 7 ] [ 14 14 49 ] ]\r\n print [ \"Determinant of \" form-matrix A ]\r\n det: determinant A\r\n print [ \"is\" det ]\r\n either det = 0 [ print \"OK\" ] [ print \"Error!\" ]\r\n\r\n A: transpose-matrix [ [ 1 1 5 ] [ 2 2 7 ] [ 14 14 49 ] ]\r\n print [ \"Determinant of \" form-matrix A ]\r\n det: determinant A\r\n print [ \"is\" det ]\r\n either det = 0 [ print \"OK\" ] [ print \"Error!\" ]\r\n\r\n A: [ [ 1 1 5 ] [ 20 2 7 ] [ 14 14 49 ] ]\r\n print [ \"Determinant of \" form-matrix A ]\r\n det: determinant A\r\n print [ \"is\" det ]\r\n either det != 0 [ print \"OK\" ] [ print \"Error!\" ]\r\n]\r\n; vim: ai sw=4 sts=4\r\n", "meta": {"hexsha": "d4bc2b7c8878b749d61c06f861ce88e3aaa70550", "size": 8669, "ext": "r", "lang": "R", "max_stars_repo_path": "linalg.r", "max_stars_repo_name": "ingvast/pdf-export", "max_stars_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-19T16:01:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T09:25:22.000Z", "max_issues_repo_path": "linalg.r", "max_issues_repo_name": "ingvast/pdf-export", "max_issues_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "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": "linalg.r", "max_forks_repo_name": "ingvast/pdf-export", "max_forks_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "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": 25.0549132948, "max_line_length": 127, "alphanum_fraction": 0.5441227362, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6765936027051569}} {"text": "#R for repeated measures\r\nlibrary(car)\r\ndata <- read.table((\"http://www.uvm.edu/~dhowell/methods8/DataFiles/KingLong.dat\"), header = TRUE)\r\n # Data are already in long form.\r\n####################################################################\r\n# > head(data) #\r\n# group subj interval dv #\r\n# 1 1 1 1 150 #\r\n# 2 1 1 2 44 #\r\n# 3 1 1 3 71 #\r\n# 4 1 1 4 59 #\r\n# 5 1 1 5 132 #\r\n# 6 1 1 6 74 #\r\n####################################################################\r\nattach(data)\r\nkingaov <- aov(outcome~factor(Group)* factor(Interval)+Error(factor(subject)))\r\nprint(summary(kingaov))\r\n\r\n###########################################################################\r\n# Error: factor(subj) #\r\n# Df Sum Sq Mean Sq F value Pr(>F) #\r\n# factor(group) 2 285815 142908 7.8 0.0029 ** #\r\n# Residuals 21 384722 18320 #\r\n# --- #\r\n# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 #\r\n# #\r\n# Error: Within #\r\n# Df Sum Sq Mean Sq F value Pr(>F) #\r\n# factor(interval) 5 399737 79947 29.85 <2e-16 *** #\r\n# factor(group):factor(interval) 10 80820 8082 3.02 0.0022 ** #\r\n# Residuals 105 281199 2678 #\r\n# --- #\r\n# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 #\r\n###########################################################################\r\n\r\ninteraction.plot(Interval, factor(Group), outcome, type=\"b\", pch = c(2,4,6),\r\n legend = \"F\", col = c(3,4,6))\r\nlegend(4, 300, c(\"same\", \"different\", \"control\"), col = c(4,6,3),\r\n text.col = \"green4\", lty = c(2, 1, 3), pch = c(4, 6, 2),\r\n merge = TRUE, bg = 'gray90')\r\n\r\n\r\ndetach(datLong)\r\n", "meta": {"hexsha": "e51db84a6a70777b3bc9bf126c0835662a070269", "size": 2563, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/KingAnova2.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/KingAnova2.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/KingAnova2.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.25, "max_line_length": 99, "alphanum_fraction": 0.2785797893, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8397339756938819, "lm_q1q2_score": 0.6765167210001943}} {"text": "#' GLS prediction intervals\n#'\n#' Computes prediction intervals for a GLS regression. When the variance covariance matrix is based on a phylogeny, this computes the prediction intervals for a phylogenetic regression (PGLS). \n#' @param Y Dependent variable. \n#' @param X Independent variable. \n#' @param Sigma Matrix describing the covariance among data points. For the phylogenetic regression, this is based on a phylogeny (vcv(tree)). \n#' @param k The sample size of the estimated future points.\n#' @return GLS results.\n#' @return Prediction intervals of the estimates ('PI').\n#' @return Prediction intervals of unobserved values of Y ('PI.plot').\n#' @references Smaers & Rohlf (2016) Testing species' deviations from allometric preductions using the phylogenetic regression. Evolution. 70 (5): 1145-1149.\n#' @examples see https://smaerslab.com/software/\n#' @export\n\ngls.pi<-function(Y,X,Sigma,k){\n n<-length(X)\n#Standardize sigma to reduce rounding errors\n tr<-sum(diag(Sigma))\n Sigma<-n*Sigma/tr\n#Input\n invSigma<-solve(Sigma)\n#pgls mean and variance\n X1<-rep(1,n)\n q<-2 # correct if multivariate!!\n C1<-solve(t(X1)%*%invSigma%*%X1)\n Y_PGLSmean<-c(C1%*%t(X1)%*%invSigma%*%Y)\n Y_PGLSdeviations = Y - Y_PGLSmean\n Y_PGLSvariance = (t(Y_PGLSdeviations)%*%invSigma%*%Y_PGLSdeviations)/(n-1)\n SE_Y_mean = sqrt(Y_PGLSvariance/n)\n#Regression\n XX<-cbind(rep(1,n),X)\n C<-solve(t(XX)%*%invSigma%*%XX)\n w<-C%*%t(XX)%*%invSigma\n B<-w%*%Y\n Yhat<-XX%*%B\n Yresid=Y-Yhat\n Y_MSEresid<-c((t(Yresid)%*%invSigma%*%Yresid)/(n-q))\n a<-B[1]\n b<-B[2]\n#SE of statistics\n SEa<-sqrt(diag(C)*Y_MSEresid)[1]\n SEb<-sqrt(diag(C)*Y_MSEresid)[2]\n#Save model\n intercept<-cbind(a,SEa)\n slope<-cbind(b,SEb)\n model<-rbind(intercept,slope)\n colnames(model)<-c(\"Estimate\",\"Std.Error\")\n rownames(model)<-c(\"intercept\",\"slope\")\n#predint\n SEYhat<-sqrt((diag(XX%*%C%*%t(XX))+c(1/k))%*%((t(Yresid)%*%invSigma%*%Yresid)/(n-q)))\n PI<-cbind(X,Yhat,SEYhat)\n Lower2.5<-Yhat-qt(0.975,n)*SEYhat\n Lower5<-Yhat-qt(0.95,n)*SEYhat\n Upper5<-Yhat+qt(0.95,n)*SEYhat\n Upper2.5<-Yhat+qt(0.975,n)*SEYhat\n PI<-cbind(PI,Lower2.5)\n PI<-cbind(PI,Lower5)\n PI<-cbind(PI,Upper5)\n PI<-cbind(PI,Upper2.5)\n PI<-PI[order(PI[,1]),]\n colnames(PI)<-c(\"X\",\"Yhat\",\"SEYhat\",\"Lower2.5\",\"Lower5\",\"Upper5\",\"Upper2.5\")\n PI<-as.data.frame(PI)\n#confint extrapolated\n Xi<-seq(c(min(X)-abs(max(X))),to=c(abs(max(X))*5),length.out=100)\n Z<-c(Xi)\n ZZ<-cbind(rep(1,length(Z)),Z)\n SEYhat.Xi<-sqrt((diag(ZZ%*%C%*%t(ZZ))+c(1/k))%*%((t(Yresid)%*%invSigma%*%Yresid)/(n-q)))\n Yhat.Xi<-a+b*Xi\n Lower2.5.Yhat.Xi<-Yhat.Xi-qt(0.975,n)*SEYhat.Xi\n Lower5.Yhat.Xi<-Yhat.Xi-qt(0.95,n)*SEYhat.Xi\n Upper5.Yhat.Xi<-Yhat.Xi+qt(0.95,n)*SEYhat.Xi\n Upper2.5.Yhat.Xi<-Yhat.Xi+qt(0.975,n)*SEYhat.Xi\n PI.plot<-cbind(Xi,Yhat.Xi,SEYhat.Xi,Lower2.5.Yhat.Xi,Lower5.Yhat.Xi,Upper5.Yhat.Xi,Upper2.5.Yhat.Xi)\n colnames(PI.plot)<-c(\"X\",\"Yhat\",\"SEYhat\",\"Lower2.5\",\"Lower5\",\"Upper5\",\"Upper2.5\")\n PI.plot<-as.data.frame(PI.plot)\nresults<-list(model,PI,PI.plot)\nnames(results)<-c(\"model\",\"PI\",\"PI.plot\")\nreturn(results)\n}\n", "meta": {"hexsha": "1186b5137db4bf37fdf1660312f595aa30dc431d", "size": 3316, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gls.pi.r", "max_stars_repo_name": "JeroenSmaers/evomap", "max_stars_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-01-07T04:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-15T19:42:12.000Z", "max_issues_repo_path": "R/gls.pi.r", "max_issues_repo_name": "JeroenSmaers/evomap", "max_issues_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "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/gls.pi.r", "max_forks_repo_name": "JeroenSmaers/evomap", "max_forks_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-10-14T18:26:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-10T04:57:55.000Z", "avg_line_length": 41.45, "max_line_length": 193, "alphanum_fraction": 0.6239445115, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6764255116108581}} {"text": "# Define consts\nweights <- c(panacea=0.3, ichor=0.2, gold=2.0)\nvolumes <- c(panacea=0.025, ichor=0.015, gold=0.002)\nvalues <- c(panacea=3000, ichor=1800, gold=2500)\nsack.weight <- 25\nsack.volume <- 0.25\nmax.items <- floor(pmin(sack.weight/weights, sack.volume/volumes))\n\n# Some utility functions\ngetTotalValue <- function(n) sum(n*values)\ngetTotalWeight <- function(n) sum(n*weights)\ngetTotalVolume <- function(n) sum(n*volumes)\nwillFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume\n\n# Find all possible combination, then eliminate those that won't fit in the sack\nknapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n)))\nok <- apply(knapsack, 1, willFitInSack)\nknapok <- knapsack[ok,]\n\n# Find the solutions with the highest value\nvals <- apply(knapok, 1, getTotalValue)\nknapok[vals == max(vals),]\n", "meta": {"hexsha": "2dd624ec9415af1aa6ac66f324499981e5960237", "size": 855, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.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/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.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/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.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": 37.1739130435, "max_line_length": 97, "alphanum_fraction": 0.7251461988, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6763973057734443}} {"text": "setwd('~/Code/SMAI/BayesianNets')\nlibrary(e1071)\n\nnorm_vec <- function(x) sqrt(sum(x^2))\n\nconstruct_kernel <- function(data_in,data_out,sequence,gamma = 0.00000002) {\n K = matrix(0,nrow(data_in),length(sequence))\n for (i in 1:nrow(data_in)) {\n for (j in 1:length(sequence)) {\n K[i,j] <- exp(-1*gamma*sum((data_in[i,] - data_out[sequence[j],])**2,na.rm = T))\n } \n }\n return(K)\n}\n\nproject_points <- function(data_in,data_out,vectors) {\n sequence = 1:nrow(data_out)\n K <- construct_kernel(data_in,data_out,sequence)\n return (t(K) %*% vectors)\n}\n\nkernel_principle_components <- function(data) {\n sequence = 1:nrow(data)\n print(\"Constructing Kernel\")\n K <- construct_kernel(data,data,sequence)\n I <- matrix(1,nrow(data),nrow(data))/nrow(data)\n K_centered <- K - I%*%K - K%*%I + I%*%K%*%I\n eig <- eigen(K_centered)\n vectors <- as.matrix(eig$vectors[,1:10])/ sqrt(eig$values[1:10])\n # final_data <- t(t(vectors) %*% t(X))\n # return(final_data)\n return(vectors)\n}\n\nkernel_linear_discriminant <- function(data,labels) {\n A <- data\n A <- as.matrix(cbind(A, labels))\n \n negative_sequence <- which(A[,ncol(A)] == -1)\n K_negative <- construct_kernel(data,data,negative_sequence)\n M2 <- apply(K_negative,1,function(X) (1/length(X))*sum(X))\n \n num_negative <- length(negative_sequence)\n K_negative <- K_negative %*% (diag(num_negative) - (1/num_negative)*matrix(1,num_negative,num_negative)) %*% t(K_negative)\n \n positive_sequence <- which(A[,ncol(A)] == 1)\n K_positive <- construct_kernel(data,data,positive_sequence)\n M1 <- apply(K_positive,1,function(X) (1/length(X))*sum(X))\n \n num_positive <- length(positive_sequence)\n K_positive <- K_positive %*% (diag(num_positive) - (1/num_positive)*matrix(1,num_positive,num_positive)) %*% t(K_positive)\n \n N <- K_positive + K_negative\n \n #print(dim(N))\n N <- N + diag(nrow(N))\n \n N_inv <- solve(N)\n \n vect <- N_inv %*% (M2-M1)\n # final_data <- t(t(vectors) %*% t(X))\n # return(final_data)\n return(vect)\n}\n\nrun_KPCA <- function(data, labels,test,test_labels) {\n #vect <- kernel_linear_discriminant(data,labels)\n vect <- kernel_principle_components(data)\n \n a <- project_points(data,data,vect)\n #mysvm <- svm(a,labels,type='C',kernel = 'radial',gamma=0.1,cost = 100)\n mysvm <- svm(a,labels,type='C',kernel = 'radial',gamma= 0.001,cost = 10)\n #mysvm <- svm(a,labels,type='C',kernel = 'linear')\n b <- project_points(data,test,vect)\n pred <- predict(mysvm,b)\n length(which(as.vector(pred) == test_labels))\n}\n\nrun_KLDA <- function(data,labels,test,test_labels) {\n vect <- kernel_linear_discriminant(data,labels)\n \n a <- project_points(data,data,vect)\n #mysvm <- svm(a,labels,type='C',kernel = 'radial',gamma=0.1,cost = 100)\n #mysvm <- svm(a,labels,type='C',kernel = 'radial',gamma= 0.1,cost = 10)\n mysvm <- svm(a,labels,type='C',kernel = 'linear')\n b <- project_points(data,test,vect)\n pred <- predict(mysvm,b)\n length(which(as.vector(pred) == test_labels))\n}\n\n\ndata <- as.matrix(read.csv(\"Datasets/arcene_train.data\",header = FALSE, sep = \" \",fill = FALSE))\nlabels <- read.csv(\"Datasets/arcene_train.labels\", header = FALSE, sep = \" \")\n\ntest <- as.matrix(read.csv(\"Datasets/arcene_valid.data\", header = FALSE, sep = \" \", fill = TRUE))\ntest_labels <- read.csv(\"Datasets/arcene_valid.labels\", header = FALSE, sep = \" \")\nrun_KPCA(data,labels,test,test_labels)\n#run_KLDA(data,labels,test,test_labels)\n\n#data <- as.matrix(read.csv(\"Datasets/gisette_train.data\",header = FALSE, sep = \" \",fill = FALSE))\n#labels <- read.csv(\"Datasets/gisette_train.labels\", header = FALSE, sep = \" \")\n\n#test <- as.matrix(read.csv(\"Datasets/gisette_valid.data\", header = FALSE, sep = \" \", fill = TRUE))\n#test_labels <- read.csv(\"Datasets/gisette_valid.labels\", header = FALSE, sep = \" \")\n#run_KPCA(data[1:1000,1:1000],labels[1:1000,],test[1:100,1:1000],test_labels[1:100,])\n#run_KLDA(data[1:1000,1:1000],labels[1:1000,],test[1:100,1:1000],test_labels[1:100,])\n\n", "meta": {"hexsha": "279d85d3ab4b57ae8e907193ab3282645e77fadf", "size": 3941, "ext": "r", "lang": "R", "max_stars_repo_path": "a4q1.r", "max_stars_repo_name": "SahilC/DimentionalityReduction", "max_stars_repo_head_hexsha": "53a1e7429c639d8500d601a855f13a07cbb1f8c6", "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": "a4q1.r", "max_issues_repo_name": "SahilC/DimentionalityReduction", "max_issues_repo_head_hexsha": "53a1e7429c639d8500d601a855f13a07cbb1f8c6", "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": "a4q1.r", "max_forks_repo_name": "SahilC/DimentionalityReduction", "max_forks_repo_head_hexsha": "53a1e7429c639d8500d601a855f13a07cbb1f8c6", "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.4907407407, "max_line_length": 124, "alphanum_fraction": 0.6714031972, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6763973036586705}} {"text": "#' Outlier\n#'\n#' @description return TRUE if the value is an outlier (boxplot criteria)\n#'\n#' @param x numeric vector\n#'\n#' @return Numeric vector\n#' @export\n#'\n#' @examples\n#'\n#' x <- c(rnorm(10),10)\n#'\n#' x\n#'\n#' is_outlier(x)\n#'\n\nis_outlier <- function(x){\n\n if(is.numeric(x) == F){\n stop(\"x must be numeric\")\n }\n\n q1 <- quantile(x, 0.25, na.rm = T)\n\n q3 <- quantile(x, 0.75, na.rm = T)\n\n aiq <- q3 - q1\n\n li <- q1 - (1.5 * aiq)\n\n ls <- q3 + (1.5 * aiq)\n\n out <- ifelse( (x <= li) | (x >= ls), T, F)\n\n return(out)\n\n}\n", "meta": {"hexsha": "48b91c177a970552856f997cb289828b0e8610c7", "size": 533, "ext": "r", "lang": "R", "max_stars_repo_path": "R/is_outlier.r", "max_stars_repo_name": "larissabf/relper", "max_stars_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "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/is_outlier.r", "max_issues_repo_name": "larissabf/relper", "max_issues_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "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/is_outlier.r", "max_forks_repo_name": "larissabf/relper", "max_forks_repo_head_hexsha": "fc6ed8006190fdb829ebbf8b2f24b3c8ef39c3a4", "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": 13.325, "max_line_length": 73, "alphanum_fraction": 0.521575985, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6762817350610482}} {"text": "#' @title calcLoadBSFC\n#'\n#' @description Calculates Brake Specific Fuel Consumption (BSFC) or Specific Oil\n#' Fuel Consumption (SFOC) using a parabolic relationship with the main engine\n#' load factor.\n#'\n#' @param loadFactor Fraction of total installed propulsive power representing\n#' the instantaneous or average propulsive power (unitless) (vector of\n#' numericals) (see ShipPowerModel library). If \\code{NA} is supplied, the\n#' baseline BSFC value is returned (i.e., the resulting emission factor will be\n#' independent of engine load).\n#' @param BSFC_Baseline Baseline BSFC value (g/kWh) (vector of numericals)\n#'\n#' @return \\code{BSFC} (g/kWh) (vector of numericals)\n#'\n#' @references\n#'International Maritime Organization. 2014. \"Third IMO GHG study 2014 - Final\n#'report.\" London: International Maritime Organization.\n#'\n#' \\href{https://doi.org/10.5194/acp-12-2641-2012}{Jalkanen, J.-P., Johansson\n#' L., Kukkonen, J., Brink, A., Kalli, J., and Stipa , T. 2012. \"Extension of an\n#' assessment model of ship traffic exhaust emissions for particulate matter and\n#' carbon monoxide. Atmospheric Chemistry and Physics 12, no. 5.}\n#'\n#' @examples\n#' calcLoadBSFC(c(NA, 0.5, 0.7),c(185,195,300))\n#'\n#' @export\n\ncalcLoadBSFC<- function(loadFactor=NULL, BSFC_Baseline){\n BSFC<-ifelse(is.na(loadFactor),\n BSFC_Baseline,\n BSFC_Baseline*(0.455*((loadFactor)^2)-0.71*loadFactor+1.28)\n )\nreturn(BSFC)\n}\n", "meta": {"hexsha": "35f8eee57f08d3fddc689ecc9c2a1c9fd9768579", "size": 1438, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipEF/R/calcLoadBSFC.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/calcLoadBSFC.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/calcLoadBSFC.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": 38.8648648649, "max_line_length": 81, "alphanum_fraction": 0.7127955494, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6762799325738358}} {"text": "### ALGORITHMS\n# SVD algorithm with rank k approximation, stops when error decrease is below eps.\nalg.svd <- function(df, pl=alg.svd.pl(df), debug=FALSE)\n{\n\tmat <- matrix(pl$init, max(df$user), max(df$movie))\n\n\t# Matrix of given values\n\tgiven <- mask <- matrix(0, max(df$user), max(df$movie))\n\tgiven[(df$movie-1)*nrow(mat)+df$user] <- df$stars\n\n\t# Mask containing a '1' for each given value\n\tmask[(df$movie-1)*nrow(mat)+df$user] <- 1\n\n\t# Error history of length 2, initialize with dummy values making no trouble.\n\terrvec <- (max(df$stars) - min(df$stars)) * c(1, 1/(1-pl$eps)^2)\n\twhile (errvec[1]/errvec[2] < 1-pl$eps) {\n\t\t# Compute error\n\t\terr <- sqrt(sum((mat*mask-given)^2) / nrow(df))\n\t\tif (debug) print(err)\n\t\terrvec <- c(err, errvec[1])\n\t\t# Then overwrite with given values ...\n\t\tmat <- mat*(1-mask)+given\n\t\tsing <- La.svd(mat, pl$k, pl$k)\n\t\t# ... and compute rank k approximation\n\t\tmat <- sing$u %*% diag(sing$d[1:pl$k],pl$k) %*% sing$v\n\t}\n\n\treturn(mat)\n}\n\nalg.svd.pl <- function(df, init=mean(df$stars), k=1, digits=2)\n\tlist(init=init, k=k, eps=10^-digits)\n\n# Hazan's algorithm with target trace tr, curvature constant Cf and eps as above,\n#\taveraged on error history of maximum length maxhist.\nalg.hazan <- function(df, pl=alg.hazan.pl(df, mean(df$stars)*(max(df$user) + max(df$movie))), debug=FALSE)\n{\n\tn <- max(df$user); m <- max(df$movie); len <- nrow(df)\n\n\t# \"Given\" matrix Y we want to approximate\n\tY <- matrix(0, n+m, n+m)\n\tY[(df$movie-1)*(n+m)+df$user+m] <- df$stars\n\tY[(df$user-1+m)*(n+m)+df$movie] <- df$stars\n\n\t# Initialize X = v*v^T with an eigenvector belonging to the greatest eigenvalue\n\ti <- 0; v <- power.method(Y, pl$Cf/pl$tr)\n\tX <- pl$tr * (v %*% t(v)) / sum(v*v)\n\terrvec <- (sum(ifelse(Y!=0, (X-Y)^2, 0))/len) * c(1/(1-pl$eps)^2, 1/(1-pl$eps)^4)\n\n\tdecr <- 1;\t# Average error decrease\n\twhile (decr > pl$eps | i < 100) {\n\t\t# Compute error and average error decrease\n\t\terr <- sum((Y!=0) * (X-Y)^2)/len\n\t\tif (debug) print(err)\n\t\terrvec <- c(err, errvec)\n\t\thist <- min(pl$maxhist, length(errvec))\n\t\tdecr <- lm(errvec[1:hist] ~ as.numeric(1:hist))$coefficients[[2]]\n\n\t\talpha <- 2/(i+2);\ti <- i+1\n\t\t# Compute \"symmetricized\" gradient matrix of\n\t\t# f(X) = \\sum_(\\Omega+(0,m)) (X_ij-Y_ij)^2\n\t\tNabla <- 2 * (Y != 0) * (X-Y)\n\n\t\t# Compute an eigenvector corresponding to the greatest eigenvalue\n\t\tv <- power.method(Nabla, alpha*pl$Cf/pl$tr)\n\n\t\t# Blend old X with tr*v*v^T\n\t\tX <- (1-alpha)*X + alpha*pl$tr * v %*% t(v)\n\t}\n\n\treturn(X[(m+1):(n+m),1:m])\n}\n\nalg.hazan.pl <- function(df, tr, digits=2, Cf=curvature(df[c(1,2)]), maxhist=50)\n\tlist(tr=tr, eps=10^-digits, Cf=tr^2 * Cf, maxhist=maxhist)\n\n# \"Power method\" to compute an eigenvector corresponding to the greatest eigenvalue\npower.method <- function(A, eps)\n{\n\t# Start with random normalized vector\n\tv <- runif(dim(A)[1])\n\tv <- v / sqrt(sum(v*v))\n\n\tl<-2; oldl<-1;\t# not \"correct\", but works in high dimensions\n\twhile (l/oldl > 1 + eps) {\n\t\tv <- A %*% v\n\t\toldl <- l; l <- sqrt(sum(v*v))\n\t\tv <- v/l\n\t}\n\treturn(v)\n}\n\n# Compute lower bound for the \"curvature constant\" C_f\ncurvature <- function(df, samples=10)\n{\n\tn <- max(df$user); m <- max(df$movie); len <- nrow(df)\n\tY <- matrix(0, n+m, n+m)\n\tY[(df$movie-1)*nrow(Y)+df$user+m] <- 1\n\n\tsamp <- vector(mode=\"list\", length=samples)\n\tfor (i in 1:samples) {\n\t\t# Generate n independent vectors\n\t\tA <- matrix(rnorm((n+m)^2), nrow=n+m)\n\t\t# Normalize them\n\t\tA <- apply(A, 2, function(x) {x/sqrt(sum(x*x))})\n\t\t# Generate weights\n\t\tw <- rexp(n+m, n+m); w <- w / sum(w)\n\t\t# Generate matrix\n\t\tsamp[[i]] <- A %*% (t(A)*w)\n\t};\n\n\tmaximum <- 0;\n\tfor (i in 1:samples)\n\t\tfor (j in 1:samples) {\n\t\t\tdiff <- sum((samp[[i]]-samp[[j]])^2 * Y)/len\n\t\t\tmaximum <- max(maximum, diff)\n\t\t}\n\treturn(maximum)\n}\n\n### POST PROCESSING ###\npost.clamp <- function(data, rg)\n{\n\tifelse(datarg[2],\n\t\t\trg[2],\n\t\t\tdata\n\t\t)\n\t)\n}\n\npost.linear <- function(data, rg)\n{\n\told<-range(data);\n\t(data-old[1])/(old[2]-old[1])*(rg[2]-rg[1])+rg[1]\n}\n\npost.logistic <- function(data, rg)\n{\n\t# Scale to [-1,1]\n\tdata <- (2*data-(rg[1]+rg[2]))/(rg[2]-rg[1])\n\t# Apply logistic function with derivative 1/2 in 0.\n\tdata <- 1/(1+exp(-2*data))\n\tdata*(rg[2]-rg[1]) + rg[1]\n}\n", "meta": {"hexsha": "d646aa2af9245f864bb6ea47114c4459480127d1", "size": 4158, "ext": "r", "lang": "R", "max_stars_repo_path": "alg.r", "max_stars_repo_name": "aaronpuchert/matrixcompletion", "max_stars_repo_head_hexsha": "30501990b03b6d076b748844a15a593314be32ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-06-07T23:25:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T04:21:56.000Z", "max_issues_repo_path": "alg.r", "max_issues_repo_name": "aaronpuchert/matrixcompletion", "max_issues_repo_head_hexsha": "30501990b03b6d076b748844a15a593314be32ab", "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": "alg.r", "max_forks_repo_name": "aaronpuchert/matrixcompletion", "max_forks_repo_head_hexsha": "30501990b03b6d076b748844a15a593314be32ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-04-16T07:38:16.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-19T14:03:22.000Z", "avg_line_length": 28.2857142857, "max_line_length": 106, "alphanum_fraction": 0.6084656085, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6761988763637479}} {"text": "#' Calculator for ds (between subjects effect size)\n#'\n#' Calculator for ds (between subjects effect size)\n#' @param x,y vectors of the DV for each group\n#' @export\n#' @examples ds_calculator()\n\nds_calculator <- function(group1, group2) {\n\n mean1 <- mean(group1)\n sd1 <- sd(group1)\n n1 <- length(group1)\n\n mean2 <- mean(group2)\n sd2 <- sd(group2)\n n2 <- length(group2)\n\n ds <- (mean1 - mean2)/\n (sqrt(\n ((n1-1)*sd1^2 + (n2-1)*sd2^2)/\n (n1 + n2 - 2)))\n\n return(abs(ds))\n}\n", "meta": {"hexsha": "2b657db0b09edf98d8691d443b5ebb7d2fd4c220", "size": 520, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ds_calculator.r", "max_stars_repo_name": "danielpearson90/vmacfeaturesearch", "max_stars_repo_head_hexsha": "8c765d402018362b27293f884203716327f52bcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-06T14:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T14:04:02.000Z", "max_issues_repo_path": "R/ds_calculator.r", "max_issues_repo_name": "danielpearson90/vmacfeaturesearch", "max_issues_repo_head_hexsha": "8c765d402018362b27293f884203716327f52bcf", "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/ds_calculator.r", "max_forks_repo_name": "danielpearson90/vmacfeaturesearch", "max_forks_repo_head_hexsha": "8c765d402018362b27293f884203716327f52bcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-06T14:05:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T14:05:27.000Z", "avg_line_length": 20.8, "max_line_length": 62, "alphanum_fraction": 0.5980769231, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6761971500780044}} {"text": "jose <-function(s, r,n){\ny <- 0:(r-1)\n for (i in (r+1):n)\n y <- (y + s) %% i\n return(y)\n}\n> jose(3,1,41) # r is the number of remained prisoner.\n[1] 30\n", "meta": {"hexsha": "1403a0d312b8a584f6df8f34ba188d68a09d196c", "size": 153, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Josephus-problem/R/josephus-problem.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/Josephus-problem/R/josephus-problem.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/Josephus-problem/R/josephus-problem.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": 17.0, "max_line_length": 54, "alphanum_fraction": 0.522875817, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.676197136151224}} {"text": "# ......................................................................................\n# ......................... Cvičení 8. Výběrové charakteristiky.........................\n# ..................................... Michal Béreš....................................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Další vybraná spojitá rozdělení ####\n# * $\\chi^2$ - Chí-kvadrát rozdělení (Pearsnovo rozdělení) ####\n# - Použítí: při odhadu směrodatné odchylky (za použití výběrové)\n# - Má jediný parametr - počet stupňů volnosti\n# - $\\frac{S^2}{\\sigma^2}(n-1) \\sim \\chi^2_{n-1}$\n# - $S$ je výběrová směrodatná odchylka\n\n\nn = 5 # počet stupňů volnosti\nx = seq(from = 0, to = 30, by = 0.01) # osa x\nfx = dchisq(x = x, df = n) # hustota pravděpodobnosti chí-kvad. rozdělení\n\nplot(x, fx, type='l')\n\nFx = pchisq(q = x, df = n) # distrib. fce. chí-kvad. rozdělení\n\nplot(x, Fx, type='l')\n\n# * $t$ - Studentovo rozdělení ####\n# - Použití: při odhadu střední hodnoty bez přesné znalosti rozptylu (pouze výběrového\n# rozptylu)\n# - $\\frac{\\bar X - \\mu}{S}\\sqrt{n} \\sim t_{n-1} $\n# - $\\bar X$ je výběrový průměr\n# - $S$ je výběrová směrodatná odchylka \n# - s rostoucím počtem stupňů volnosti konverguje k normovanému normálnímu rozdělení\n\n\nn = 5 # počet stupňů volnosti\nx = seq(from = -3, to = 3, by = 0.01) # osa x\nfx = dt(x = x, df = n) # hustota pravděpodobnosti studentova rozdělení\n\nplot(x, fx, type='l')\n\nfnorm = dnorm(x, mean=0, sd=1) # hodnoty norm. normálního roz.\nlines(x, fnorm, col=\"red\") # do posledního grafu\n\nFx = pt(q = x, df = n) # hustota pravděpodobnosti studentova rozdělení\n\nplot(x, Fx, type='l')\n\nFnorm = pnorm(x, mean=0, sd=1) # hodnoty norm. normálního roz.\nlines(x, Fnorm, col=\"red\") # do posledního grafu\n\n# * $F$ - Fisher-Snedecorovo rozdělení ####\n# - Používá se k testování schody rozptylů\n# - $\\frac{S_1^2/\\sigma_1^2}{S_2^2/\\sigma_2^2} \\sim F_{n_1 - 1, n_2 - 1}$\n\n\nn = 5 # počet stupňů volnosti výběr. 1\nm = 6 # počet stupňů volnosti výběr. 2\nx = seq(from = 0, to = 10, by = 0.01) # osa x\nfx = df(x = x, df1 = n, df2 = m) # hustota pravděpodobnosti chí-kvad. rozdělení\n\nplot(x, fx, type='l')\n\nFx = pf(q = x, df1 = n, df2 = m) # hustota pravděpodobnosti chí-kvad. rozdělení\n\nplot(x, Fx, type='l')\n\n# Jak se chová průměr hodnot z normálního rozdělení? ####\n# Funkce **rnorm(n, mean, sd)** generuje **n** hodnot z normálního rozdělení se střední\n# hodnotou **mean** a směrodatnou odchylkou **sd**.\n\n\nvel_nah_vyberu = 30\nmu = 10\nsigma = 3\nnah_vyber = rnorm(n=vel_nah_vyberu, mean=mu, sd=sigma) \nnah_vyber\n\nmean(nah_vyber)\nsd(nah_vyber)\n\n# ** Náhodná veličina: průměr hodnot ####\n\n\npoc_vyberu = 1000\nprumery = numeric(poc_vyberu) # numeric vyrobi vektor 0\nsmer_odchylky = numeric(poc_vyberu)\nfor(i in 1:poc_vyberu){\n nah_vyber = rnorm(n=vel_nah_vyberu,mean=mu,sd=sigma)\n prumery[i] = mean(nah_vyber)\n smer_odchylky[i] = sd(nah_vyber)\n}\n\nhist(prumery)\n\nqqnorm(prumery)\nqqline(prumery)\n\nmean(prumery)\nsd(prumery)\nsigma/sqrt(vel_nah_vyberu)\n\n# Jak se chová průměr hodnot z uniformního rozdělení? ####\n# Fukce **runif(n, min, max)** generuje **n** hodnot z uniformního rozdělení\n# U(**min,max**).\n\n\nvel_nah_vyberu = 30\na = 1\nb = 7\nnah_vyber=runif(n=vel_nah_vyberu, min=a, max=b)\n#nah_vyber\n\nhist(nah_vyber)\nqqnorm(nah_vyber)\nqqline(nah_vyber)\n\nmu = (a+b)/2\nmu\nmean(nah_vyber)\nsigma = sqrt((b-a)^2/12)\nsigma\nsd(nah_vyber)\n\n# ** Náhodná veličina: průměr hodnot ####\n\n\npoc_vyberu = 1000\nprumery = numeric(poc_vyberu)\nsmer_odchylky = numeric(poc_vyberu)\nfor(i in 1:poc_vyberu){\n nah_vyber = runif(n=vel_nah_vyberu, min=a, max=b)\n prumery[i] = mean(nah_vyber)\n smer_odchylky[i] = sd(nah_vyber)\n}\n\nhist(prumery)\n\nqqnorm(prumery)\nqqline(prumery)\n\nmean(prumery)\nsd(prumery)\nsigma/sqrt(vel_nah_vyberu)\n\n# Příklady ####\n# * Příklad 1. ####\n# Zatížení letadla s 64 místy nemá překročit 6 000 kg. Jaká je pravděpodobnost, že při\n# plném obsazení bude tato hodnota překročena, má-li hmotnost cestujícího střední\n# hodnotu 90 kg a směrodatnou odchylku 10 kg?\n\n\n# X...hmotnost 64 cestujících\n# X ~ N(64*90; 64*100)\n# P(X > 6000) = 1 - F(6000)\n\n1 - pnorm(q=6000, mean=64*90, sd=sqrt(64*100))\n\n# * Příklad 2. ####\n# Zásilka obsahuje 300 výrobků určitého typu. Je známo, že pravděpodobnost zhotovení\n# vadného výrobku tohoto typu je 0,04.\n# ** a) ####\n# Odhadněte pravděpodobnost, že absolutní odchylka podílu vadných výrobků v zásilce od\n# pravděpodobnosti vyrobení vadného výrobku bude menší než 1 %.\n\n\n# X = (p − π)/sqrt(π*(1 − π))*sqrt(n) ∼ N(0, 1)\n# P(-0.01/sqrt(π*(1 − π))*sqrt(n) < X < 0.01/sqrt(π*(1 − π))*sqrt(n))\npi = 0.04\nn = 300\nbound = 0.01/sqrt(pi*(1-pi))*sqrt(n)\npnorm(q=bound, mean=0, sd=1) - pnorm(q=-bound, mean=0, sd=1)\n\n# ** b) ####\n# Jak se změní výsledek, jestliže zásilka bude obsahovat 3 000 výrobků?\n\n\nn = 3000\nbound = 0.01/sqrt(pi*(1-pi))*sqrt(n)\npnorm(q=bound, mean=0, sd=1) - pnorm(q=-bound, mean=0, sd=1)\n\n# * Příklad 3. ####\n# Cestující pravidelně jezdí do zaměstnání a zpět MHD. Je známo, že doba čekání na\n# příjezd MHD se pohybuje v mezích od 0 do 3 minut. Jaká je pravděpodobnost, že celková\n# doba čekání zaměstnance na příjezd MHD během 23 pracovních dnů bude kratší než 80\n# minut?\n\n\n# Y...doba i-tého čekání na MHD\n# y ~ R(0; 3)\n# X...celková doba čekání během 23 dnů (cesta tam a zpět ⇒ 46 čekání)\n# X ~ N(46*EY; 46*DY)\n# P(X < 80)\n\na = 0\nb = 3\nn = 46\nEY = (a+b)/2\nDY = (b-a)^2/12\n\npnorm(q=80, mean=n*EY, sd=sqrt(n*DY))\n\n# * Příklad 4. ####\n# Předpokládejme, že průměrná spotřeba elektrické energie domácností v určitém městě v\n# lednu je 120 kWh a směrodatná odchylka spotřeby je 100 kWh. Určete pravděpodobnost, že\n# průměrná spotřeba 100 náhodně vybraných domácností bude větší než 140 kWh.\n\n\n# Xi...spotřeba i-té domácnosti\n# X...průměrná spotřeba 100 domácností\n# X ~ N(EXi;Dxi/n)\n# P(X > 140)\n\nEXi = 120\nDXi = 100^2\nn = 100\n1 - pnorm(q=140, mean=EXi, sd=sqrt(DXi/n))\n\n# * Příklad 5. ####\n# Společnost Acme Battery Company vyvinula nový typ baterie mobilních telefonů. V\n# průměru vydrží baterie 60 minut na jedno nabití. Směrodatná odchylka této doby je 4\n# minuty. Předpokládejme, že výrobní oddělení po 6 měsících spustí test kontroly\n# kvality. Provedli dva náhodné výběry o rozsahu 10 baterií a v obou zjistili\n# směrodatnou odchylku výdrže baterií větší než 6 minut. S jakou pravděpodobností takový\n# výsledek mohli očekávat?\n\n\n# X = (n − 1)S^2/σ^2\n# X ∼ χ_n-1\n# P(S > 6) = P(X > ...)\n\nn = 10\nS_obs = 6\nsigma = 4\nX_obs = (n - 1)*S_obs^2/sigma^2\n\nP_jedno_mereni = 1 - pchisq(q=X_obs, df=n-1)\nP_jedno_mereni\nP_jedno_mereni^2\n\n# * Příklad 6. ####\n# Z úmrtnostních tabulek vyplývá pravděpodobnost 0,99, že se 35 - letý muž dožije\n# dalšího roku. Roční pojistné této věkové skupiny činí 2 000 Kč, v případě úmrtí\n# pojišťovna vyplatí 100 000 Kč. Jaká je pravděpodobnost, že zisk z 500 pojištěných mužů\n# ve věku 35 let bude alespoň 500 000 Kč? (Řešte dvěma způsoby - pomocí binomického\n# rozdělení a pomoci aproximace binomického rozdělení rozdělením normálním.)\n\n\n# X...počet mužů z 500, kteří se nedožijí dalšího roku\n# X ~ Bi(500; 0.01)\n# Z = 500 · 2 000 − X · 100 000\n# P(Z ≥ 500 000) = P(X ≤ 5)\n\npbinom(5, size=500, prob=0.01)\n\n# X ~ Bi(500; 0.01) ~ N(500*0.01; 500*0.01*(1-0.01))\n# P(X ≤ 5) ~ P(X < 5.5) (oprava na spojitost)\n\npnorm(5.5, mean=500*0.01, sd=sqrt(500*0.01*(1-0.01)))\n\n# * Příklad 7. ####\n# Předpokládejme, že v populaci má přibližně 60 % mladých mužů vyšší než doporučenou\n# hladinu cholesterolu v séru. S jakou pravděpodobností bude mít v náhodném výběru 200\n# mladých mužů více než 120 z nich vyšší než doporučenou hladinu cholesterolu v séru?\n\n\n# X...počet mladých mužů z 200 s vyšší než doporučenou hladinou cholesterolu v séru\n# X ∼ Bi(200; 0.6)\n# P(X > 120) = 1 - P(X ≤ 120)\n\n1 - pbinom(120, size=200, prob=0.6)\n\n# X ~ N(200*0.6; 200*0.6(1-0.6)), tj. X ≈ N(120; 48)\n# 1 - P(X ≤ 120) ~ 1 - P(X < 120.5) (oprava na spojitost)\n\n1 - pnorm(120.5, mean=200*0.6, sd=sqrt(200*0.6*(1-0.6)))\n\n\n\n", "meta": {"hexsha": "f49a2918c41971705bfcd87f3df7b517bed5ad71", "size": 8140, "ext": "r", "lang": "R", "max_stars_repo_path": "CV8/cv8.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV8/cv8.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "CV8/cv8.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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.9679715302, "max_line_length": 88, "alphanum_fraction": 0.655036855, "num_tokens": 3806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6761652529007576}} {"text": "#Neural network\r\n#h = ReLU\r\nh = function(x)\r\n{\r\n ifelse(x>0, x, 0)\r\n}\r\ndh = function(x)\r\n{\r\n ifelse(x>0, 1, 0)\r\n}\r\ng = function(x)\r\n{\r\n x\r\n}\r\n#Load data\r\nM = 50 #network's width\r\nset.seed(43253)\r\ndat = read.table(\"functionestimationnn.ascii\",header=F)\r\nX = dat[,1]\r\nX = cbind(1, X) #Has the effect of including the intercept into the alpha vector\r\ny = dat[,2]\r\nfGTs = dat[,3]\r\nd.nn = data.frame(y=y,x=X)\r\np = ncol(X)\r\n#initialize param with random values\r\nbeta = runif(M)\r\nbeta0 = runif(1) #I add the bias term\r\nalpha = matrix(runif(M*p),ncol=p)\r\n\r\ny<-d.nn$y\r\nX<-as.matrix(d.nn[,-1])\r\nN.epo = 20\r\nlambda = 0\r\nQvec = NULL\r\nQ.rep = rep(NA,N.epo)\r\nTE.s = NULL #test error between f_est e GT after each epoch\r\nfor(epo in 1:N.epo)\r\n{\r\n m = 50\r\n #Qvec = NULL\r\n itvec = NULL\r\n for(it in 0:10000)\r\n {\r\n #Subsampling\r\n ind = sample(1:n,m,replace=FALSE)\r\n X.sub = X[ind,,drop=FALSE]\r\n y.sub = y[ind]\r\n #Forwards\r\n zz = X.sub%*%t(alpha)\r\n z = h(zz)\r\n TT = z%*%matrix(beta,ncol=1)\r\n eta = g(TT + beta0)\r\n res = as.vector(y.sub-eta)\r\n \r\n #Backwards\r\n df.beta = z\r\n dQ.beta = rep(0,M)\r\n for(k in 1:M)\r\n dQ.beta[k] = -2*sum(res*df.beta[,k])+2*lambda*beta[k]\r\n dQ.alpha = matrix(nrow=M,ncol=p)\r\n for(k in 1:M)\r\n for(j in 1:p)\r\n {\r\n df.alpha = beta[k]*dh(zz[,k])*X.sub[,j]\r\n dQ.alpha[k,j] = -2*sum(res*df.alpha)\r\n }\r\n dQ.alpha\r\n dQ.alpha = dQ.alpha + 2*lambda*alpha\r\n\r\n #gamma = (1+0.5*rep/N.rep)/10000\r\n gamma = 1/(10000 + epo)\r\n beta0 = beta0 + 2* gamma*sum(res)\r\n beta = beta-gamma*dQ.beta\r\n alpha = alpha-gamma*dQ.alpha\r\n \r\n if(it%%1000==0) #Compute full objective function\r\n {\r\n #Forwards\r\n zz = X%*%t(alpha)\r\n z = h(zz)\r\n TT = z%*%matrix(beta,ncol=1)\r\n eta = g(TT + beta0)\r\n res = as.vector(y-eta)\r\n Q = sum(res^2)+lambda*sum(alpha^2)+lambda*sum(beta^2)\r\n Qvec = c(Qvec,Q)\r\n itvec = c(itvec,it)\r\n show(c(it,Q,beta,beta0))\r\n }\r\n }\r\nzz = X%*%t(alpha)\r\nz = h(zz)\r\nTT = z%*%matrix(beta,ncol=1)\r\neta = g(TT + beta0)\r\nres = as.vector(fGTs-eta)\r\nTE = sum(res^2)\r\nTE.s = c(TE.s, TE)\r\nQ.rep[epo] = Q\r\n}\r\n#Plot value of Q as function of iteration\r\nplot(10:length(Qvec[-1]),Qvec[10:length(Qvec[-1])],type=\"l\",xlab=\"Iteration (E+03)\",ylab=\"Q\")\r\nplot(1:length(TE.s[-1]),TE.s[1:length(TE.s[-1])],type=\"l\",xlab=\"Epoch\",ylab=\"Test error\")\r\ndev.off()\r\n", "meta": {"hexsha": "562e5ff4b93e93e0b308cc92d72b54b2d7244b29", "size": 2392, "ext": "r", "lang": "R", "max_stars_repo_path": "neural_network_SDG.r", "max_stars_repo_name": "LeeoBianchi/SDG_NeuralNetwork", "max_stars_repo_head_hexsha": "f81ef8d4b3d3d77b9a89fe771f3535f7957a11fe", "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": "neural_network_SDG.r", "max_issues_repo_name": "LeeoBianchi/SDG_NeuralNetwork", "max_issues_repo_head_hexsha": "f81ef8d4b3d3d77b9a89fe771f3535f7957a11fe", "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": "neural_network_SDG.r", "max_forks_repo_name": "LeeoBianchi/SDG_NeuralNetwork", "max_forks_repo_head_hexsha": "f81ef8d4b3d3d77b9a89fe771f3535f7957a11fe", "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": 23.2233009709, "max_line_length": 94, "alphanum_fraction": 0.5505852843, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6761505669833235}} {"text": "# makeCacheMatrix()\n# This function creates a special \"matrix\" object that can cache its inverse.\n\n# In order to make solve function work your matrix should be invertible (aka nonsingular or nondegenerate)\n# For details on this concept: \n# https://www.khanacademy.org/math/precalculus/precalc-matrices/inverting_matrices/v/singular-matrices\n\n# Computing the inverse of a square matrix can be done with the solve function in R. \n# For example, if X is a square invertible matrix, then solve(X) returns its inverse.\n# For this assignment, assume that the matrix supplied is always invertible.\n\n#Usage example:\n# x <- matrix(1:4, 2, 2) // create a matrix x\n# m <- makeCacheMatrix(x) // create \"special\" matrix m\n# m$get() // return matrix m\n\nmakeCacheMatrix <- function(x = matrix()) {\t\n # m will store cached inverse matrix\n m <- NULL\n # Setting value for matrix\n set <- function(y) {\n x <<- y\n m <<- NULL\n }\n # Getting value for matrix\n get <- function() x\n # Setting inverse value\n setinverse <- function(inverse) m <<- inverse\n # Getting invers value\n getinverse <- function() m\n # Return matrix with defined functions\n list(set = set, \n get = get, \n setinverse = setinverse,\n getinverse = getinverse)\n}\n\n# cacheSolve()\n# This function computes the inverse of the special \"matrix\" returned by makeCacheMatrix above. \n# If the inverse has already been calculated (and the matrix has not changed), \n# then the cachesolve should retrieve the inverse from the cache.\n\n# Usage example:\n# cacheSolve(m) // Return the inverse\n# cacheSolve(m) // Call the 2nd time, so return\n# // the cached inverse\n\ncacheSolve <- function(x) {\n # Return a matrix that is the inverse of 'x'\n m <- x$getinverse()\n # Checking if inverse already was calculated and return it in case it was\n if(!is.null(m)) {\n message(\"getting cached data\")\n return(m)\n }\n # In case inverse was not calculated, calculating and return\n data <- x$get()\n m <- solve(data)\n # Caching the inverse\n x$setinverse(m)\n # Returning inverse\n m\n}", "meta": {"hexsha": "da69e1ea4955873765f940b182c0a8d5de62a1aa", "size": 2163, "ext": "r", "lang": "R", "max_stars_repo_path": "R/CacheMatrix/CacheMatrix.r", "max_stars_repo_name": "mikerodionov/ps_scripts", "max_stars_repo_head_hexsha": "7f100ca7622fdab19f0d525d2a83ec6d2b96ab59", "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/CacheMatrix/CacheMatrix.r", "max_issues_repo_name": "mikerodionov/ps_scripts", "max_issues_repo_head_hexsha": "7f100ca7622fdab19f0d525d2a83ec6d2b96ab59", "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/CacheMatrix/CacheMatrix.r", "max_forks_repo_name": "mikerodionov/ps_scripts", "max_forks_repo_head_hexsha": "7f100ca7622fdab19f0d525d2a83ec6d2b96ab59", "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.3333333333, "max_line_length": 106, "alphanum_fraction": 0.6638927416, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6761323081270201}} {"text": "######################################################################################################\n# CS171 BioVis Project \n# Spring 2013\n# Author: John Mercer\n# Code: Computes the principal components (and saves top prin comps)\n# http://stat.ethz.ch/R-manual/R-patched/library/stats/html/princomp.html\n# http://cran.r-project.org/web/packages/psych/index.html\n#######################################################################################################\n\n#load packages\nlibrary(psych)\nlibrary(GPArotation)\n\n#simulate an example\nx <- rnorm( 10, mean=20, sd=5 )\ny <- rnorm( 10, mean=10, sd=2 )\nz <- rnorm( 10, mean=15, sd=4 )\nk <- rnorm( 10, mean=3, sd=0.4 )\nmydata = data.frame(x=x,y=y,z=z,k=k)\npca_output <- principal(mydata, nfactors=2,rotate=\"varimax\",scores=TRUE) \n#if scores are TRUE, and missing=TRUE, then impute missing values using either the median or the mean\n\n#principal component scores\npca_output$scores\npca_output$values/sum(pca_output$values)\n\n\n######################################################################################################################\n## Start of prcomp code for each of the 6 classes of indices\n######################################################################################################################\nrequire(graphics)\n\n##########################################################\n########### alpha_and_turn_propensities ##################\n##########################################################\nfor (var in 1:ncol(alpha_and_turn_pca_data)) {\n if (class(alpha_and_turn_pca_data[,var])==\"numeric\") {\n alpha_and_turn_pca_data[is.na(alpha_and_turn_pca_data[,var]),var] <- mean(alpha_and_turn_pca_data[,var], na.rm = TRUE)\n }\n}\n\nalpha_and_turn_pca_results <- prcomp(~ .,alpha_and_turn_pca_data, center=TRUE,scale = TRUE)\nsummary(alpha_and_turn_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13 PC14\n#Standard deviation 7.7600 3.42107 2.93869 2.57624 2.30050 2.26154 1.75332 1.66951 1.5966 1.4120 1.3612 1.2991 1.17256 1.12525\n#Proportion of Variance 0.5103 0.09918 0.07319 0.05625 0.04485 0.04334 0.02605 0.02362 0.0216 0.0169 0.0157 0.0143 0.01165 0.01073\n#Cumulative Proportion 0.5103 0.60950 0.68269 0.73894 0.78379 0.82713 0.85318 0.87680 0.8984 0.9153 0.9310 0.9453 0.95696 0.96769\n \nbiplot(alpha_and_turn_pca_results)\n\n#now compute the pincipal components with the eigenvectors\nalpha_and_turn_prin_comps <- predict(alpha_and_turn_pca_results,alpha_and_turn_pca_data)\nplot(alpha_and_turn_prin_comps[,1],alpha_and_turn_prin_comps[,2])\nwrite.csv(alpha_and_turn_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/alpha_prin_comps.csv\") \n\n##########################################################\n########### beta_propensities ##################\n##########################################################\nfor (var in 1:ncol(beta_propensities_pca_data)) {\n if (class(beta_propensities_pca_data[,var])==\"numeric\") {\n beta_propensities_pca_data[is.na(beta_propensities_pca_data[,var]),var] <- mean(beta_propensities_pca_data[,var], na.rm = TRUE)\n }\n}\n\nbeta_propensities_pca_results <- prcomp(~ .,beta_propensities_pca_data, center=TRUE,scale = TRUE)\nsummary(beta_propensities_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13\n#Standard deviation 5.2418 1.41498 1.26916 1.10451 0.96427 0.86212 0.7884 0.75631 0.7273 0.58217 0.48967 0.45392 0.36456\n#Proportion of Variance 0.7426 0.05411 0.04353 0.03297 0.02513 0.02009 0.0168 0.01546 0.0143 0.00916 0.00648 0.00557 0.00359\n#Cumulative Proportion 0.7426 0.79672 0.84025 0.87322 0.89835 0.91844 0.9352 0.95070 0.9650 0.97416 0.98064 0.98621 0.98980\n \nbiplot(beta_propensities_pca_results)\n\n#now compute the pincipal components with the eigenvectors\nbeta_propensities_prin_comps <- predict(beta_propensities_pca_results,beta_propensities_pca_data)\nplot(beta_propensities_prin_comps[,1],beta_propensities_prin_comps[,2])\nwrite.csv(beta_propensities_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/beta_prin_comps.csv\") \n\n##########################################################\n########### composition ##################\n##########################################################\nfor (var in 1:ncol(composition_pca_data)) {\n if (class(composition_pca_data[,var])==\"numeric\") {\n composition_pca_data[is.na(composition_pca_data[,var]),var] <- mean(composition_pca_data[,var], na.rm = TRUE)\n }\n}\n\ncomposition_pca_results <- prcomp(~ .,composition_pca_data, center=TRUE,scale = TRUE)\nsummary(composition_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13\n#Standard deviation 3.8771 2.2605 0.99991 0.80783 0.79489 0.68553 0.5940 0.43067 0.39051 0.35461 0.32214 0.27865 0.20382\n#Proportion of Variance 0.6263 0.2129 0.04166 0.02719 0.02633 0.01958 0.0147 0.00773 0.00635 0.00524 0.00432 0.00324 0.00173\n#Cumulative Proportion 0.6263 0.8392 0.88089 0.90808 0.93441 0.95399 0.9687 0.97642 0.98277 0.98801 0.99234 0.99557 0.99730\n\nbiplot(composition_pca_results)\n\n#now compute the pincipal components with the eigenvectors\ncomposition_prin_comps <- predict(composition_pca_results,composition_pca_data)\nplot(composition_prin_comps[,1],composition_prin_comps[,2])\nwrite.csv(composition_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/composition_prin_comps.csv\") \n\n##########################################################\n########### hydrophobicity ##################\n##########################################################\nfor (var in 1:ncol(hydro_pca_data)) {\n if (class(hydro_pca_data[,var])==\"numeric\") {\n hydro_pca_data[is.na(hydro_pca_data[,var]),var] <- mean(hydro_pca_data[,var], na.rm = TRUE)\n }\n}\n\nhydro_pca_results <- prcomp(~ .,hydro_pca_data, center=TRUE,scale = TRUE)\nsummary(hydro_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13\n#Standard deviation 8.8466 3.73402 3.31842 3.11394 2.28059 2.24177 2.12416 1.88003 1.72602 1.64055 1.57913 1.49701 1.29349\n#Proportion of Variance 0.5253 0.09358 0.07391 0.06508 0.03491 0.03373 0.03028 0.02372 0.01999 0.01806 0.01674 0.01504 0.01123\n#Cumulative Proportion 0.5253 0.61883 0.69274 0.75782 0.79272 0.82645 0.85673 0.88046 0.90045 0.91851 0.93525 0.95029 0.96152\n\n\nbiplot(hydro_pca_results)\n\n#now compute the pincipal components with the eigenvectors\nhydro_prin_comps <- predict(hydro_pca_results,hydro_pca_data)\nplot(hydro_prin_comps[,1],hydro_prin_comps[,2])\nwrite.csv(hydro_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/hydro_prin_comps.csv\") \n\n##########################################################\n########### other properties ##################\n##########################################################\nfor (var in 1:ncol(other_properties_pca_data)) {\n if (class(other_properties_pca_data[,var])==\"numeric\") {\n other_properties_pca_data[is.na(other_properties_pca_data[,var]),var] <- mean(other_properties_pca_data[,var], na.rm = TRUE)\n }\n}\n\n#http://stat.ethz.ch/R-manual/R-patched/library/stats/html/prcomp.html\nother_pca_results <- prcomp(~ .,other_properties_pca_data, center=TRUE,scale = TRUE)\nsummary(other_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13\n#Standard deviation 3.7241 2.0465 1.47927 1.34542 1.26273 1.02230 0.7902 0.77152 0.69578 0.63354 0.56303 0.48291 0.44467\n#Proportion of Variance 0.4953 0.1496 0.07815 0.06465 0.05695 0.03732 0.0223 0.02126 0.01729 0.01433 0.01132 0.00833 0.00706\n#Cumulative Proportion 0.4953 0.6449 0.72305 0.78770 0.84464 0.88197 0.9043 0.92553 0.94282 0.95715 0.96847 0.97680 0.98386\n\nbiplot(other_pca_results)\n\n#now compute the pincipal components with the eigenvectors\nother_prin_comps <- predict(other_pca_results,other_properties_pca_data)\nplot(other_prin_comps[,1],other_prin_comps[,2])\nwrite.csv(other_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/other_prin_comps.csv\") \n\n##########################################################\n######### Physicochemical properties #################\n##########################################################\nfor (var in 1:ncol(physico_properties_pca_data)) {\n if (class(physico_properties_pca_data[,var])==\"numeric\") {\n physico_properties_pca_data[is.na(physico_properties_pca_data[,var]),var] <- mean(physico_properties_pca_data[,var], na.rm = TRUE)\n }\n}\n\n#http://stat.ethz.ch/R-manual/R-patched/library/stats/html/prcomp.html\nphysico_pca_results <- prcomp(~ .,physico_properties_pca_data, center=TRUE,scale = TRUE)\nsummary(physico_pca_results)\n\n#Importance of components:\n# PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10 PC11 PC12 PC13\n#Standard deviation 5.2882 2.2257 2.00197 1.65923 1.32188 1.10587 0.91374 0.81684 0.73423 0.57076 0.54512 0.39715 0.37680\n#Proportion of Variance 0.6079 0.1077 0.08713 0.05985 0.03799 0.02659 0.01815 0.01451 0.01172 0.00708 0.00646 0.00343 0.00309\n#Cumulative Proportion 0.6079 0.7156 0.80276 0.86261 0.90059 0.92718 0.94533 0.95983 0.97155 0.97863 0.98509 0.98852 0.99161\n \nbiplot(physico_pca_results)\n\n#now compute the pincipal components with the eigenvectors\nphysico_prin_comps <- predict(physico_pca_results,physico_properties_pca_data)\nplot(physico_prin_comps[,1],physico_prin_comps[,2])\nwrite.csv(physico_prin_comps,file=\"/Users/mercicle/Documents/python_workspace/BioVis/Codes/IndexData/physico_prin_comps.csv\") \n\n\n######################################################################################################################\n## Scatter-plots of the principal components for each class of indices\n# #http://www.statmethods.net/graphs/scatterplot.html\n######################################################################################################################\n# \n#pairs(~PC1+PC2+PC3,data=other_prin_comps, main=\"Top 3 PC for Other Properties\")\n\n\n", "meta": {"hexsha": "3c163f9dfa98df6095e8a67deebcc62ead8f9561", "size": 10407, "ext": "r", "lang": "R", "max_stars_repo_path": "GeneralizedMu8App/Codes/R_Codes/principal_component_analysis.r", "max_stars_repo_name": "mercicle/Mu-8", "max_stars_repo_head_hexsha": "e98ce9e3b7c672e0fa9e924ba6815c65a6d34dc0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-27T08:26:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T21:41:27.000Z", "max_issues_repo_path": "OnePageStaticMu8App/R_Codes/principal_component_analysis.r", "max_issues_repo_name": "mercicle/Mu-8", "max_issues_repo_head_hexsha": "e98ce9e3b7c672e0fa9e924ba6815c65a6d34dc0", "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": "OnePageStaticMu8App/R_Codes/principal_component_analysis.r", "max_forks_repo_name": "mercicle/Mu-8", "max_forks_repo_head_hexsha": "e98ce9e3b7c672e0fa9e924ba6815c65a6d34dc0", "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": 53.3692307692, "max_line_length": 134, "alphanum_fraction": 0.6299606034, "num_tokens": 3247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6759943449671283}} {"text": "#' Find the distance from the \"from\" location to a vector of \"to\" locations, given their latitude and longitude. Used by the earth.dist function.\n#' \n#' @param long1 the \"from\" longitude, in degrees\n#' @param lat1 the \"from\" latitude, in degrees\n#' @param long2 the vector of \"to\" longitudes, in degrees\n#' @param lat2 the vector of \"to latitudes, in degrees\n#' \n#' @return numeric scalar distance from the \"from\" location to the \"to\" locations.\ndeg.dist = function (long1, lat1, long2, lat2) {\n rad <- pi/180\n a1 <- lat1 * rad\n a2 <- long1 * rad\n b1 <- lat2 * rad\n b2 <- long2 * rad\n dlon <- b2 - a2\n dlat <- b1 - a1\n a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2\n c <- 2 * atan2(sqrt(a), sqrt(1 - a))\n R <- 40041.47/(2 * pi)\n d <- R * c\n return(d)\n}", "meta": {"hexsha": "854de431a378d0a602791206365bd8de97bf38d3", "size": 800, "ext": "r", "lang": "R", "max_stars_repo_path": "R/deg.dist.r", "max_stars_repo_name": "wrbrooks/lagr", "max_stars_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "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/deg.dist.r", "max_issues_repo_name": "wrbrooks/lagr", "max_issues_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "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/deg.dist.r", "max_forks_repo_name": "wrbrooks/lagr", "max_forks_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "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.3636363636, "max_line_length": 145, "alphanum_fraction": 0.60875, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6759696935479569}} {"text": "# Example : 3 Chapter : 5.3 Page No: 271\r\n# The inverse of the traingular matrix is traingular\r\nA<-matrix(c(1,1,1,1,0,1,1,1,0,0,1,1,0,0,0,1),ncol=4)\r\nA1<-solve(A)\r\nprint(\"The inverse of A is\")\r\nprint(A1)", "meta": {"hexsha": "546b936b89aca0d94f8b30031108a3a5205c57ba", "size": 209, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.3.3/Ex5.3_3.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.3.3/Ex5.3_3.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.3.3/Ex5.3_3.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 34.8333333333, "max_line_length": 53, "alphanum_fraction": 0.6363636364, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6758093943112276}} {"text": "\"\nИспользуя скрипты, написать программы, в которых требуется\n• получить вводом с клавиатуры два числа\n• первое число возвести в степень второго, вывести эти числа\nи результат\n• затем второе число возвести в степень первого, вывести\nрезультат\n• разделить первое число на второе, вывести результат\n• выполнить деление на ноль, посмотреть на результат\n\nУказание. Для ввода строки с клавиатуры использовать функцию readline().\nДля преобразования строки в число использовать функции as.integer(), as.double().\nДля формирования строки с результатами использовать функции paste(), paste0().\nДля вывода результатов функцию print().\n\"\n{\n \n #Получить вводом с клавиатуры два числа\n a1 <- as.integer(readline(\"Введите число №1 -> \"))\n a2 <- as.integer(readline(\"Введите число №2 -> \"))\n print(paste(\"Вы ввели числа\", a1, \"и\", a2))\n \n #первое число возвести в степень второго, вывести эти числа и результат\n result <- a1^a2\n print(paste0(a1,\"^\",a2,\" = \",result))\n \n #затем второе число возвести в степень первого, вывести результат\n result <- a2^a1\n print(paste0(a2,\"^\",a1,\" = \",result))\n \n #разделить первое число на второе, вывести результат\n result <- a1/a2\n print(paste0(a1,\"/\",a2,\" = \",result))\n \n #выполнить деление на ноль, посмотреть на результат\n result <- a1/0\n print(paste0(a1,\"/0 = \",result))\n \n}", "meta": {"hexsha": "551b79ee8befd866858242f661037cef365a54a6", "size": 1318, "ext": "r", "lang": "R", "max_stars_repo_path": "Course II/R/pract/pract3/task3.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course II/R/pract/pract3/task3.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course II/R/pract/pract3/task3.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 33.7948717949, "max_line_length": 81, "alphanum_fraction": 0.722306525, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6758093943112276}} {"text": "### Construct UMAU intervals for a truncated Gaussian\r\n\r\n\r\n\r\n\r\n## Simple functions for specifying and checking a \"cutoffs\" object, which\r\n## is just a matrix, each of whose rows is a non-empty real interval (infinite endpoints allowed)\r\n\r\ncheck.cutoffs <- function(cutoffs) {\r\n if(!is.matrix(cutoffs) || dim(cutoffs)[2] != 2) stop(\"cutoffs should be a matrix with 2 columns\")\r\n if(sum(cutoffs[,2] <= cutoffs[,1]) > 0) stop(\"all right endpoints should be > left endpoints\")\r\n if(sum(diff(c(t(cutoffs))) <= 0) > 0) stop(\"endpoints should be strictly increasing\")\r\n}\r\n\r\nnegate.cutoffs <- function(cutoffs) {\r\n -cutoffs[nrow(cutoffs):1,2:1,drop=FALSE]\r\n}\r\n\r\nnegate.cutoffs(rbind(c(-Inf,-4),c(-3,-2),c(7,Inf)))\r\n\r\ntwo.sided.cutoff <- function(x) rbind(neg=c(-Inf,-abs(x)),pos=c(abs(x),Inf))\r\n\r\ntwo.sided.cutoff(3)\r\n\r\n## Compute Phi(b-mu) - Phi(a-mu) in a numerically robust way\r\n## mu can be a vector\r\npnorm.interval <- function(mu, ab) {\r\n ifelse(mean(ab) - mu < 0,\r\n pnorm(ab[2] - mu) - pnorm(ab[1] - mu),\r\n pnorm(mu - ab[1]) - pnorm(mu - ab[2]))\r\n}\r\n\r\n## Compute Phi(b-mu) - Phi(a-mu) for each [a,b] in S\r\npnorm.cutoffs <- function(mu, cutoffs) {\r\n ret <- apply(cutoffs, 1, function(cut) pnorm.interval(mu, cut))\r\n if(!is.matrix(ret)) ret <- t(ret)\r\n dimnames(ret) <- list(as.character(mu),row.names(cutoffs))\r\n ret\r\n}\r\n\r\npnorm.cutoffs(-1:1,two.sided.cutoff(3))\r\npnorm.cutoffs(-1,two.sided.cutoff(3))\r\n\r\n\r\n## Compute phi(b-mu) - phi(a-mu) for each [a,b] in S\r\n## mu can be a vector\r\ndnorm.cutoffs <- function(mu, cutoffs) {\r\n ret <- apply(cutoffs, 1, function(cut) dnorm(cut[2] - mu) - dnorm(cut[1] - mu))\r\n if(!is.matrix(ret)) ret <- t(ret)\r\n dimnames(ret) <- list(as.character(mu),row.names(cutoffs))\r\n ret\r\n}\r\n\r\ndnorm.cutoffs(-1:1,two.sided.cutoff(3))\r\ndnorm.cutoffs(-1,two.sided.cutoff(3))\r\n\r\n## Compute P_mu(X= cutoffs[,1] & x <= cutoffs[,2])\r\n stopifnot(length(k)==1)\r\n (sum(pk[(1:K) < k]) + pnorm.interval(mu, c(cutoffs[k,1], x)) ) / p\r\n}\r\n\r\nF.mu(-10.01,0,two.sided.cutoff(10))\r\nF.mu(-9,0,two.sided.cutoff(10))\r\nF.mu(10.2,0,two.sided.cutoff(10))\r\n\r\n## Compute the inverse of the previous function\r\n## mu CANNOT be a vector, pk is a one-row matrix or vector\r\nF.inv.mu <- function(F, mu, cutoffs, pk=pnorm.cutoffs(mu, cutoffs)) {\r\n stopifnot(length(mu)==1, nrow(pk)==1 || !is.matrix(pk))\r\n p <- sum(pk)\r\n k <- max(which(c(0,cumsum(pk))/p < F))\r\n pnorm.increment <- p*F - c(0,cumsum(pk))[k]\r\n if(mean(cutoffs[k,]) < 0)\r\n mu + qnorm(pnorm(cutoffs[k,1]-mu) + pnorm.increment)\r\n else\r\n mu + qnorm(pnorm(cutoffs[k,1]-mu,lower.tail=FALSE) - pnorm.increment,lower.tail=FALSE)\r\n}\r\n\r\n## Compute c2(c1) for a single c1\r\n## mu CANNOT be a vector, pk is a one-row matrix or vector\r\nc2.single <- function(c1, mu, alpha, cutoffs, pk=pnorm.cutoffs(mu, cutoffs)) {\r\n stopifnot(length(mu)==1, nrow(pk)==1 || !is.matrix(pk))\r\n K <- length(pk)\r\n alpha1 <- F.mu(c1, mu, cutoffs, pk)\r\n if(alpha1 > alpha) return(NA)\r\n\r\n alpha2 <- alpha-alpha1\r\n return(F.inv.mu(1-alpha2, mu, cutoffs, pk))\r\n}\r\n\r\nc2.single(-10.3, 0, .05, two.sided.cutoff(10))\r\nF.mu(-10.3, 0, two.sided.cutoff(10))\r\n\r\n## Do the same, for a vector of c1 and mu\r\nc2 <- function(c1, mu, alpha, cutoffs, pk=pnorm.cutoffs(mu, cutoffs)) {\r\n sapply(1:length(c1),function(i)\r\n c2.single(c1[i], mu[i], alpha, cutoffs,\r\n pk[i,,drop=FALSE]))\r\n}\r\nc2(-10.3, 0, .05, two.sided.cutoff(10))\r\n\r\n\r\n## Compute g_mu(c1) for a single mu and c1 (see LaTeX documentation)\r\n## c1 and mu CANNOT be vectors, pk is NOT a matrix\r\ng.mu.single <- function(c1, mu, alpha, cutoffs,\r\n pk=pnorm.cutoffs(mu, cutoffs), dk=dnorm.cutoffs(mu, cutoffs)) {\r\n const <- (1-alpha) * (sum(-dk) + mu * sum(pk))\r\n cc2 <- c2(c1, mu, alpha, cutoffs, pk)\r\n if(is.na(cc2)) return(Inf)\r\n\r\n K <- length(pk)\r\n p <- sum(pk)\r\n k1 <- which(c1 >= cutoffs[,1] & c1 <= cutoffs[,2])\r\n stopifnot(length(k1)==1)\r\n k2 <- which(cc2 >= cutoffs[,1] & cc2 <= cutoffs[,2])\r\n stopifnot(length(k2)==1)\r\n\r\n if(k1 < k2) {\r\n sum(-dk[(1:K) > k1 & (1:K) < k2]) + mu * sum(pk[(1:K) > k1 & (1:K) < k2]) +\r\n - dnorm(cutoffs[k1,2] - mu) + dnorm(c1 - mu) - dnorm(cc2 - mu) + dnorm(cutoffs[k2,1] - mu) +\r\n mu * (pnorm.interval(mu,c(c1,cutoffs[k1,2])) + pnorm.interval(mu,c(cutoffs[k2,1], cc2))) -\r\n const\r\n } else {\r\n - dnorm(cc2 - mu) + dnorm(c1 - mu) + mu * pnorm.interval(mu,c(c1,cc2)) - const\r\n }\r\n}\r\n\r\n## Compute g_mu(c1) for a vector of mu and c1 (see LaTeX documentation)\r\ng.mu <- function(c1, mu, alpha, cutoffs,\r\n pk=pnorm.cutoffs(mu, cutoffs), dk=dnorm.cutoffs(mu, cutoffs)) {\r\n sapply(1:length(c1),function(i)\r\n g.mu.single(c1[i], mu[i], alpha, cutoffs,\r\n pk[i,,drop=FALSE], dk[i,,drop=FALSE]))\r\n}\r\n\r\ndnorm.cutoffs(c(0,0),two.sided.cutoff(10))\r\nc.vals <- seq(-10.3,-10.28,.001)\r\nplot(c.vals,g.mu(c.vals,rep(0,length(c.vals)), .05, two.sided.cutoff(10)))\r\n\r\ng.mu(-10.2925, 0, .05, two.sided.cutoff(10))\r\n\r\n## Compute g_mu'(c1)\r\ndg.mu <- function(c1, mu, alpha, cutoffs,\r\n pk=pnorm.cutoffs(mu, cutoffs)) {\r\n (c2(c1, mu, alpha, cutoffs, pk) - c1) * dnorm(c1 - mu)\r\n}\r\n\r\npoints(c.vals, g.mu(c.vals-.001, rep(0,length(c.vals)), .05, two.sided.cutoff(10)) +\r\n dg.mu(c.vals-.001, rep(0,length(c.vals)), .05, two.sided.cutoff(10)) * .001,col=\"red\",pch=3)\r\n\r\nmu.vals <- seq(-10,15,.1)\r\nplot(mu.vals, g.mu(rep(-10.2925,length(mu.vals)), mu.vals, .05, two.sided.cutoff(10)))\r\nmu.vals <- seq(-.001,.001,.0001)\r\nplot(mu.vals, g.mu(rep(-10.2925,length(mu.vals)), mu.vals, .05, two.sided.cutoff(10)))\r\n\r\n\r\n## Compute upper CI endpoint, for a single x, when sigma=1\r\numau.normal.unit.var.upper.single <- function(x, cutoffs, alpha=.05, mu.lo=x, mu.hi=x+2, tol=1E-8) {\r\n check.cutoffs(cutoffs)\r\n\r\n mu.too.low <- function(mu) {\r\n g.mu(x,mu,alpha,cutoffs) > 0\r\n }\r\n mu.too.high <- function(mu) {\r\n g.mu(x,mu,alpha,cutoffs) < 0\r\n }\r\n\r\n while(mu.too.high(mu.lo)) {\r\n mu.hi <- mu.lo\r\n mu.lo <- mu.lo - 2\r\n }\r\n while(mu.too.low(mu.hi)) {\r\n mu.lo <- mu.hi\r\n mu.hi <- mu.hi + 2\r\n }\r\n while(mu.hi - mu.lo > tol) {\r\n mu.avg <- (mu.lo + mu.hi) / 2\r\n if(mu.too.high(mu.avg)) {\r\n mu.hi <- mu.avg\r\n } else {\r\n mu.lo <- mu.avg\r\n }\r\n }\r\n mu.avg\r\n}\r\n\r\numau.normal.unit.var.upper.single(-10.29, two.sided.cutoff(10), mu.lo=-1, mu.hi=5)\r\numau.normal.unit.var.upper.single(-10.2925, two.sided.cutoff(10), mu.lo=-1, mu.hi=5)\r\n\r\n## Compute both CI endpoints, for a single x\r\numau.normal.single <- function(x, cutoffs, sigma=1, alpha=.05, mu.lo=x, mu.hi=x+2, tol=1E-8) {\r\n mu.upper <- sigma * umau.normal.unit.var.upper.single(x/sigma, cutoffs/sigma, alpha,\r\n mu.lo/sigma, mu.hi/sigma, tol)\r\n mu.lower <- -sigma * umau.normal.unit.var.upper.single(-x/sigma, negate.cutoffs(cutoffs)/sigma, alpha,\r\n -mu.hi/sigma, -mu.lo/sigma, tol)\r\n return(c(mu.lower, mu.upper))\r\n}\r\n\r\numau.normal.single(10.29, two.sided.cutoff(10))\r\numau.normal.single(1+10.29, 1+two.sided.cutoff(10))\r\numau.normal.single(-10.29, two.sided.cutoff(10))\r\numau.normal.single(1-10.29, 1+two.sided.cutoff(10))\r\n\r\numau.normal.single(10.005, two.sided.cutoff(10))\r\n\r\numau.normal.single(-13, two.sided.cutoff(10))\r\n\r\n\r\n## Compute both CI endpoints, for a vector of x\r\numau.normal <- function(x, cutoffs, sigma=1, alpha=.05, tol=1E-8) {\r\n sapply(1:length(x), function(i) umau.normal.single(x[i], cutoffs, sigma, alpha, tol=tol))\r\n}\r\n\r\n\r\n## Make UMAU CIs for two different S's:\r\n## first, (-Inf, -10) U (10, Inf)\r\n## second, (-Inf, -10) U (-0.1, 0.1) U (10, Inf)\r\n## We see that even a small sliver of additional support keeps the\r\n## CIs from \"reaching back\" too far\r\nx.vals <- c(seq(-20,-14,1),seq(-13,-10.4,.1),seq(-10.3,-10.06,.02),seq(-10.05,-10.01,.01),seq(-10.01,-10,.002))\r\nlength(x.vals)\r\nCIs10 <- umau.normal(x.vals, two.sided.cutoff(10))\r\nCIsMid <- umau.normal(x.vals, rbind(c(-Inf,-10),c(-.1,.1),c(10,Inf)))\r\n\r\nx.vals1side <- c(seq(10.14,10.3,.01),seq(10.4,11,.1),12:15)\r\nCIs1side <- umau.normal(x.vals1side, t(c(10,Inf)))\r\n\r\npdf(\"UMAU.pdf\",width=16)\r\npar(mfrow=c(1,3))\r\n\r\nmatplot(x.vals1side,t(CIs1side),type=\"l\",xlim=c(-20,20),ylim=c(-23,23),lty=1,col=1,\r\n xlab=\"Observed X\", ylab=\"UMAU Confidence Interval\",\r\n main=expression(S==(10*\",\"*infinity)))\r\nabline(h=0,lty=2)\r\nabline(v=10,lty=3)\r\nabline(0,1,lty=3)\r\n\r\nmatplot(x.vals,t(CIs10),type=\"l\",xlim=c(-20,20),ylim=c(-23,23),lty=1,col=1,\r\n xlab=\"Observed X\", ylab=\"UMAU Confidence Interval\",\r\n main=expression(S==(-infinity*\",\"*10)~U~(10*\",\"*infinity)))\r\nmatplot(-x.vals,t(-CIs10),type=\"l\",lty=1,col=1,add=TRUE)\r\nabline(h=0,lty=2)\r\nabline(v=c(-10,10),lty=3)\r\nabline(0,1,lty=3)\r\n\r\nmatplot(x.vals,t(CIsMid),type=\"l\",xlim=c(-20,20),ylim=c(-23,23),lty=1,col=1,\r\n xlab=\"Observed X\", ylab=\"UMAU Confidence Interval\",\r\n main=expression(S==(-infinity*\",\"*10)~U~(-.1*\",\"*.1)~U~(10*\",\"*infinity)))\r\nmatplot(-x.vals,-t(CIsMid),type=\"l\",lty=1,col=1,add=TRUE)\r\nabline(h=0,lty=2)\r\nabline(v=c(-10,10),lty=3)\r\nabline(0,1,lty=3)\r\ndev.off()\r\n\r\n", "meta": {"hexsha": "518a81acb25227416a7d932890f9541855f976f6", "size": 9619, "ext": "r", "lang": "R", "max_stars_repo_path": "umpu/umpu.r", "max_stars_repo_name": "TianXie1999/selective-inference", "max_stars_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2016-03-31T16:34:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T04:32:58.000Z", "max_issues_repo_path": "umpu/umpu.r", "max_issues_repo_name": "TianXie1999/selective-inference", "max_issues_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2016-04-07T00:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T18:31:14.000Z", "max_forks_repo_path": "umpu/umpu.r", "max_forks_repo_name": "TianXie1999/selective-inference", "max_forks_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-10-28T17:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T21:04:30.000Z", "avg_line_length": 36.713740458, "max_line_length": 112, "alphanum_fraction": 0.5816612954, "num_tokens": 3359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.675705787388754}} {"text": "#install.packages(\"openxlsx\")\n#install.packages(\"readr\")\nlibrary(forecast)\nlibrary(ggplot2)\nlibrary(openxlsx)\nlibrary(readr)\n\n\n# Importing xlsx file from local drive using openxlsx package\nsetwd(\"C:/Users/Samer/Desktop/Time Series\")\nelec = read.xlsx('Elec-train.xlsx', sheet = 1)\n\nnames(elec)[2] = \"pw\"\nnames(elec)[3] = \"tmp\"\n\n\nhead(elec)\nstr(elec)\n\n\n\n# Converting the first column into Datetime\n\nelec[,1] = as.POSIXct(elec[,1], format='%m/%d/%Y %H:%M')\nhead(elec)\n\n\n# Creating a Time Series object \n# Setting frequency = 4 to generate a horly Time Series\n\nelec_pw = ts(elec[,2], frequency = 4)\n\n# Removing NA values \nelec_pw = na.omit(elec_pw)\n\n# Vlaidating that ts has been created and we are ready to go with our forecasting\nis.ts(elec_pw)\n\n#plotting time series with Frequency = 4\n\nautoplot(elec_pw,) + \n ggtitle ('Power (kW/hr)') +\n xlab('Time (hr)') +\n ylab('Power (kW)')\n\n\n\n# Creating Train, Test datasets\n\nelec_pw_train= window(elec_pw, start=c(1,2), end=c(902,4))\nelec_pw_test= window(elec_pw, start=c(903,1), end=c(1127,4))\n\n# PLotting Train, Test Datasets (kw per HOUR)\nautoplot(elec_pw_train,series='Train') + \n autolayer(elec_pw_test,series='Test')+\n ggtitle ('Power (kW/h)') +\n xlab('Time (hr)') +\n ylab('Power (kW)')\n\n\n\n# Auto Correlation and Partial Auto Correlation\n\nacf(elec_pw)\nPacf(elec_pw)\n\n\n\n# Hotl Winters Additive\n\nhw_ad=hw(elec_pw_train,seasonal=\"additive\",damped=FALSE,h=900)\n\n# Plotting\n\nplot(elec_pw_train,xlim=c(1,1100),ylim=c(0,400))\nlines(elec_pw_test,lty=2)\nlines(hw_ad$mean,col=2)\n\n\n#the data should be differnciated\n#determining Lag will be depending in acf function \nacf(elec_pw, lag=150)\n\n\n\n# Diffferenciating ts with lag 96\nelec_pw %>% \ndiff(lag = 96) %>% \nggtsdisplay()\n\nBox.test(diff(elec_pw, lag=96), type=\"Ljung-Box\")\n\n\n#changing the freaqency of our data to 96\nelec_pw2 = ts(elec[,2], frequency = 96)\nelec_pw2 = na.omit(elec_pw2)\n\n\n# building new Train and Test Datasets\nelec_pw_train2 = head(elec_pw2,3606)\nelec_pw_test2 = tail(elec_pw2,901)\n\nautoplot(elec_pw_train2,series=\"Train\") + \n autolayer(elec_pw_test2,series='Test ')+\n ggtitle ('Power') +\n xlab('Time') +\n ylab('Power (kW)')\n\n#Holt Winters - Additive\n\nhw_add <- HoltWinters(elec_pw_train2,alpha=NULL,beta=NULL,gamma=NULL)\n\n#Plotting\nplot(elec_pw_train2,ylim=c(100,350))\nhw_add_p <- forecast(hw_add, h=96)\nlines(p,col=2)\n\n#RMSE\nprint(paste(\"RMSE for HW-Additive:: \",sqrt(mean((hw_add_p$mean-elec_pw_test2)^2))))\n\n\n# SARIMA\n\nauto_arima <- auto.arima(elec_pw_train2)\nauto_arima\n\n#Plotting\nautoplot(forecast(auto_arima, h=96))\n\n#RMSE\nauto_arima_p <- forecast(auto_arima, h=96)\nprint(paste(\"Auto ARIAM \",sqrt(mean((auto_arima_p$mean-elec_pw_test2)^2))))\n\n\n#Checking residuals to see of there is any correlation missed by automatic function, and we will try to enhance it manually \ncheckresiduals(auto_arima, lag.max=200)\n\n# Neural Networks\nANN <- nnetar(elec_pw_train2)\nprint(ANN)\n\n#Plotting\nautoplot(forecast(ANN, h=96))\n\n#RMSE\nANN_P <- forecast(ANN, h=96)\nprint(paste(\"Neural Network \",sqrt(mean((ANN_P$mean-elec_pw_test2)^2))))\n\n\n#Without Tempreture Final Results\nprint(paste(\"RMSE for HW-Additive: \",sqrt(mean((hw_add_p$ mean-elec_pw_test2)^2))))\nprint(paste(\"Auto ARIMA: \",sqrt(mean((auto_arima_p$ mean-elec_pw_test2)^2))))\nprint(paste(\"Neural Network: \",sqrt(mean((ANN_P$ mean-elec_pw_test2)^2))))\n\n# Forecasting using Auto Arima\nPower_final <- auto.arima(elec_pw2)\nPower_final_p <- forecast(Power_final, h= 96)\n\n\n# Plotting Final Model with zoom on day 17FEB\n\nautoplot(elec_pw2,series=\"Power 01JAN10 - 16FEB10\") + \n autolayer(Power_final_p$mean,series='17FEB10 Prediction')+\n ggtitle ('Power (kw/hr)') +\n# Zooming on forecasting to have better look\n coord_cartesian(xlim = c(40,50))+\n xlab('hr') +\n ylab('kW')\n\n#Save Predection results to local CSV\n\nPrediction_Power <- print(Power_final_p)\n\nwrite_csv(Prediction_Power,path=\"C:/Users/Samer/Desktop/Time Series/Evaluation/Forecast_withOUT_Temprature.csv\")\n\nelec = read.xlsx('Elec-train.xlsx', sheet = 1)\n\nhead(elec)\nstr(elec)\n\n# Converting the first column into Datetime\n\nelec[,1] = as.POSIXct(elec[,1], format='%m/%d/%Y %H:%M')\n\nhead(elec)\nstr (elec)\n\n# Creating a Time Series object \n\nelec_pw_c = ts(elec[,2:3], frequency = 96)\n\nnames(elec)[2] = \"pw\"\nnames(elec)[3] = \"tmp\"\n\n# Suprressing NA values \nelec_pw_c = na.omit(elec_pw_c)\n\n# Vlaidating that ts has been created and we are ready to go with our forecasting\nis.ts(elec_pw_c)\n\n# building new Train and Test Datasets (89% Train, 20% Test)\nelec_pw_c_train = head(elec_pw_c,3606)\nelec_pw_c_test = tail(elec_pw_c,901)\n\n\n\nautoplot(elec_pw_c[,2])\n\n\n# Time Series Linear Regression Model\n\ntslm=tslm(elec_pw_c_train[,1]~elec_pw_c_train[,2]+trend+season, data=elec_pw_c_train)\n\nsummary(tslm)\nCV(tslm)\ncheckresiduals(tslm,test='LB',plot=TRUE)\n\n\n\n#Dynamic Regression Model\n\ndynamic_reg <- auto.arima(elec_pw_c_train[,1],xreg = elec_pw_c_train[,2])\nsummary(dynamic_reg)\n\n#Plotting\nautoplot(forecast(dynamic_reg,xreg=rep(mean(elec_pw_c_train[,2]),96)))\n\n#RMSE\ndynamic_reg_p <- forecast(dynamic_reg,xreg = elec_pw_c_test[,2], h=96)\nprint(paste(\"Dynamic Regression - with Temprature: \",sqrt(mean((dynamic_reg_p$mean-elec_pw_c_test[,1])^2))))\n\n\n#Check if residuals are white noise\n\ndynamic_reg %>% residuals() %>% Box.test()\n\n\n\n# Neural Network - with Temprature\n\nANN_TMP <- nnetar(elec_pw_c_train[,1],xreg = elec_pw_c_train[,2])\nANN_TMP\n\n# Plotting\nautoplot(forecast(ANN_TMP,xreg=rep(mean(elec_pw_c_train[,2]),96)))\n\n# RMSE\nANN_TMP_P <- forecast(ANN_TMP,xreg = elec_pw_c_test[,2], h=96)\nprint(paste(\"Auto Neural Network - with Temprature: \",sqrt(mean((ANN_TMP_P$mean-elec_pw_c_test[,1])^2))))\n\n\n\n# Trying to have a general (Zoomed) overview to assess the models performance\n# but as expected and Dynamic Regression model is our hero today, with the lowest RMSE!\n\nautoplot(elec_pw_train2, series=\"Train set\") + \n autolayer(elec_pw_test2, series='Test set' )+\n autolayer(ANN_TMP_P$mean, series='Neural Network')+\n autolayer(dynamic_reg_p$mean, series='Dynamic Regression with Temperature')+\n coord_cartesian(xlim = c(35,50))+\n ggtitle ('Power (kW/hr)') +\n xlab('(hr)') +\n ylab('(kW)')\n\n#With Tempreture Final Results\nprint(paste(\"Dynamic Regression - with Temprature: \",sqrt(mean((dynamic_reg_p$mean-elec_pw_c_test[,1])^2))))\nprint(paste(\"Auto Neural Network - with Temprature: \",sqrt(mean((ANN_TMP_P$mean-elec_pw_c_test[,1])^2))))\n\n\n#Extract temperature of 17th Feb to make new time series object for forecast\ntmp17 <- ts(elec[4508:4603,3], frequency = 4, start=c(1,2))\nis.ts(tmp17)\n\n#### ignore - data check\n#tmp_chk<-elec[4508:4603,3]\n\n#tmp_test <- print(tmp_chk)\n\n#write_csv(as.data.frame(tmp_test),path=\"C:/Users/Samer/Desktop/Time Series/Evaluation/tmpcheck.csv\")\n\n# Forecasting using Auto Arima\nPower_tmp_final <-auto.arima(elec_pw_c[,1], xreg = elec_pw_c[,2])\nPower_tmp_final_p <- forecast (Power_tmp_final, xreg = tmp17, h= 96)\n\n\n# Plotting Final Model with zoom on day 17FEB\n\nautoplot(elec_pw2,series=\"Power 01JAN10 - 16FEB10\") + \n autolayer(Power_tmp_final_p$mean,series='17FEB10 Prediction WITH TEMPRETURE')+\n ggtitle ('Power (kw/hr)') +\n# Zooming on forecasting to have better look\n coord_cartesian(xlim = c(40,50))+\n xlab('hr') +\n ylab('kW')\n\n#Save Predection results to local CSV\n\nPrediction_Power <- print(Power_tmp_final_p)\n\nwrite_csv(Prediction_Power,path=\"C:/Users/Samer/Desktop/Time Series/Evaluation/Forecast_with_Temprature.csv\")\n\nd=1\nDD=1\nper=52\nfor(p in 1:4){\n for(q in 1:2){\n for(P in 0:4){\n for(Q in 0:2){\n if(p+d+q+P+DD+Q<=10){\n try({model<-arima(x=elec_pw_train2, order = c((p),d,(q)), seasonal = list(order=c((P),DD,(Q)), period=per))\n pval<-Box.test(model$residuals, lag=log(length(model$residuals)))\n sse<-sum(model$residuals^2)\n cat(p,d,q,P,DD,Q,per, 'AIC=', model$aic, ' SSE=',sse,' p-VALUE=', pval$p.value,'\\n') })}}}}}\n", "meta": {"hexsha": "f6c9d8760015d843e4a04d8dfb83f0a38982c9bb", "size": 7904, "ext": "r", "lang": "R", "max_stars_repo_path": "Time_Series_Project.r", "max_stars_repo_name": "Samer-Is/Time-Series-Forecasting", "max_stars_repo_head_hexsha": "911a197d475524a460b716bf1b60692f96c2bfab", "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": "Time_Series_Project.r", "max_issues_repo_name": "Samer-Is/Time-Series-Forecasting", "max_issues_repo_head_hexsha": "911a197d475524a460b716bf1b60692f96c2bfab", "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": "Time_Series_Project.r", "max_forks_repo_name": "Samer-Is/Time-Series-Forecasting", "max_forks_repo_head_hexsha": "911a197d475524a460b716bf1b60692f96c2bfab", "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": 25.1719745223, "max_line_length": 124, "alphanum_fraction": 0.7131831984, "num_tokens": 2563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6757000594901438}} {"text": "model_stochastic_simulateR <- function(init_obs_current, init_obs_daily, period_start, pi_fn,timestrain,timestest, pars, fix_pars, T_predict, ...){\n stochastic_sampleR <- function(stage_pars, fix_pars, old_values) {\n ## stage pars\n b = stage_pars[1]\n r = stage_pars[2]\n ## fixed pars\n alpha_p = fix_pars[1] \n alpha_u = fix_pars[2]\n beta_1 = fix_pars[3]\n beta_2 = fix_pars[4]\n delta_1 = fix_pars[5]\n delta_2 = fix_pars[6]\n lambda = fix_pars[7]\n mu = fix_pars[8]\n mu_c = fix_pars[9]\n De = fix_pars[10]\n Dr = fix_pars[11]\n f = fix_pars[12]\n N = fix_pars[13]\n ## old values\n S = old_values[1]\n E = old_values[2]\n U = old_values[3]\n P = old_values[4]\n F = old_values[5]\n RU = old_values[6]\n RR = old_values[7]\n DU = old_values[8]\n DR = old_values[9]\n ##\n pS_vec <- c( b * (alpha_p * P + alpha_u * U + F) / N , mu, 1 - b * (alpha_p * P + alpha_u * U + F) / N - mu)\n sample_S <- rmultinom(1, size = S, prob = pS_vec)\n ##\n pE_vec <- c((1-r) / De, r * (1-f) / De, r*f/De, mu,1 - 1 / De - mu)\n sample_E <- rmultinom(1, size = E, prob = pE_vec)\n ##\n pU_vec <- c(1/(beta_1*Dr),delta_1*mu_c,mu,1-1/(beta_1*Dr)-delta_1*mu_c-mu)\n \n sample_U <- rmultinom(1, size = U, prob = pU_vec)\n ##\n pP_vec <- c(1 / Dr, mu_c,mu, 1 - 1 / Dr - mu-mu_c)\n sample_P <- rmultinom(1, size = P, prob = pP_vec)\n ##\n pF_vec <- c(beta_2 / Dr, mu_c/delta_2,mu,1 -beta_2 / Dr- mu_c/delta_2-mu)\n sample_F <- rmultinom(1, size = F, prob = pF_vec)\n ##\n pRU_vec <- c( mu,1-mu)\n sample_RU <- rmultinom(1, size = RU, prob = pRU_vec)\n ##\n pRR_vec <- c(mu,1-mu)\n sample_RR <- rmultinom(1, size = RR, prob = pRR_vec)\n ## new values\n S_new <- sample_S[3] + lambda*N\n E_new <- sample_E[5] + sample_S[1]\n U_new <- sample_U[4] + sample_E[1]\n P_new <- sample_P[4] + sample_E[2]\n F_new <- sample_F[4] + sample_E[3]\n RU_new <- sample_RU[2] + sample_U[1]+sample_F[1]\n RR_new <- sample_RR[2] + sample_P[1]\n DU_new <- DU + sample_U[2]+sample_F[2]\n DR_new <- DR + sample_P[2]\n est_P_new<- sample_E[2]\n est_RR_new<- sample_P[1]\n est_DR_new <- sample_P[2]\n est_F_new<-sample_E[3]\n est_U_new<-sample_E[1]\n return(c(S_new, E_new, U_new, P_new, F_new, RU_new, RR_new, DU_new, DR_new, \n est_P_new,est_RR_new,est_DR_new,est_F_new,est_U_new))\n }\n n_period = length(period_start)\n \n which.period <- function(i, phase = period_start){ # function to determine which period i falls in\n sum(i >= phase)\n }\n\n for(i in 1:length(timestrain)){\n stage_pars <- c(b = pars[which.period(i)], r = pars[n_period + which.period(i)])\n if(i == 1) {\n old_values <- init_obs_current\n results = matrix(c(init_obs_current,init_obs_daily,0,0), nrow = 1)\n } else {\n now_values <- stochastic_sampleR(stage_pars = stage_pars, fix_pars = fix_pars, old_values = old_values)\n results = rbind(results, now_values)\n old_values <- now_values[1:9]\n }\n }\n \n for(j in 1:length(timestest)){\n stage_pars <- c(b=pars[n_period]*pi_fn[j], r = pars[2*n_period])\n now_values <- stochastic_sampleR(stage_pars = stage_pars, fix_pars = fix_pars, old_values = old_values)\n results = rbind(results, now_values)\n old_values <- now_values[1:9]\n }\n\n return(results)\n}", "meta": {"hexsha": "de7fb20451009bc67c4d021ff1384893860a6e60", "size": 3323, "ext": "r", "lang": "R", "max_stars_repo_path": "model/seirfansy_f=0/model_stochastic_simulateR.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/model_stochastic_simulateR.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/model_stochastic_simulateR.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": 34.6145833333, "max_line_length": 147, "alphanum_fraction": 0.6093891062, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6756018099483155}} {"text": "# Function for generating data and calculating initial summaries\n\ngendata<-function(nI,J,K,nd,dstbn,par1){\n \n nondom=nd\n \n # Lower and upper limits for mean, std. dev. and skewness \n # mean\n ml=0.2\n mu=0.8\n # low st. dev.\n lvl=0.02\n lvu=0.04\n # high st. dev.\n hvl=0.08\n hvu=0.1\n # positive skewness\n lskew=0.5\n uskew=1\n \n # nInitialize arrays\n # Generated Data\n gdata=array(rep(0,nI*J*K),c(nI,J,K))\n # Standardized (generated) data\n stdata=array(rep(0,nI*J*K),c(nI,J,K))\n # Summary of generated data\n gsum=array(rep(0,nI*J*11),c(nI,J,11))\n \n # Generate means from uniform distribution\n gsum[,,1]=runif(nI*J,ml,mu)\n \n # For non-dominated alternatives, standardize criteria means with sum of squares equal to 1\n if (nondom==\"T\"){ \n gsum_t = gsum[,,1]^2\n gsum[,,1]=sqrt(gsum_t/apply(gsum_t,1,sum))\n }\n \n # Generate low or high variances from uniform distribution\n if (par1==\"lowvar\"){gsum[,,2]=runif(nI*J,lvl,lvu)}else{gsum[,,2]=runif(nI*J,hvl,hvu)}\n \n if (dstbn==\"normal\"){\n # Generate data from normal distribution\n gdata<-rnorm(nI*J*K,gsum[,,1],gsum[,,2])\n dim(gdata)<-c(nI,J,K)\n } else if (dstbn==\"skew\"){ \n # Generate skewness\n gsum[,,3]=runif(nI*J,lskew,uskew)\n \n for (i in 1:nI){\n for (j in 1:J){\n # Gamma shape parameter\n gshape=(2/gsum[i,j,3])^2\n # Gamma scale parameter\n gscale=sqrt((gsum[i,j,2])^2/gshape)\n # Generate data from Gamma distbn [mean + ~G(0,gshape,gscale)] \n gdata[i,j,]=gsum[i,j,1]+rgamma(K,shape=gshape,scale=gscale)-gshape*gscale\n }\n }\n }\n \n for (j in 1:J){\n # Standardize all data values on each criterion to lie between 0 and 1\n stdata[,j,]=(gdata[,j,]-min(gdata[,j,]))/(max(gdata[,j,])-min(gdata[,j,]))\n }\n \n # Populate gsum for generated data from normal distribution\n if (dstbn==\"normal\"){\n for (m in 1:nI){\n for (n in 1:J){\n gsum[m,n,4]=mean(gdata[m,n,]) # normal mean parameter\n gsum[m,n,5]=sd(gdata[m,n,]) # normal stdev parameter \n gsum[m,n,7]=mean(stdata[m,n,]) # mean of st. data\n gsum[m,n,8]=var(stdata[m,n,]) # variance of st. data\n gsum[m,n,9]=quantile(stdata[m,n,],probs=0.05) # l. quantile of st. data\n gsum[m,n,10]=quantile(stdata[m,n,],probs=0.5) # m. quantile of st. data\n gsum[m,n,11]=quantile(stdata[m,n,],probs=0.95) # u. quantile of st. data\n }\n }\n } else if (dstbn==\"skew\"){ \n for (m in 1:nI){\n for (n in 1:J){\n gsum[m,n,4]=mean(gdata[m,n,]) # gamma mean parameter \n skewness = mean((gdata[m,n,]-mean(gdata[m,n,]))^3)/(var(gdata[m,n,])^1.5)\n gsum[m,n,5]=(2/skewness)^2 # gamma shape parameter\n gsum[m,n,6]=sqrt(var(gdata[m,n,])/gsum[m,n,5]) # gamma scale parameter\n gsum[m,n,7]=mean(stdata[m,n,]) # mean of st. data\n gsum[m,n,8]=var(stdata[m,n,]) # variance of st. data\n gsum[m,n,9]=quantile(stdata[m,n,],probs=0.05) # l. quantile of st. data\n gsum[m,n,10]=quantile(stdata[m,n,],probs=0.5) # m. quantile of st. data\n gsum[m,n,11]=quantile(stdata[m,n,],probs=0.95) # u. quantile of st. data\n }\n }\n }\n list(stdata=stdata,gsum=gsum)\n}\n", "meta": {"hexsha": "dbe01638ff280057c265a332139a64d086caeeac", "size": 3393, "ext": "r", "lang": "R", "max_stars_repo_path": "Generate.r", "max_stars_repo_name": "iandurbach/SMAA-uncertainty-simulation", "max_stars_repo_head_hexsha": "361a4458a7ca508f30e135aaaba5bcf1336f31af", "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": "Generate.r", "max_issues_repo_name": "iandurbach/SMAA-uncertainty-simulation", "max_issues_repo_head_hexsha": "361a4458a7ca508f30e135aaaba5bcf1336f31af", "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": "Generate.r", "max_forks_repo_name": "iandurbach/SMAA-uncertainty-simulation", "max_forks_repo_head_hexsha": "361a4458a7ca508f30e135aaaba5bcf1336f31af", "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.34375, "max_line_length": 95, "alphanum_fraction": 0.5523135868, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6756018014785804}} {"text": "\r\n\r\n# Goal: Using data from Yahoo finance, estimate the beta of Sun Microsystems\r\n# for weekly returns.\r\n# This is the `elaborate version' (36 lines), also see terse version (16 lines)\r\n\r\nlibrary(tseries)\r\n\r\n# I know that the yahoo symbol for the common stock of Sun Microsystems\r\n# is \"SUNW\" and for the S&P 500 index is \"^GSPC\".\r\nprices <- cbind(get.hist.quote(\"SUNW\", quote=\"Adj\", start=\"2003-01-01\", retclass=\"zoo\"),\r\n get.hist.quote(\"^GSPC\", quote=\"Adj\", start=\"2003-01-01\", retclass=\"zoo\"))\r\ncolnames(prices) <- c(\"SUNW\", \"SP500\")\r\nprices <- na.locf(prices) # Copy last traded price when NA\r\n\r\n# To make weekly returns, you must have this incantation:\r\nnextfri.Date <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1)\r\n# and then say\r\nweekly.prices <- aggregate(prices, nextfri.Date,tail,1)\r\n\r\n# Now we can make weekly returns --\r\nr <- 100*diff(log(weekly.prices))\r\n\r\n# Now shift out of zoo to become an ordinary matrix --\r\nr <- coredata(r)\r\nrj <- r[,1]\r\nrM <- r[,2]\r\nd <- lm(rj ~ rM) # Market model estimation.\r\nprint(summary(d))\r\n\r\n# Make a pretty picture\r\nbig <- max(abs(c(rj, rM)))\r\nrange <- c(-big, big)\r\nplot(rM, rj, xlim=range, ylim=range,\r\n xlab=\"S&P 500 weekly returns (%)\", ylab=\"SUNW weekly returns (%)\")\r\ngrid()\r\nabline(h=0, v=0)\r\nlines(rM, d$fitted.values, col=\"blue\")\r\n\r\n", "meta": {"hexsha": "ac5abedbbcabfbe7774beab61fdd9660e89a01e5", "size": 1353, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o5.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o5.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o5.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.825, "max_line_length": 90, "alphanum_fraction": 0.6334072432, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6752557478846951}} {"text": "# Program to find the sum of natural numbers upto n using recursion\ncalculate_sum() <- function(n) {\nif(n <= 1) {\nreturn(n)\n} else {\nreturn(n + calculate_sum(n-1))\n}\n}", "meta": {"hexsha": "e8f6e8e563909a2958ae2bf856034488a2cc6f5e", "size": 167, "ext": "r", "lang": "R", "max_stars_repo_path": "sum_of_natural_numbers.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "sum_of_natural_numbers.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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": "sum_of_natural_numbers.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "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.875, "max_line_length": 67, "alphanum_fraction": 0.6766467066, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.675078137091232}} {"text": "#################################################################################\r\n## Code generating Figure 5 and expected serial interval quoted in manuscript #\r\n################################################################################\r\n\r\n####################\r\n# Define functions #\r\n####################\r\n\r\n#truncated normal\r\nrtnorm <- function(n, mean, sd, a = 0, b = 1){\r\n qnorm(runif(n, pnorm(a, mean, sd), pnorm(b, mean, sd)), mean, sd)\r\n}\r\n\r\n## Transparent colors\r\n## Mark Gardener 2015\r\n## www.dataanalytics.org.uk\r\nt_col <- function(color, percent = 10, name = NULL) {\r\n #\t color = color name\r\n #\tpercent = % transparency\r\n #\t name = an optional name for the color\r\n ## Get RGB values for named color\r\n rgb.val <- col2rgb(color)\r\n ## Make new color using input color as base and alpha set by transparency\r\n t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],\r\n max = 255,\r\n alpha = (100-percent)*255/100,\r\n names = name)\r\n ## Save the color\r\n invisible(t.col)\r\n \r\n}\r\n## END\r\nl<-function(t,As){\r\n t[t<0]<-0\r\n As*t*exp(-0.5*As*t*t)}\r\n\r\nline<-function(t,shift=15, A){lines(t,l(t-shift,A),type =\"l\", lwd=0.5, col= mycol)}\r\n\r\nmycol<-t_col(\"red\",percent =50)\r\n\r\n# illustration of SI prior with parameters used in main text- this is from a truncated normal distribution, normal uniform bounded distribution version commented out\r\n\r\n#incubation period\r\nshift<-15\r\n#Alpha parameter\r\nAs<-0.003\r\n\r\nt<- c(1:200)\r\n\r\nplot(t,l(t-shift,As),type =\"l\", lwd=0.5, col= \"red\", xlab = \"Time\", ylab=\"Probability density\", ylim=c(0,0.12), cex.lab=1.5, cex.axis =1.5 )\r\n\r\n#we set a prior for Alpha with mean 0.003 and sd 0.01,using a truncated normal distribution\r\n#As<-runif(300,0.00001,0.02)\r\nAs<-rtnorm(1000,0.003,0.01)\r\n#As<-rtnorm(1000,0.002,0.1)\r\n\r\n\r\nquant<-quantile(As,c(0.025,0.975,0.5))\r\nAs_2.5<-quant[1]\r\nAs_97.5<-quant[2]\r\nAs_0.5<-quant[3]\r\n\r\n#2.5% quantile \r\nt[which.max(l(t-shift,As_2.5))]\r\n\r\n#97.5% quantile\r\nt[which.max(l(t-shift,As_97.5))]\r\n\r\n#median\r\nt[which.max(l(t-shift,As_0.5))]\r\n\r\nfor(i in 1:length(As)){\r\n line(t=t,A=As[i])\r\n}\r\nAs<-0.003\r\nlines(t,l(t-shift,As), type =\"l\", lwd=5, col= \"black\")\r\nlines(t,l(t-shift,As_2.5), type =\"l\", lwd=5,lty=\"dashed\", col= \"black\")\r\nlines(t,l(t-shift,As_97.5), type =\"l\", lwd=5, lty= \"dashed\", col= \"black\")\r\ntitle(\"Serial Interval Distribution\", cex.main=2)", "meta": {"hexsha": "1476d8ba5f2019f46cb8c761b55d5520135cceea", "size": 2364, "ext": "r", "lang": "R", "max_stars_repo_path": "Source_Code_File_3_Source_code_to_generate_Figure_5.r", "max_stars_repo_name": "IzzyRou/estimates-Rc-China", "max_stars_repo_head_hexsha": "767cfcfbb42f62799aea8c9c92c3e453d4e945c5", "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": "Source_Code_File_3_Source_code_to_generate_Figure_5.r", "max_issues_repo_name": "IzzyRou/estimates-Rc-China", "max_issues_repo_head_hexsha": "767cfcfbb42f62799aea8c9c92c3e453d4e945c5", "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_File_3_Source_code_to_generate_Figure_5.r", "max_forks_repo_name": "IzzyRou/estimates-Rc-China", "max_forks_repo_head_hexsha": "767cfcfbb42f62799aea8c9c92c3e453d4e945c5", "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.9240506329, "max_line_length": 166, "alphanum_fraction": 0.5710659898, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6749950252551795}} {"text": "rm(list = ls())\nlibrary(ggplot2)\nlibrary(fpp2)\nlibrary(RMSE)\nfile <- \"~/SeniorStats/HW4/STA372_Homework4_Question3.dat.txt\"\ndata_table <- read.table(file, header = FALSE, sep = \"\")\ncolnames(data_table) <- c(\"Week\",\"Y\",\"FixedForcast\")\n\nhead(data_table)\ntail(data_table)\n\n\nfigure <- ggplot()\nfigure <- figure + geom_point(aes(data_table$Week, data_table$Y))\nfigure <- figure + geom_line(aes(data_table$Week, data_table$Y))\nfigure <- figure + scale_y_continuous()\nfigure <- figure + ggtitle(\"Time series plot of Y (Solid black line) and in-sample forecasts\")\nfigure <- figure + xlab(\"Week\") + ylab(\"Y\")\nprint (figure)\nprint(\"There is a pattern in Y through time and it is a pattern of increasing over time\")\n\ndata_table$Error <- data_table$Y - data_table$FixedForcast\nRMSE_FixedForcast <- sqrt(sum(data_table$Error^2)/nrow(data_table))\nprint(RMSE_FixedForcast)\n\ny_time_series <- ts(data_table[,2]) \nresult_random_walk <- ses(y_time_series, alpha=1, initial=\"simple\", h=1)\nresult_random_walk$model\naccuracy(result_random_walk)\nprint(\"The RMSE here was 63.10765\")\n\ndata_table$forcast <- result_random_walk$fitted\ndata_table$residualswalk <- result_random_walk$residuals\nhead(data_table)\ntail(data_table)\n\nresult <- ses(y_time_series, initial=\"simple\", h=3)\nresult$model\n\nprint(result)\ndata_table$forcast2 <- result$fitted\ndata_table$residuals <-result$residuals\nhead(data_table)\ntail(data_table)\n\nfigure2 <- ggplot() \nfigure2 <- figure2 + geom_point(aes(data_table$Week, data_table$Y))\nfigure2 <- figure2 + geom_line(aes(data_table$Week, data_table$Y))\nfigure2 <- figure2 + geom_point(aes(data_table$Week, data_table$forcast2), color=\"Red\")\nfigure2 <- figure2 + geom_line(aes(data_table$Week, data_table$forcast2), color=\"Red\", lty=2)\nfigure2 <- figure2 + scale_y_continuous()\nfigure2 <- figure2 + ggtitle(\"Time series plot of Y (Solid black line) and in-sample forecasts\") \nfigure2 <- figure2 + xlab(\"Week\") + ylab(\"Y\")\nprint (figure2)\naccuracy(result)\nprint(\"The RMSE here is 54.70586\")\n\n\n\nfigure3 <- ggplot()\nfigure3 <- figure3 + geom_point(aes(data_table$Week, data_table$residuals))\nfigure3 <- figure3 + geom_line(aes(data_table$Week, data_table$residuals))\nfigure3 <- figure3 + scale_y_continuous()\nfigure3 <- figure3 + ggtitle(\"In-sample forecast errors\")\nfigure3 <- figure3 + xlab(\"Time\") + ylab(\"Residuals\")\nprint (figure3) \n\nggAcf(data_table$residuals)\nsummary(result)\n\nprint(\"The residuals are not independent, this implies that there is information leftover in the residuals that will not be reflected in the formal forcasting.\")\nprint(\"We should use the model that was used for figure 2, the Simple Exponential smoothing model, not the random walk model\")\nprint(\"seasonal factor is .975\")\nseasonal <- .975*839.4273\nseasonal\nprint(\"The week 67 forcast of volume is 818.4416, and the 95% CI is (732.2058, 946.6488)\")\n", "meta": {"hexsha": "aa4d1cf0d698f9a0bd703d38e3b2b1264844a09c", "size": 2824, "ext": "r", "lang": "R", "max_stars_repo_path": "Forecasting/Exponetial_Smooting/Exponential Smoothing.r", "max_stars_repo_name": "PeterShortino20/Financial-Econometric-Modeling", "max_stars_repo_head_hexsha": "8250110c1d7290a01bc4d3f061c0bdebada2d104", "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": "Forecasting/Exponetial_Smooting/Exponential Smoothing.r", "max_issues_repo_name": "PeterShortino20/Financial-Econometric-Modeling", "max_issues_repo_head_hexsha": "8250110c1d7290a01bc4d3f061c0bdebada2d104", "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": "Forecasting/Exponetial_Smooting/Exponential Smoothing.r", "max_forks_repo_name": "PeterShortino20/Financial-Econometric-Modeling", "max_forks_repo_head_hexsha": "8250110c1d7290a01bc4d3f061c0bdebada2d104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-20T13:56:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T13:56:10.000Z", "avg_line_length": 36.6753246753, "max_line_length": 161, "alphanum_fraction": 0.7553116147, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6749496238695243}} {"text": "#'@title calcDispUnitConversion\n#'\n#'@description Convert displacement in tonnages to cubic meters.\n#'\n#'@param tonnageDisp Displacement (vector of numericals, tonnage)\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#'\n#'@return \\code{disp} (vector of numericals, m^3)\n#'\n#'@examples\n#'calcDispUnitConversion(70000, 1.025)\n#'\n#'@export\n\ncalcDispUnitConversion<- function(tonnageDisp, seawaterDensity=1.025){\n\n disp<- tonnageDisp/seawaterDensity\n\n return(disp)\n}\n", "meta": {"hexsha": "a39306a8bacdd8fe31bf2cbfb03181ebb994a05d", "size": 572, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcDispUnitConversion.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/calcDispUnitConversion.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/calcDispUnitConversion.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": 26.0, "max_line_length": 79, "alphanum_fraction": 0.7465034965, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6749491970966539}} {"text": "# CS422 Data Mining\n# Vijay K. Gurbani, Ph.D.\n# Illinois Institute of Technology\n\n# DBSCAN clustering on non-globular data\n\nlibrary(fpc)\nlibrary(factoextra)\nlibrary(dbscan)\n\nset.seed(123)\n\nrm(list=ls())\n\ndata(\"multishapes\", package = \"factoextra\")\ndf <- multishapes[, 1:2]\n\nplot(df, main=\"Raw points before DBSCAN\")\n\n# Let's run k-means on this first. Choose a value of k...\nk <- kmeans(df, centers=5, nstart=25)\nfviz_cluster(k, df)\n\n# ---- Now, onto dbscan\n# Run dbscan\ndb <- fpc::dbscan(df, eps = 0.15, MinPts = 5)\nplot(db, df, main = \"DBSCAN\", frame = FALSE)\n\n# You can also draw this using fviz_cluster\nfviz_cluster(db, df, stand = FALSE, ellipse = F, geom = \"point\")\n\n# In the output below, column names are cluster numbers. Cluster 0 corresponds\n# to noise (outliers)\nprint(db)\n\n# How to determine eps and k (MinPts)?\n# k is provided by the user. EPS is determined by looking at the \"knee\".\n# For example, head(kNNdist(df, k=5)) shows a numeric vector with distance\n# to its k-nearest neighbours. kNNdistplot() samples the points from df and\n# calculates the distance to 5-NN. Look at the \"knee\" and you will find the\n# (pot of gold, err) eps.\ndbscan::kNNdistplot(df, k = 5)\nabline(h = 0.15, lty = 2)\n\n", "meta": {"hexsha": "6d906b0667977cfc35e2ac0e6a977b7660a7db20", "size": 1214, "ext": "r", "lang": "R", "max_stars_repo_path": "hw8/dbscan-clust.r", "max_stars_repo_name": "liwenlongonly/cs422_hw", "max_stars_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "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": "hw8/dbscan-clust.r", "max_issues_repo_name": "liwenlongonly/cs422_hw", "max_issues_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "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": "hw8/dbscan-clust.r", "max_forks_repo_name": "liwenlongonly/cs422_hw", "max_forks_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "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.9777777778, "max_line_length": 79, "alphanum_fraction": 0.6985172982, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6748527436415316}} {"text": "=begin\n # sample-geometry02.rb\n\n require 'algebra'\n R = MPolynomial(Rational)\n x,y,a1,a2,b1,b2,c1,c2 = R.vars('xya1a2b1b2c1c2')\n \n V = Vector(R, 2)\n X, A, B, C = V[x,y], V[a1,a2], V[b1,b2], V[c1,c2]\n \n def line(p1, p2, p3)\n SquareMatrix.det([[1, *p1], [1, *p2], [1, *p3]])\n end\n \n def vline(p1, p2, p3)\n (p1-p2).norm2 - (p1-p3).norm2\n end\n \n l1 = vline(X, A, B)\n l2 = vline(X, B, C)\n l3 = vline(X, C, A)\n \n s = line(A, B, C)\n \n g = Groebner.basis [l1, l2, l3, s-1] #s-1 means non degeneracy\n \n g.each do |f|\n p f\n end\n #x - 1/2a1a2b1 + 1/2a1a2c1 + 1/2a1b1c2 - 1/2a1c1c2 - 1/2a1 - 1/2a2^2b2 + 1/2a2^2c2 + 1/2a2b1^2 - 1/2a2b1c1 + 1/2a2b2^2 - 1/2a2c2^2 - 1/2b1^2c2 + 1/2b1c1c2 - 1/2b2^2c2 + 1/2b2c2^2 - 1/2c1\n #y + 1/2a1^2b1 - 1/2a1^2c1 - 1/2a1b1^2 + 1/2a1c1^2 + 1/2a2^2b1 - 1/2a2^2c1 - 1/2a2b1b2 - 1/2a2b1c2 + 1/2a2b2c1 + 1/2a2c1c2 + 1/2b1^2c1 + 1/2b1b2c2 - 1/2b1c1^2 -1/2b2c1c2 - 1/2b2 - 1/2c2\n #a1b2 - a1c2 - a2b1 + a2c1 + b1c2 - b2c1 - 1\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "f8ec9ef3e9590a81a34f8493dc828b822251e9df", "size": 997, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-geometry02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc/sample-geometry02.rb.v.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-geometry02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.4857142857, "max_line_length": 188, "alphanum_fraction": 0.5536609829, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6747956855633703}} {"text": "# Example : 4.1A Chapter : 4.1 Page No: 201\n# Dimensions of the subspaces in the given space\ndim_R<-9\ndim_S<-6\nprint(\"Possible dimensions of the subspaces orthogonal to S\")\nx<-dim_R-dim_S\northogonal_dimensions<-c(0:x)\nprint(orthogonal_dimensions)\nprint(paste(\"possible dimensions of orthogonal complement subspaces to S\",dim_R-dim_S))\nprint(paste(\"The smallest matrix A in S is \",dim_S,\" by \",dim_R))\nprint(paste(\"The Null space matrix N is \",dim_R,\" by \",dim_R-dim_S))\n", "meta": {"hexsha": "1bfe0abcdda99b47d345754d89eab08ec4d579f9", "size": 476, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.a/Ex4_4.1A.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.a/Ex4_4.1A.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH4/EX4.1.a/Ex4_4.1A.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 39.6666666667, "max_line_length": 87, "alphanum_fraction": 0.7457983193, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6743518275782464}} {"text": "library(npowerPrioR)\nsource(\"data_Gaussian.r\")\n\ngs.data <- list(\n N0 = N_0,\n y0 = y_0,\n mu0 = mu_0,\n kappa0 = kappa_0,\n alpha0 = alpha_0,\n beta0 = beta_0,\n a_0 = 1\n)\n\n###\nget_l_a0_gaussian <- function(y0, n0, alpha0, beta0, m0, k0, a_0){\n nstar <- a_0 * n0\n ybar <- mean(y0)\n s <- mean( (y0-ybar)^2 )\n kappa_n <- k0 + nstar \n alpha_n <- alpha0 + nstar/2\n beta_n <- beta0 + .5 * (nstar * s + (k0 * nstar * (ybar - m0)^2 )/kappa_n ) \n ans <- lgamma(alpha_n)-lgamma(alpha0)\n ans <- ans + alpha0 * log(beta0) - alpha_n * log(beta_n)\n ans <- ans + .5 *( log(k0) - log(kappa_n) )-nstar/2 * log(2*pi)\n return(ans)\n}\n############\nl_a0 <- function(x) {\n get_l_a0_gaussian(\n y0 = gs.data$y0,\n n0 = gs.data$N0,\n alpha0 = gs.data$alpha0,\n beta0 = gs.data$beta0,\n m0 = gs.data$mu0,\n k0 = gs.data$kappa0,\n a_0 = x\n )\n}\nl_a0 <- Vectorize(l_a0)\n###\nl_a0_p <- function(x) numDeriv::grad(l_a0, x)\nl_a0_p <- Vectorize(l_a0_p)\nl_a0_pp <- function(x) numDeriv::hessian(l_a0, x)\nl_a0_pp <- Vectorize(l_a0_pp)\n\n####################\nJ <- 20\nmaxA <- 10\n\n## Importing \nuniform.ca0.estimates <- read.csv(paste(\"../../data/constant_data/Gaussian_logCA0_uniform\", \"_J=\", J, \".csv\", sep = \"\"))\nadaptive.ca0.estimates <- read.csv(paste(\"../../data/constant_data/Gaussian_logCA0_adaptive\", \"_J=\", J, \".csv\", sep = \"\"))\nadaptive.ca0.estimates.derivOnly <- read.csv(paste(\"../../data/constant_data/Gaussian_logCA0_adaptive_derivOnly\", \"_J=\", J, \".csv\", sep = \"\"))\n\n####\n## Plotting the curves l(a_0) and derivatives\n\ncurve(l_a0_p, 0, 10, lwd = 3, lty = 2, col = 2, \n # ylim = c(-30, 60),\n ylab = \"\", xlab = expression(a[0]), cex.lab = 3, cex.axis = 2.5)\nabline(h = 0, lwd = 2 , lty = 3)\ncurve(l_a0, 0, 10, lwd = 3, add = TRUE)\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$lc_a0, cex = 1.5, pch = 16)\ncurve(l_a0_pp, 0, 10, lwd = 3, col = 3, add = TRUE)\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$second_deriv_lc, cex = 1.5, col = 3, pch = 16)\nlegend(x = \"bottomright\", legend = c(\"l(a_0)\", \"l'(a_0)\", \"l''(a_0)\"),\n col = 1:3, lwd = 2, bty = 'n', cex = 1.5)\npoints(adaptive.ca0.estimates$a0, adaptive.ca0.estimates$deriv_lc,\n pch = 16, cex = 1.5, col = 2)\n\n\n#######\n\nfit.gam.uniform <- mgcv::gam(lc_a0 ~ s(a0, k = J + 1), data = uniform.ca0.estimates)\nfit.gam.adaptive <- mgcv::gam(lc_a0 ~ s(a0, k = J + 1), data = adaptive.ca0.estimates)\nderiv.gam.fit <- mgcv::gam(deriv_lc ~ s(a0, k = J + 1), data = adaptive.ca0.estimates.derivOnly)\n\n########################\nK <- 20000\npred_a0s <- seq(0, maxA, length.out = K)\n\npreds.gam.uniform <- get_band(fit.gam.uniform, xpred = pred_a0s)\npreds.gam.adaptive <- get_band(fit.gam.adaptive, xpred = pred_a0s)\nderiv.preds <- cumsum(predict(deriv.gam.fit, newdata = data.frame(a0 = pred_a0s))) * diff(pred_a0s)[1]\n\ntrue.lca0s <- l_a0(pred_a0s)\ngam.preds.list <- list(\n uniform = data.frame (a0 = pred_a0s, lca0 = preds.gam.uniform$mean, lwr = preds.gam.uniform$lwr,\n upr = preds.gam.uniform$upr, approximating_function = \"gam\", design = \"uniform\"),\n adaptive = data.frame (a0 = pred_a0s, lca0 = preds.gam.adaptive$mean, lwr = preds.gam.adaptive$lwr,\n upr = preds.gam.adaptive$upr, approximating_function = \"gam\", design = \"adaptive\"),\n derivative = data.frame (a0 = pred_a0s, lca0 = deriv.preds, lwr = NA, upr = NA,\n approximating_function = \"numerical\", design = \"adaptive_numerical\")\n)\n\n\nl_a0(.15)\npredict(fit.gam.uniform, newdata = data.frame(a0 = .15))\npredict(fit.gam.adaptive, newdata = data.frame(a0 = .15))\n\nl_a0(.75)\npredict(fit.gam.uniform, newdata = data.frame(a0 = .75))\npredict(fit.gam.adaptive, newdata = data.frame(a0 = .75))\n\nl_a0(5)\npredict(fit.gam.uniform, newdata = data.frame(a0 = 5))\npredict(fit.gam.adaptive, newdata = data.frame(a0 = 5)) \n\n## RMSE\nlapply(gam.preds.list, function(pred) sqrt(mean( (pred$lca0 - true.lca0s)^2 )) )\n## MAD\nlapply(gam.preds.list, function(pred) mean( abs(pred$lca0 - true.lca0s) )) \n\n## RMSE, a0 < 1\nlapply(gam.preds.list, function(pred) sqrt(mean( (pred[pred$a0 < 1, ]$lca0 - true.lca0s[pred_a0s < 1])^2 )) )\n## MAD, a0 < 1\nlapply(gam.preds.list, function(pred) mean( abs(pred[pred$a0 < 1, ]$lca0 - true.lca0s[pred_a0s < 1]) )) \n\nforplot_ca0 <- do.call(rbind, gam.preds.list)\n\nwrite.csv(forplot_ca0,\n file = paste(\"../data/constant_data/fitted_predictions_lca0_Gaussian\", \"_J=\", J, \".csv\", sep = \"\"),\n row.names = FALSE)\n\nlibrary(ggplot2)\n\np0 <- ggplot(data = forplot_ca0, aes(x = a0, y = lca0, colour = design, fill = design)) +\n geom_line() +\n geom_ribbon(aes(min = lwr, max = upr), alpha = .4) +\n stat_function(fun = l_a0, linetype = \"dashed\", size = 1.2, colour = \"black\") + \n geom_point(data = adaptive.ca0.estimates,\n mapping = aes(x = a0, y = lc_a0), colour = \"black\", alpha = .4, size = 5, inherit.aes = FALSE) + \n scale_x_continuous(expression(a[0])) +\n scale_y_continuous(expression(log(c(a[0])))) +\n theme_bw(base_size = 16)\np0 \n\np0b <- ggplot(data = subset(forplot_ca0, a0 < 1 & design != \"uniform\"), aes(x = a0, y = lca0, colour = design, fill = design)) +\n geom_line() +\n geom_ribbon(aes(min = lwr, max = upr), alpha = .4) +\n stat_function(fun = l_a0, linetype = \"dashed\", size = 1.2, colour = \"black\") +\n geom_point(data = subset(adaptive.ca0.estimates, a0 < 1),\n mapping = aes(x = a0, y = lc_a0), colour = \"black\", alpha = .4, size = 5, inherit.aes = FALSE) + \n scale_x_continuous(expression(a[0]), limits = c(0, 1)) +\n scale_y_continuous(expression(log(c(a[0])))) +\n theme_bw(base_size = 16)\np0b\n\nplot(pred_a0s, (true.lca0s-preds.gam.adaptive$mean))\nplot(pred_a0s, (true.lca0s-deriv.preds))\n\nggsave(p0, filename = paste(\"../../figures/estimates_log_ca0_Gaussian_J=\", J, \".pdf\", sep = \"\"), dpi = 300)\n\nggsave(p0b, filename = paste(\"../../figures/estimates_log_ca0_Gaussian_restricted_J=\", J, \".pdf\", sep = \"\"), dpi = 300)", "meta": {"hexsha": "a552af99dc6380f6dc5f516a16bd875d227dd311", "size": 5919, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Gaussian/simple_Gaussian_plot_c(a_0).r", "max_stars_repo_name": "maxbiostat/propriety_power_priors", "max_stars_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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/Gaussian/simple_Gaussian_plot_c(a_0).r", "max_issues_repo_name": "maxbiostat/propriety_power_priors", "max_issues_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-29T19:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T15:58:08.000Z", "max_forks_repo_path": "code/Gaussian/simple_Gaussian_plot_c(a_0).r", "max_forks_repo_name": "maxbiostat/propriety_power_priors", "max_forks_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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.4350649351, "max_line_length": 142, "alphanum_fraction": 0.6254434871, "num_tokens": 2137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6743518016722728}} {"text": "knapsack<- function(Value, Weight, Objects, Capacity){\n Fraction = rep(0, length(Value))\n Cost = Value/Weight\n #print(Cost)\n W = Weight[order(Cost, decreasing = TRUE)]\n Obs = Objects[order(Cost, decreasing = TRUE)]\n Val = Value[order(Cost, decreasing = TRUE)]\n #print(W)\n RemainCap = Capacity\n i = 1\n n = length(Cost)\n if (W[1] <= Capacity){\n Fits <- TRUE\n }\n else{\n Fits <- FALSE\n }\n while (Fits && i <= n ){\n Fraction[i] <- 1\n RemainCap <- RemainCap - W[i]\n i <- i+1\n #print(RemainCap)\n if (W[i] <= RemainCap){\n Fits <- TRUE\n }\n else{\n Fits <- FALSE\n }\n }\n #print(RemainCap)\n if (i <= n){\n Fraction[i] <- RemainCap/W[i]\n }\n names(Fraction) = Obs\n Quantity_to_take = W*Fraction\n Total_Value = sum(Val*Fraction)\n print(\"Fraction of available quantity to take:\")\n print(round(Fraction, 3))\n print(\"KG of each to take:\")\n print(Quantity_to_take)\n print(\"Total value of tasty meats:\")\n print(Total_Value)\n}\n", "meta": {"hexsha": "7fa8871e5357767310b1f76e263bfc7725fad48f", "size": 975, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Knapsack-problem-Continuous/R/knapsack-problem-continuous.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/Knapsack-problem-Continuous/R/knapsack-problem-continuous.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/Knapsack-problem-Continuous/R/knapsack-problem-continuous.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": 22.1590909091, "max_line_length": 54, "alphanum_fraction": 0.6030769231, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6742742810013174}} {"text": "class_update_train_ndp <- function(n, K , alpha, name_new, uniq_clabs, clabs,\r\n y, x, x_cat_shell, x_num_shell,\r\n cat_idx, num_idx,\r\n beta_shell, psi_shell,\r\n beta_new, psi_new, cat_new, num_new){\r\n\r\n # shells\r\n c_shell <- matrix(NA, nrow = n, ncol = K + 1)\r\n colnames(c_shell) <- c(uniq_clabs, name_new)\r\n\r\n ## prior for existing cluster\r\n pr_exist <- matrix(NA, nrow = n, ncol = K)\r\n colnames(pr_exist) <- uniq_clabs\r\n\r\n pr_new <- numeric(length = n)\r\n\r\n clabs <- factor(clabs, levels = uniq_clabs)\r\n for(j in 1:n){\r\n n_min_j <- table(clabs[-j] )\r\n pr_exist[j,] <- log( (alpha*(n_min_j==0) + n_min_j)/(j + alpha - 1) )\r\n pr_new[j] <- log( (alpha) / (j + alpha - 1) )\r\n }\r\n\r\n\r\n ## existing clusters\r\n for(k in uniq_clabs){\r\n\r\n lk_exist <- numeric(length = n)\r\n\r\n for(p in cat_idx){\r\n lk_exist <- lk_exist + dbinom(x[ ,p], 1, x_cat_shell[[p]][1,k], T)\r\n }\r\n\r\n for(p in num_idx){\r\n lk_exist <- lk_exist + dnorm(x[, p],\r\n x_num_shell[[p]][[1]][,k],\r\n sqrt(x_num_shell[[p]][[2]][,k]), T )\r\n }\r\n\r\n lk_exist <- lk_exist + dnorm(x = y,\r\n mean = x %*% beta_shell[,k, drop=F],\r\n sd = sqrt(psi_shell[,k]), T)\r\n\r\n c_shell[,k] <- lk_exist + pr_exist[,k]\r\n }\r\n\r\n\r\n ## New clusters\r\n lk_new <- numeric(length = n)\r\n\r\n for(p in cat_idx){\r\n lk_new <- lk_new + dbinom(x[ ,p], 1, cat_new[p], T)\r\n }\r\n\r\n for(p in num_idx){\r\n lk_new <- lk_new + dnorm(x[, p], num_new[1,p], sqrt(num_new[2,p]), T)\r\n }\r\n\r\n lk_new <- lk_new + dnorm(x = y,\r\n mean = x %*% t(beta_new),\r\n sd = sqrt(psi_new), T)\r\n\r\n c_shell[,name_new] <- lk_new + pr_new\r\n\r\n weights <- t(apply(c_shell, 1, function(x) exp(x)/sum(exp(x)) ))\r\n\r\n return(weights)\r\n}\r\n\r\nclass_update_test_ndp <- function(n, K , alpha, name_new, uniq_clabs, clabs, x,\r\n x_cat_shell, x_num_shell,\r\n cat_idx, num_idx,\r\n cat_new, num_new){\r\n\r\n # shells\r\n c_shell <- matrix(NA, nrow = n, ncol = K + 1)\r\n colnames(c_shell) <- c(uniq_clabs, name_new)\r\n\r\n ## prior for existing cluster\r\n clabs <- factor(clabs, levels = uniq_clabs)\r\n pr_exist <- log(table(clabs)/(length(clabs)+alpha))\r\n\r\n ## existing clusters\r\n for(k in uniq_clabs){\r\n\r\n lk_exist <- numeric(length = n)\r\n\r\n for(p in cat_idx){\r\n lk_exist <- lk_exist + dbinom(x[ ,p], 1, x_cat_shell[[p]][1,k], T)\r\n }\r\n\r\n for(p in num_idx){\r\n\r\n lk_exist <- lk_exist + dnorm(x[, p],\r\n x_num_shell[[p]][[1]][,k],\r\n sqrt(x_num_shell[[p]][[2]][,k]), T )\r\n }\r\n\r\n c_shell[,k] <- lk_exist + pr_exist[k]\r\n }\r\n\r\n\r\n ## New clusters\r\n lk_new <- numeric(length = n)\r\n\r\n for(p in cat_idx){\r\n lk_new <- lk_new + dbinom(x[ ,p], 1, cat_new[p], T)\r\n }\r\n\r\n for(p in num_idx){\r\n lk_new <- lk_new + dnorm(x[, p], num_new[1,p], sqrt(num_new[2,p]), T)\r\n }\r\n\r\n c_shell[,name_new] <- lk_new + log(alpha/(length(clabs)+alpha))\r\n\r\n weights <- t(apply(c_shell, 1, function(x) exp(x)/sum(exp(x)) ))\r\n\r\n return(weights)\r\n}\r\n\r\npost_pred_draw_train_ndp <- function(n, x, pc, beta_shell, psi_shell){\r\n\r\n y_pp <- numeric(length = n)\r\n\r\n clabs <- unique(pc)\r\n\r\n for( k in clabs ){\r\n y_pp[pc==k] <- rnorm(n = sum(pc==k),\r\n mean = x[pc==k,, drop=F] %*% beta_shell[,k,drop=F],\r\n sd = sqrt(psi_shell[1,k]) )\r\n }\r\n\r\n return(y_pp)\r\n}\r\n\r\n\r\npost_pred_draw_test_ndp <- function(n, x, pc, beta_shell, psi_shell,\r\n name_new, beta_new, psi_new){\r\n\r\n y_pp <- numeric(length = n)\r\n\r\n clabs <- unique(pc)\r\n\r\n for( k in setdiff(clabs, name_new) ){\r\n y_pp[pc==k] <- rnorm(n = sum(pc==k),\r\n mean = x[pc==k,, drop=F] %*% beta_shell[,k,drop=F],\r\n sd = sqrt(psi_shell[1,k]) )\r\n }\r\n\r\n y_pp[pc==name_new] <- rnorm(n = sum(pc==name_new),\r\n mean = x[pc==name_new,, drop=F] %*% t(beta_new),\r\n sd = sqrt(psi_new) )\r\n\r\n return(y_pp)\r\n}\r\n", "meta": {"hexsha": "dd63b5535c20f18103b6c72ec4a6657b829760ee", "size": 4276, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helper_functions_ndp.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/helper_functions_ndp.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/helper_functions_ndp.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": 27.4102564103, "max_line_length": 80, "alphanum_fraction": 0.490645463, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6739830387845762}} {"text": "a <- c(0.4,0.3,0.2,0.1)\nb <- c(0.1,0.4,0.3,0.2)\nc <- c(0.1,0.2,0.4,0.3)\nd <- c(0.1,0.2,0.3,0.4)\n\na <- c(0.7,0.1,0.1,0.1)\nb <- c(0.1,0.7,0.1,0.1)\nc <- c(0.1,0.1,0.7,0.1)\nd <- c(0.1,0.1,0.1,0.7)\n\na <- c(0.4,0.1,0.2,0.3)\nb <- c(0.3,0.4,0.1,0.2)\nc <- c(0.2,0.3,0.4,0.1)\nd <- c(0.1,0.2,0.3,0.4)\n\na <- c(0.4,0.3,0.2,0.1)\nb <- c(0.25,0.25,0.25,0.25)\nc <- c(0.25,0.25,0.25,0.25)\nd <- c(0.25,0.25,0.25,0.25)\n\na <- c(0.7,0.1,0.1,0.1)\nb <- c(0.1,0.6,0.2,0.1)\nc <- c(0.1,0.1,0.6,0.2)\nd <- c(0.1,0.1,0.2,0.6)\n\na <- c(0.4,0.3,0.2,0.1)\nb <- c(0.3,0.4,0.2,0.1)\nc <- c(0.2,0.3,0.4,0.1)\nd <- c(0.1,0.2,0.3,0.4)\n\ns <- c(0.25,0.25,0.25,0.25)\ns <- c(0.1,0.2,0.3,0.4)\ns <- t(as.matrix(s))\nt <- rbind(a,b,c,d)\nresult = s\nfor(i in 1:100){\n s = s%*%t\n result = rbind(result,s)\n}\nn = 1:101\nplot(result[,1]~n,type = 'l',ylim = c(0,0.4))\nlines(result[,2]~n,col = 'red')\nlines(result[,3]~n,col = 'green')\nlines(result[,4]~n,col = 'blue')\n\nresult[101,]\n", "meta": {"hexsha": "01fde208f4cb227a299be4c3aab73ae82536bf57", "size": 937, "ext": "r", "lang": "R", "max_stars_repo_path": "plot/markov.r", "max_stars_repo_name": "yufree/democode", "max_stars_repo_head_hexsha": "f09a89437bfeb4b56d245a568bedb39e48dbe7b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-11-08T11:11:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T13:36:31.000Z", "max_issues_repo_path": "plot/markov.r", "max_issues_repo_name": "yufree/democode", "max_issues_repo_head_hexsha": "f09a89437bfeb4b56d245a568bedb39e48dbe7b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-09-30T20:16:26.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-23T14:52:34.000Z", "max_forks_repo_path": "plot/markov.r", "max_forks_repo_name": "yufree/democode", "max_forks_repo_head_hexsha": "f09a89437bfeb4b56d245a568bedb39e48dbe7b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-09-30T15:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T13:36:30.000Z", "avg_line_length": 19.9361702128, "max_line_length": 45, "alphanum_fraction": 0.4631803629, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6739830227589672}} {"text": "## 2. Quantitative and Qualitative Variables ##\n\nlibrary(readr)\nwnba <- read_csv(\"wnba.csv\")\n\n# variables <- c(\"Three_PA\", \"Age\", \"AST\", \"Birth_Place\", \"Birthdate\", \"BMI\", \"College\", \n# \"DREB\", \"Experience\", \"FGA\", \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \"Games_Played\", \n# \"Height\", \"MIN\", \"Name\", \"OREB\", \"Pos\", \"PTS\", \"REB\", \"Team\", \"Weight\")\nqualitative_vars <- c(\"Birth_Place\", \"College\", \"Name\", \"Pos\", \"Team\")\n\nquantitative_vars <- c(\"Three_PA\", \"Age\", \"AST\", \"Birthdate\", \"BMI\", \"DREB\", \"Experience\", \n \"FGA\", \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \"Games_Played\", \"Height\", \n \"MIN\", \"OREB\", \"PTS\", \"REB\", \"Weight\")\n\nqualitative_vars <- sort(qualitative_vars)\nquantitative_vars <- sort(quantitative_vars)\n\n## 4. The Nominal Scale ##\n\n# variables <- c(\"Three_PA\", \"Age\", \"AST\", \"Birth_Place\", \"Birthdate\", \n# \"BMI\", \"College\", \"DREB\", \"Experience\", \"FGA\", \n# \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \"Games_Played\", \n# \"Height\", \"MIN\", \"Name\", \"OREB\", \"Pos\", \n# \"PTS\", \"REB\", \"Team\", \"Height_labels\")\nnominal_scale <- sort(c(\"Name\", \"Team\", \"Pos\", \"Birth_Place\", \"College\"))\n\n## 5. The Ordinal Scale ##\n\nquestion_1 <- TRUE\nquestion_2 <- FALSE\nquestion_3 <- FALSE\nquestion_4 <- TRUE\nquestion_5 <- FALSE\nquestion_6 <- FALSE\n\n## 7. The Difference Between Ratio and Interval Scales ##\n\n# quantitative_vars <- c(\"Three_PA\", \"Age\", \"AST\", \"Birthdate\", \"BMI\", \"DREB\", \"Experience\", \n# \"FGA\", \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \"Games_Played\", \"Height\", \n# \"MIN\", \"OREB\", \"PTS\", \"REB\", \"Weight\", \"Weight_deviation\")\ninterval_scale <- sort(c(\"Birthdate\", \"Weight_deviation\"))\nratio_scale <- sort(c(\"Three_PA\", \"Age\", \"AST\", \"BMI\", \"DREB\", \"Experience\", \"FGA\", \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \n \"Games_Played\", \"Height\", \"MIN\", \"OREB\", \"PTS\", \"REB\", \"Weight\"))\n\n## 9. Discrete and Continuous Variables ##\n\n# ratio_scale <- sort(c(\"Three_PA\", \"Age\", \"AST\", \"BMI\", \"DREB\", \"Experience\", \"FGA\", \"FGM\", \"FT_perc\", \"FTA\", \"FTM\", \n# \"Games_Played\", \"Height\", \"MIN\", \"OREB\", \"PTS\", \"REB\", \"Weight\"))\ncontinuous <- sort(c(\"Age\", \"BMI\", \"Experience\", \"FT_perc\", \"Height\", \"MIN\", \"Weight\"))\ndiscrete <- sort(c(\"Three_PA\", \"AST\", \"DREB\", \"FGA\", \"FGM\", \"FTA\", \"FTM\", \"Games_Played\", \"OREB\", \"PTS\", \"REB\"))\n\n## 10. Real Limits ##\n\n# bmi <- list(\n# \"21.201\" = c(, ),\n# \"21.329\" = c(, ),\n# \"23.875\" = c(, ),\n# \"24.543\" = c(, ),\n# \"25.469\" = c(, ))\nbmi <- list(\n \"21.201\" = c(21.2005, 21.2015),\n \"21.329\" = c(21.3285, 21.3295),\n \"23.875\" = c(23.8745, 23.8755),\n \"24.543\" = c(24.5425, 24.5435),\n \"25.469\" = c(25.4685, 25.4695))\n\nbmi", "meta": {"hexsha": "9e98fe5f9b3ed92e38364ab40d5cf0ca7a9f0858", "size": 2711, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/3. Variables in Statistics.r", "max_stars_repo_name": "MyArist/Dataquest", "max_stars_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-27T12:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T04:39:33.000Z", "max_issues_repo_path": "Data Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/3. Variables in Statistics.r", "max_issues_repo_name": "myarist/Dataquest", "max_issues_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "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 Analyst in R/Step 5 - Probability and Statistics/1. Statistics Fundamentals in R/3. Variables in Statistics.r", "max_forks_repo_name": "myarist/Dataquest", "max_forks_repo_head_hexsha": "d0ee0a2a5e9d1f69f09bf0f6c32f382b6fa46b18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2021-03-30T06:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T03:55:02.000Z", "avg_line_length": 40.4626865672, "max_line_length": 118, "alphanum_fraction": 0.5396532645, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.673946763242916}} {"text": "## utilities for manipulating positions\n\nradec2hms <- function(...) {\n radec <- unlist(list(...))\n dec <- radec[2]\n ra <- radec[1]/15\n ra.h <- trunc(ra)\n ra <- 60*(ra-ra.h)\n ra.m <- trunc(ra)\n ra.s <- 60*(ra-ra.m)\n ds <- sign(dec)\n dec.d <- trunc(dec)\n dec <- 60*abs(dec-dec.d)\n dec.m <- trunc(dec)\n dec.s <- 60*(dec-dec.m)\n cat(paste(ra.h, ra.m, format(ra.s, digits=2),sep=\":\"))\n if (ds >= 0) cat(\" +\") else cat(\" -\")\n cat(paste(dec.d, dec.m, format(dec.s, digits=1), sep=\":\"), \"\\n\")\n}\n\nhms2radec <- function(...) {\n radec <- unlist(list(...))\n nr <- length(radec)/2\n radec <- matrix(radec,nr,2)\n ra <- radec[,1]\n dec <- radec[,2]\n ra.h <- trunc(ra)\n ra <- 100*(ra-ra.h)\n ra.m <- trunc(ra)\n ra.s <- 100*(ra-ra.m)\n ra.d <- 15*(ra.h + ra.m/60 + ra.s/3600)\n dec.sign <- sign(dec)\n dec <- abs(dec)\n dec.d <- trunc(dec)\n dec <- 100*abs(dec-dec.d)\n dec.m <- trunc(dec)\n dec.s <- 100*(dec-dec.m)\n dec.d <- dec.sign*(dec.d+dec.m/60+dec.s/3600)\n list(ra=ra.d, dec=dec.d)\n}\n\n\nlb2radec <- function(...) {\n rotm <- matrix(c(-.054876, -.873437, -.483835,\n .494109, -0.444830, .746982,\n -0.867666, -0.198076, 0.455984), 3, 3)\n lb <- unlist(list(...))\n nr <- length(lb)/2\n lb <- matrix(lb, nr, 2)\n l <- pi*lb[,1]/180\n b <- pi*lb[,2]/180\n x.lb <- rbind(cos(b)*cos(l), cos(b)*sin(l), sin(b))\n x.ad <- rotm %*% x.lb\n a <- atan2(x.ad[2,], x.ad[1,])\n a[a<0] <- 2*pi+a[a<0]\n d <- asin(x.ad[3,])\n ad <- data.frame(ra=a*180/pi, dec=d*180/pi)\n ad\n}\n\nradec2lb <- function(...) {\n rotm <- t(matrix(c(-.054876, -.873437, -.483835,\n .494109, -0.444830, .746982,\n -0.867666, -0.198076, 0.455984), 3, 3))\n radec <- unlist(list(...))\n nr <- length(radec)/2\n radec <- matrix(radec,nr,2)\n ra <- pi*radec[,1]/180\n dec <- pi*radec[,2]/180\n x.ad <- rbind(cos(ra)*cos(dec),sin(ra)*cos(dec),sin(dec))\n x.lb <- rotm %*% x.ad\n l <- atan2(x.lb[2,], x.lb[1,])\n l[l<0] <- 2*pi+l[l<0]\n b <- asin(x.lb[3,])\n lb <- data.frame(l=180*l/pi, b=180*b/pi)\n lb\n}\n\n", "meta": {"hexsha": "348de3bbf4d2f8dec6523ae91ab7caf447cb6ef5", "size": 2025, "ext": "r", "lang": "R", "max_stars_repo_path": "spmutils/R/posutils.r", "max_stars_repo_name": "mlpeck/spmutils", "max_stars_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "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": "spmutils/R/posutils.r", "max_issues_repo_name": "mlpeck/spmutils", "max_issues_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "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": "spmutils/R/posutils.r", "max_forks_repo_name": "mlpeck/spmutils", "max_forks_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "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": 25.6329113924, "max_line_length": 66, "alphanum_fraction": 0.5150617284, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6737193390756706}} {"text": "\nresult = 0\nb = 1\nfor i in range(0,n):\n temp = result\n result = b\n b = temp + b\n", "meta": {"hexsha": "f84cba1663399976bc42b27755681f6a35f42851", "size": 89, "ext": "r", "lang": "R", "max_stars_repo_path": "test/data/phenology/crop2ml/algo/r/Fibonacci.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": "test/data/phenology/crop2ml/algo/r/Fibonacci.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": "test/data/phenology/crop2ml/algo/r/Fibonacci.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "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": 11.125, "max_line_length": 20, "alphanum_fraction": 0.5056179775, "num_tokens": 36, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6735504671600626}} {"text": "#' f_bbgd\n#'\n#' The descent algorithm with Barzilar-borwein stepsize\n#'\n#' @param v_y vector of y\n#' @param v_x vector of x\n#' @param v_k0 vector of internal knots for covariates\n#' @param v_m vector of orders for covariates\n#'\n#' @param init initialization for $\\beta$\n#' @param v_smooth vector of smoothing parameters\n#' @param maxit maximum number of iterations\n#' @param eps stopping critria threshhold\n#' @param eta stopping criteria for gradient size\n#' @param trace indicator whether to plot trace\n#'\n#'\n#' @return the estimated $\\beta$\n#'\nf_bbgd <- function(v_y, v_x, v_k0, v_m, init = NULL,\n v_smooth = rep(1, 3),\n maxit = 1e4, eps = 1e-3, eta = NULL, trace = NULL) {\n\n#-------------------------------------------------------\n##### set up #####\n#-------------------------------------------------------\n function_call <- match.call()\n x_ord <- order(v_x)\n v_x <- v_x[x_ord]\n v_y <- v_y[x_ord]\n s_center <- mean(v_x)\n s_sd <- sd(v_x)\n v_x <- c(scale(v_x))\n iter <- 0L\n converge <- F\n #Define dimensions\n k1 <- v_k0[1]; k2 <- v_k0[2]; m1 <- v_m[1]; m2 <- v_m[2]\n #Require\n m_n1 <- f_n1(v_x, k1, m1)\n m_g1 <- f_g1(k2, m2)\n m_g2 <- f_g2(k2, m2)\n m_sigmatau <- f_sigmatau(k2 + m2)\n m_sigma <- f_sigma(k1 + m1, k2 + m2)\n m_s <- f_mats(k1 + m1, k2 + m2, v_smooth)\n n_m2 <- rep(0, k2 + m2); n_m2[k2 + m2] <- 1\n\n #Precalculate\n m_h1 <- f_h1(m_n1, m_g1, m_g2, m_sigmatau, n_m2)\n\n #Initialization\n if (is.null(init)) {\n init <- f_init(v_y, v_x, m_sigma, m_n1, v_k0, v_m, m_s)\n }\n til_beta0 <- init\n v_beta0 <- og_beta(til_beta0, k1 + m1, k2 + m2)\n v_grad0 <- 0\n\n #Calculate H2 (most time consuming)\n v_taustar <- f_tausearch(v_y, m_n1, til_beta0, m_sigma, k2, m2)\n m_ntau <- f_ntau(v_taustar, k2, m2)\n m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau)\n\n ##Loss\n s_loss <- f_loss(v_beta0, til_beta0, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n\n ##trace\n if (!is.null(trace)) {\n con_quan <- list(\n x = v_x,\n y = v_y,\n center = s_center,\n sd = s_sd,\n v_k0 = v_k0,\n v_m = v_m,\n m_sigma = m_sigma,\n n1 = m_n1,\n til_beta = til_beta0,\n iter = iter,\n loss = s_loss,\n alpha = 0,\n bet = 0)\n cq_plot(trace, con_quan)\n }\n\n #Standard gradient updates\n v_deriv <- f_lossderiv(til_beta0, v_k0 + v_m, m_sigma, m_h1, m_h2)\n v_grad1 <- f_grad(v_beta0, v_deriv, m_s)\n #Calculate new coefficients\n s_step <- 0.25\n v_beta1 <- v_beta0 - s_step * v_grad1\n til_beta1 <- tilde_beta(v_beta1, k1 + m1, k2 + m2)\n new_loss <- f_loss(v_beta1, til_beta1, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n\n #Repeat\n while (maxit > iter) {\n iter <- iter + 1\n\n #Calculate difference\n v_delta <- v_beta1 - v_beta0\n v_gdiff <- v_grad1 - v_grad0\n\n #bb stepsize\n s_delgrad <- crossprod(v_delta, v_gdiff)\n step1 <- crossprod(v_delta) / s_delgrad\n step2 <- s_delgrad / crossprod(v_gdiff)\n s_step <- min(step1, step2, 100)\n if (s_step < 0) s_step <- 0.25\n\n #update v_beta0, til_beta0, v_grad0, s_loss\n v_beta0 <- v_beta1\n til_beta0 <- til_beta1\n v_grad0 <- v_grad1\n s_loss <- new_loss\n\n #Update H2 (most time consuming)\n#ptm <- proc.time()# Start the clock!\n v_taustar <- f_tausearch(v_y, m_n1, til_beta1, m_sigma, k2, m2)\n#print(proc.time() - ptm)# Stop the clock\n m_ntau <- f_ntau(v_taustar, k2, m2)\n m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau)\n\n #Calculate gradient\n v_deriv <- f_lossderiv(til_beta1, v_k0 + v_m, m_sigma, m_h1, m_h2)\n v_grad1 <- f_grad(v_beta1, v_deriv, m_s)\n\n #Update v_beta1, til_beta1, new_loss\n v_beta1 <- v_beta0 - s_step * v_grad1\n til_beta1 <- tilde_beta(v_beta1, k1 + m1, k2 + m2)\n new_loss <- f_loss(v_beta1, til_beta1, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n\n #Check stop criterion\n if (is.null(eta)) {\n converge <- (abs(new_loss - s_loss) <= eps * abs(s_loss))\n } else {\n converge <- (norm_2(v_grad1) / norm_2(v_beta0) <= eta)\n }\n\n ##trace\n if (!is.null(trace)) {\n con_quan$til_beta <- til_beta1\n con_quan$loss <- new_loss\n con_quan$iter <- iter\n cq_plot(trace, con_quan)\n }\n\n #If gradient size criteria\n if (converge) break\n\n }\n\n#-------------------------------------------------------\n##### Output #####\n#-------------------------------------------------------\n\n out <- list(\n beta = v_beta1,\n til_beta = til_beta1,\n gradient = v_grad1,\n converge = converge,\n stepsize = s_step,\n grad_size = norm_2(v_grad1),\n iter = iter,\n loss = new_loss,\n tau = v_taustar,\n x = v_x,\n y = v_y,\n center = s_center,\n sd = s_sd,\n v_k0 = v_k0,\n v_m = v_m,\n n1 = m_n1,\n m_sigma = m_sigma,\n mat_s = m_s,\n alpha = 0,\n bet = 0,\n call = function_call)\n\n return(out)\n}", "meta": {"hexsha": "7932471b1fc7d0cd377e8c81310f88041f516094", "size": 5354, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bb-gd.r", "max_stars_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_stars_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/bb-gd.r", "max_issues_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_issues_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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/bb-gd.r", "max_forks_repo_name": "ZhuolinSong/-Quantile-sheet-estimator-with-shape-constraints", "max_forks_repo_head_hexsha": "f871f5ac7b1d7a6add799f023b23d10ce899d5d6", "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.9106145251, "max_line_length": 88, "alphanum_fraction": 0.5197982817, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6735203277376904}} {"text": "##### Chapter 3: Classification using Nearest Neighbors --------------------\npacman::p_load(\"class\", \"gmodels\", \"tidyverse\")\n## Example: Classifying Cancer Samples ----\n## Step 2: Exploring and preparing the data ---- \n\n# import the CSV file\nwbcd <- read.csv(\".//Chapter03//wisc_bc_data.csv\", stringsAsFactors = FALSE)\n\n# examine the structure of the wbcd data frame\nwbcd \n# drop the id feature\nwbcd <- wbcd[-1]\n\n# table of diagnosis\ntable(wbcd$diagnosis)\n\n# recode diagnosis as a factor\nwbcd$diagnosis <- factor(wbcd$diagnosis, levels = c(\"B\", \"M\"),\n labels = c(\"Benign\", \"Malignant\"))\n\n# table or proportions with more informative labels\nround(prop.table(table(wbcd$diagnosis)) * 100, digits = 1)\n\n# summarize three numeric features\nsummary(wbcd[c(\"radius_mean\", \"area_mean\", \"smoothness_mean\")])\n\n# create normalization function\nnormalize <- function(x) {\n return ((x - min(x)) / (max(x) - min(x)))\n}\n\n# test normalization function - result should be identical\nnormalize(c(1, 2, 3, 4, 5))\nnormalize(c(10, 20, 30, 40, 50))\n\n# normalize the wbcd data\nwbcd_n <- as.data.frame(lapply(wbcd[2:31], normalize))\n\n# confirm that normalization worked\nsummary(wbcd_n$area_mean)\n\n# create training and test data\nwbcd_train <- wbcd_n[1:469, ]\nwbcd_test <- wbcd_n[470:569, ]\n\n# create labels for training and test data\n\nwbcd_train_labels <- wbcd[1:469, 1]\nwbcd_test_labels <- wbcd[470:569, 1]\n\n## Step 3: Training a model on the data ----\n\n# load the \"class\" library\nlibrary(class)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\n cl = wbcd_train_labels, k = 21)\n\n## Step 4: Evaluating model performance ----\n\n# load the \"gmodels\" library\nlibrary(gmodels)\n\n# Create the cross tabulation of predicted vs. actual\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\n prop.chisq = FALSE)\n\n## Step 5: Improving model performance ----\n\n# use the scale() function to z-score standardize a data frame\nwbcd_z <- as.data.frame(scale(wbcd[-1]))\n\n# confirm that the transformation was applied correctly\nsummary(wbcd_z$area_mean)\n\n# create training and test datasets\nwbcd_train <- wbcd_z[1:469, ]\nwbcd_test <- wbcd_z[470:569, ]\n\n# re-classify test cases\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test,\n cl = wbcd_train_labels, k = 21)\n\n# Create the cross tabulation of predicted vs. actual\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred,\n prop.chisq = FALSE)\n\n# try several different values of k\nwbcd_train <- wbcd_n[1:469, ]\nwbcd_test <- wbcd_n[470:569, ]\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=1)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=5)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=11)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=15)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=21)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\nwbcd_test_pred <- knn(train = wbcd_train, test = wbcd_test, cl = wbcd_train_labels, k=27)\nCrossTable(x = wbcd_test_labels, y = wbcd_test_pred, prop.chisq=FALSE)\n\n\n\n\n# 타이디문법으로 재구성\ninstall.packages(\"modeldata\")\npacman::p_load(\"dplyr\", \"class\", \"gmodels\", \"tidyverse\", \"ggplot2\", \"rsample\", \"recipes\", \"caret\", \"modeldata\") # 없는 패키지는 자동으로 다운로드받아줌\nlibrary(modeldata)\n\noptions(scipen = 999)\nggplot2::theme_set(ggplot2::theme_light())\n\n\n\".//Chapter03//wisc_bc_data.csv\" %>% \n read.csv(stringsAsFactors = FALSE) %>% \n as.tibble %>% \n mutate_if(is.ordered, factor, ordered = FALSE) -> wbcd\n\nwbcd %>% # 양성과 음성 수 보기\n select(-id) %>% \n glimpse() %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"M\", \"Malignant\")) %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"B\", \"Benign\")) %>% \n count(diagnosis)\n\nwbcd %>% # 양성과 음성 비율 보기\n select(-id) %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"M\", \"Malignant\")) %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"B\", \"Benign\")) %>% \n count(diagnosis) %>% \n mutate(prop=format(prop.table(n)*100, digits=3))\n\nlibrary(tidymodels) # 머신러닝용 타이디패키지\nwbcd %>% # 훈련데이터, 테스트데이터 생성 (7:3 비율로 나누었다!)\n select(-id) %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"M\", \"Malignant\")) %>% \n mutate(diagnosis = str_replace_all(diagnosis, \"B\", \"Benign\")) %>% \n ungroup() %>% \n rsample::initial_split(prop = 0.7, strata = diagnosis) -> wbcd_split\n\nwbcd_split %>% # 데이터 어떻게 생겼나?\n training() %>% # 테스트 데이터 보려면 testing()\n glimpse() \n\nwbcd_split %>% training() -> train_df\nwbcd_split %>% testing() -> test_df\n\n# 이제부터 직관적인 분석이 시작됩니다.\ndf_rec <- recipe(diagnosis ~., data = train_df) %>% \n step_downsample(diagnosis) %>% # 훈련데이터 정제작업\n step_center(-diagnosis) %>% # 숫자 데이터를 평균0으로 정규화\n step_scale(-diagnosis) %>% # 숫자 데이터를 표준편차 1로 정규화\n prep()\n\ndf_juiced <- juice(df_rec)\n\ndf_juiced %>% pivot_longer(-diagnosis) %>% \n ggplot() +\n geom_histogram(aes(value, fill = diagnosis)) +\n facet_wrap(~name)\n\nbaked_test <- bake(df_rec, new_data = test_df)\n\ninstall.packages(\"kknn\")\n#make a knn spec\nknn_spec <- nearest_neighbor() %>% \n set_engine(\"kknn\") %>% \n set_mode(\"classification\")\n\n#make a rf spec\nrf_spec <- rand_forest() %>% \n set_engine(\"ranger\") %>% \n set_mode(\"classification\")\n\n#use the knn spec to fit the pre-processed training data\nknn_fit <- knn_spec %>% \n fit(diagnosis ~., data = df_juiced)\n\n#use the rf spec to fit the pre-processed training data\nrf_fit <- rf_spec %>% \n fit(diagnosis ~., data = df_juiced)\n\nrf_fit\n\nknn_fit %>% \n predict(baked_test) %>% \n bind_cols(baked_test) %>% \n metrics(truth = diagnosis, estimate = .pred_class)\n\nknn_fit %>% \n predict(df_juiced) %>% \n bind_cols(df_juiced) %>% \n metrics(truth = diagnosis, estimate = .pred_class)\n\nrf_fit %>% \n predict(df_juiced) %>% \n bind_cols(df_juiced) %>% \n metrics(truth = diagnosis, estimate = .pred_class)\n\n\nresults_train <- knn_fit %>% \n predict(df_juiced) %>% \n mutate(model = \"knn\", \n truth = df_juiced$diagnosis) %>% \n bind_rows(rf_fit %>% \n predict(df_juiced) %>% \n mutate(model = \"rf\",\n truth = df_juiced$diagnosis)\n \n ) %>% \n mutate(accuracy = if_else(.pred_class == truth, \"yes\", \"no\"))\n\n\nresults_test <- knn_fit %>% \n predict(baked_test) %>% \n mutate(model = \"knn\", \n truth = baked_test$diagnosis) %>% \n bind_rows(rf_fit %>% \n predict(baked_test) %>% \n mutate(model = \"rf\",\n truth = baked_test$diagnosis)\n \n ) %>% \n mutate(accuracy = if_else(.pred_class == truth, \"yes\", \"no\"))\n\n\nresults_train %>% \n ggplot() +\n geom_bar(aes(accuracy, fill = accuracy)) +\n facet_wrap(~ model)\n\nresults_test %>% \n ggplot() +\n geom_bar(aes(accuracy, fill = accuracy)) +\n facet_wrap(~ model)\n", "meta": {"hexsha": "bea9b402dd364d431e4b697bf083ef51ef48d898", "size": 7119, "ext": "r", "lang": "R", "max_stars_repo_path": "Data_analytics/machineLearning/Chapter03/MLwR_3rdEd_03.r", "max_stars_repo_name": "kjsang/My.R.Study", "max_stars_repo_head_hexsha": "83ea82feb77190fc3ca43798ede985751dcb1233", "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_analytics/machineLearning/Chapter03/MLwR_3rdEd_03.r", "max_issues_repo_name": "kjsang/My.R.Study", "max_issues_repo_head_hexsha": "83ea82feb77190fc3ca43798ede985751dcb1233", "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_analytics/machineLearning/Chapter03/MLwR_3rdEd_03.r", "max_forks_repo_name": "kjsang/My.R.Study", "max_forks_repo_head_hexsha": "83ea82feb77190fc3ca43798ede985751dcb1233", "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.1762295082, "max_line_length": 134, "alphanum_fraction": 0.6690546425, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6734945077817933}} {"text": "#' @title calcHullEff\n#'\n#' @description Calculate the hull efficiency (\\code{hullEff}) (dimensionless)\n#' for a specified vessel.\n#'\n#' @param thrustFactor Thrust deduction coefficient (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcHMThrustFactor}} and \\code{\\link{calcKristThrustFactor}})\n#' @param wakeFraction Wake fraction coefficient (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcHMWakeFraction}} and \\code{\\link{calcKristWakeFrac}})\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcHMThrustFactor}}\n#'\\item \\code{\\link{calcKristThrustFactor}}\n#'\\item \\code{\\link{calcHMWakeFraction}}\n#'\\item \\code{\\link{calcKristWakeFrac}}}\n#'\n#' @return \\code{hullEff} (vector of numericals, dimensionless)\n#'\n#' @examples\n#' calcHullEff(c(0.19,0.17), c(0.32,0.29))\n#'\n#' @export\n\ncalcHullEff <- function(thrustFactor, wakeFraction ){\n\n hullEff<- (1-thrustFactor)/(1-wakeFraction)\n\n\n return(hullEff)\n}\n", "meta": {"hexsha": "96f7c2ff898ed1234f37423d18fcb4f05cd8d3dd", "size": 926, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHullEff.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/calcHullEff.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/calcHullEff.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": 29.8709677419, "max_line_length": 89, "alphanum_fraction": 0.7246220302, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6732415334900307}} {"text": "# 1A\r\n# X... pocet stad na 1km^2\r\n# X - pouzijeme Poissonovu vetu\r\nlambda = 1/25\r\nt = 100\r\nlt = lambda*t # parametr Poissonova rozdeleni\r\n\r\n# P(x <= 6)\r\n# V oblasti 100km^2 bude nejvyse 6 stad\r\nppois(6, lt) # s pravdepodobnosti 88,93 %\r\n\r\n\r\n# 1B\r\n# P(1<=X<=7) = P(X <= 7) - P(X <= 0)\r\n# V oblasti 100km^2 bude alespon 1 ale nejvyse 7 stad\r\nppois(7, lt) - ppois(0, lt) # s pravdepodobnosti 93,06 %\r\n\r\n\r\n# 1C\r\n# V oblasti 100km^2 bude alespon 5 stad, jestlize 2 stada byla nalezena\r\n(1-ppois(4,lt)) / (1-ppois(1,lt)) # 0.4085801\r\n\r\n\r\n\r\n# 1D\r\nlambda = 1/25 \r\nt = 50 \r\n# P(X >= 1) = P(X > 0) = 1 - P(X <= 0)\r\n# V oblasti 50km^2 bude alespon jedno stado\r\n1 - ppois(0, lambda*t) # s pravdepodobnosti 86,47 %\r\n\r\n\r\n\r\n# 2A\r\n# X... pocet opravenych domacich ukolu za 1h\r\n# X - pouzijeme Poissonovu vetu\r\nlambda = 6 # cetnost vyskytu za hodinu\r\nt = 8 # behem 8mi hodin\r\nlt = lambda*t # parametr Poissonova rozdeleni\r\n\r\n# P(x > 50) = 1 - P(X <= 49)\r\n# Opravi vice jak 50 ukolu\r\n1 - ppois(50, lt) # s 35,13% pravdepodobnosti\r\n\r\n#Pravd fun\r\nx = 20:80 \r\nP_x = dpois(x-1, lt)\r\nplot(x, P_x)\r\ngrid()\r\n\r\n#Dist fun\r\nx = 20:80 \r\nF_x = ppois(x-1, lt)\r\nplot(x, F_x, type='s')\r\ngrid()\r\n\r\n\r\n# 2B\r\n# Opravi 45 az 55 ukolu\r\nppois(55, lt) - ppois(45-1, lt) # s 54,67% sanci\r\n\r\n\r\n# 2C\r\n# Opravi 55 ukolu jestlize 40 opravil\r\n(1 - ppois(54, lt)) / (1 - ppois(39, lt)) # s pravdepodobnosti 19,4 %\r\n\r\n\r\n# 2D\r\n# X ... pocet pokusu nez vybereme spatny ukol\r\n# X ~ NB(k = 3,p = 0.2)\r\nx = 17\r\nk = 3\r\np = 0.2\r\n# P(X > 15) = 1 - P(X <= 15)\r\n# Narazi na tri spatne ukoly nejdrive za 17 pokusu\r\n1-pnbinom(x - k, k, p) # s pravdepodobnosti 30,96 %\r\n\r\n\r\n\r\n# 3A\r\n# X ... doba do restartu ve dnech\r\n## X ~ Exp(lambda), kde E(X)=1/lambda\r\nlambda = 1/365\r\n\r\nx = seq(from = 0, to = 2500, by = 1)\r\nf_x = dexp(x-1, lambda)\r\nplot(x, f_x, cex = 0.1, main=\"Hustota pravdepodobnosti po dnech\")\r\ngrid()\r\n\r\nF_x = pexp(x-1, lambda)\r\nplot(x, F_x, type='s', main=\"Distribucni funkce po dnech\")\r\ngrid()\r\n\r\n\r\n# 3B\r\n# Restart bude potreba nejdrive za 13 mesicu\r\n1 - pexp(365/12*13, lambda) # s pravdepodobnosti 33,85 %\r\nx = seq(from = 0, to = 2500, by = 1)\r\nf_x = dexp(x-1, lambda)\r\nplot(x, f_x, cex = 0.1, main=\"Hustota pravdepodobnosti a restart po 13 mesicich\")\r\nlines(c(0, 2500),c(dexp(365/12*13, lambda), dexp(365/12*13, lambda)))\r\nlines(c(365/12*13, 365/12*13),c(0, max(f_x)))\r\ngrid()\r\n\r\n\r\n# 3C\r\n# Pravdepodobnost restartu po roce pouzivani v nasledujicich 14 dnech\r\npexp(365 + 365/52*2, lambda) - pexp(365, lambda) # je 1,38 %.\r\n\r\n\r\n# 3D\r\n# P(X F(t)=0,9 -> t… 90% kvantil\r\n# Server bude treba restartovat s 90 % pravdepodobnosti\r\nqexp(0.9, lambda) # po 840,4 dnech.\r\n\r\n\r\n\r\n# 4A\r\n# Systolicky krevni tlak, normalni rozdeleni se stredni hodnotou 112 a smerodatnou odchylkou 10\r\nmu = 112\r\nsigma = 10\r\n\r\n# vykreslime si Hustotu pravdepodobnosti\r\nx = seq(from = 70, to = 150, by = 0.1)\r\nf_x = dnorm(x, mean=mu, sd=sigma)\r\nplot(x, f_x, cex = 0.01, main=\"Hustota pravdepodobnosti\")\r\ngrid()\r\n\r\n# vykreslime si Distribucni funkci\r\nF_x = pnorm(x, mean=mu, sd=sigma)\r\nplot(x, F_x, type = 'l', main=\"Distribucni funkce\")\r\ngrid()\r\n\r\n\r\n# 4B\r\n# Tlak mimo rozmezi 90 az 120g\r\n1- (pnorm(120, mean=mu, sd=sigma) - pnorm(90, mean=mu, sd=sigma)) # s pravdepodobnosti 22,58 %\r\n\r\n# Zaznaceni do grafu\r\n# x = c(seq(from = 50, to = 90, by = 0.1),seq(from = 120, to = 180, by = 0.1))\r\n# Vysrafovana oblast je pod krivkou v levo od hodnoty 90 a v pravo od hodnoty x=120 a y<0\r\nx = seq(from = 70, to = 150, by = 0.1)\r\nf_x = dnorm(x, mean=mu, sd=sigma)\r\nplot(x, f_x, cex = 0.01, main=\"Hustota pravdepodobnosti\")\r\nlines(c(90,90),c(0,max(f_x)))\r\nlines(c(120,120),c(0,max(f_x)))\r\ngrid()\r\n\r\n\r\n# 4C\r\n# Tlak nizsi nez 105mmHg\r\npnorm(105, mean=mu, sd=sigma) # s pravdepodobnosti 24,2 %\r\nF_x = pnorm(x, mean=mu, sd=sigma)\r\nplot(x, F_x, type = 'l', main=\"Distribucni funkce s tlakem\")\r\nlines(c(105,105),c(0,max(F_x)))\r\nlines(c(70,150),c(pnorm(105, mean=mu, sd=sigma),pnorm(105, mean=mu, sd=sigma)))\r\ngrid()\r\n\r\n\r\n# 4D\r\n# 82. percentil\r\nqnorm(0.82, mean=mu, sd=sigma) # je 121.15 mmHg\r\n# Vysvetleni percentilu: 82% lidi ma hodnotu systolickeho krevniho tlaku do hranice 121.15 mmHg\r\n\r\n", "meta": {"hexsha": "033a91d3066009750aa537b054379c82c99fe4eb", "size": 4102, "ext": "r", "lang": "R", "max_stars_repo_path": "3P/3P.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "3P/3P.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "3P/3P.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": 24.8606060606, "max_line_length": 96, "alphanum_fraction": 0.6214041931, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6730556443030162}} {"text": "library(tidyr)\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(cowplot)\nlibrary(readr)\n\n\npredict_mean_fitness <- function(Ne, L, s, eps)\n{\n k <- c(0:L)\n f <- exp(-s*k^(1-eps))\t\n p_k <- (f^(2*Ne-2)*choose(L, k))/sum(f^(2*Ne-2)*choose(L, k))\n sum(f*p_k)\n}\n\n#file_lst <- list.files(\"sim_results\",pattern=\"n100.txt\",full.names=T)\nt <- read_csv(\"../processed_results/all.csv\")\n\nt %>% group_by(sel_coef,epistasis_coef,mu_prob) %>%\n mutate(an_mean_fitness=predict_mean_fitness(100,100,sel_coef,epistasis_coef),q=1-epistasis_coef)-> t_sum\n\nfor (s in c(0.1, 0.01, 0.001, 0.0001)){\n t_sum %>% filter(sel_coef==s) -> f\n \n p <- ggplot(f, aes(x=mu_prob*100, y=mean_fitness,color=factor(q)))+\n stat_summary(fun.y = mean,\n fun.ymin = function(x) mean(x) - sd(x)/sqrt(length(x)), \n fun.ymax = function(x) mean(x) + sd(x)/sqrt(length(x)), \n geom = \"pointrange\",\n size=0.4)+\n geom_line(aes(y = an_mean_fitness,group=factor(epistasis_coef),color=factor(q)))+\n xlab('Ne*mu')+\n ylab('Mean fitness')+\n scale_x_log10()+\n #scale_y_continuous(breaks=seq(0.99,1,0.005))+\n guides(col = guide_legend(title=\"Q\",reverse = TRUE))+\n theme(axis.title = element_text(size = 14),\n axis.text = element_text(size = 12),\n legend.text = element_text(size = 11),\n legend.title = element_text(size = 12))\n \n save_plot(paste0(\"../plots/mean_fit_v_time_s\",s,\".pdf\"), p)\n}\n\n\n\n", "meta": {"hexsha": "cbd244d022511966f998d7558fe0041dba3ba688", "size": 1449, "ext": "r", "lang": "R", "max_stars_repo_path": "fixed_q_sim/src/plot_fitness_v_sel_coeff.r", "max_stars_repo_name": "clauswilke/epistasis_evolution", "max_stars_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "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": "fixed_q_sim/src/plot_fitness_v_sel_coeff.r", "max_issues_repo_name": "clauswilke/epistasis_evolution", "max_issues_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "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": "fixed_q_sim/src/plot_fitness_v_sel_coeff.r", "max_forks_repo_name": "clauswilke/epistasis_evolution", "max_forks_repo_head_hexsha": "25ef74bb772d98ec14a9fcb367be85c56ca308f1", "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.829787234, "max_line_length": 106, "alphanum_fraction": 0.6169772257, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6726097688388913}} {"text": "#' Calculates mean and standard error of frequency data\r\n#' \r\n#' Helper function for Francis ESS calculations.\r\n#' @param bins the values in the class marks (ages in this case)\r\n#' @param N the total number (ESS in this case)\r\n#' @param frdist the frequency distribution (should sum to one over the bins)\r\n#' @return vector of mean and standard error\r\n#' @export\r\n \r\nCalcFreqMeanSE <- function(bins,N,frdist){\r\n Y <- bins\r\n f <- N*frdist\r\n n <- sum(f)\r\n sumfY <- sum(f*Y)\r\n Ybar <- sumfY/n\r\n sumfY2 <- sum(f*Y*Y)\r\n CT <- sumfY^2/n\r\n sumfy2 <- sumfY2-CT\r\n s2 <- sumfy2/(n-1)\r\n sigma <- sqrt(s2)\r\n stderror <- sigma/sqrt(n) # note this is standard deviation of the mean\r\n meanstderror <- c(Ybar,stderror)\r\n return(meanstderror)\r\n}\r\n", "meta": {"hexsha": "c346f33398a35a6cd5f5bbb537c0db37ab542a3e", "size": 744, "ext": "r", "lang": "R", "max_stars_repo_path": "R/calc_freq_mean_se.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/calc_freq_mean_se.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/calc_freq_mean_se.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": 29.76, "max_line_length": 78, "alphanum_fraction": 0.6559139785, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6725356847335381}} {"text": "=begin\n # sample-algebraicfield02.rb\n\n require \"algebra\"\n \n F = AlgebraicExtensionField(Rational, \"x\") {|x| x**2 + x + 1}\n x = F.var\n p( (x + 1)**100 )\n p( (x-1)** 3 / (x**2 - 1) )\n \n H = AlgebraicExtensionField(F, \"y\") {|y| y**5 + x*y + 1}\n y = H.var\n p( 1/(x + y + 1)**7 )\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "bf8709662175f2e88daf6765c51bffc9efe29050", "size": 308, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-algebraicfield02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-algebraicfield02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-algebraicfield02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 19.25, "max_line_length": 63, "alphanum_fraction": 0.5, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6724731476163277}} {"text": "outliers_fnc <- function(x, conf.level = 0.95)\n{\n x <- x[!is.na(x)]\n del.val <- NULL\n \n while (TRUE) {\n n <- length(x)\n if (n < 3) {\n break\n }\n \n r <- range(x)\n t <- abs(r - mean(x)) / sd(x)\n q <- sqrt((n - 2) / ((n - 1) ^ 2 / t ^ 2 / n - 1))\n p <- n * pt(q, n - 2, lower.tail = FALSE)\n \n if (t[1] < t[2]) {\n if (p[2] < 1 - conf.level) {\n del.val <- c(del.val, r[2])\n x <- x[x != r[2]]\n next\n }\n } else {\n if (p[1] < 1 - conf.level) {\n del.val <- c(del.val, r[1])\n x <- x[x != r[1]]\n next\n }\n }\n break\n }\n return(list(x = x, del.val = del.val))\n}\n", "meta": {"hexsha": "8f98595bfaba210dc4ee0faa0365222a50ead266", "size": 659, "ext": "r", "lang": "R", "max_stars_repo_path": "Application/DDS2/script/outlier_removal.r", "max_stars_repo_name": "Sanaxen/Data_analysis_tools", "max_stars_repo_head_hexsha": "be487ef5d011e1dd9af347a8c6f2b9347bcfabf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-01-20T13:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:39:39.000Z", "max_issues_repo_path": "Application/DDS2/script/outlier_removal.r", "max_issues_repo_name": "Sanaxen/Data_analysis_tools", "max_issues_repo_head_hexsha": "be487ef5d011e1dd9af347a8c6f2b9347bcfabf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-09T13:16:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-09T13:16:52.000Z", "max_forks_repo_path": "Application/DDS2/script/outlier_removal.r", "max_forks_repo_name": "Sanaxen/Data_analysis_tools", "max_forks_repo_head_hexsha": "be487ef5d011e1dd9af347a8c6f2b9347bcfabf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-08T09:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T09:37:23.000Z", "avg_line_length": 19.3823529412, "max_line_length": 54, "alphanum_fraction": 0.373292868, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6724731464975614}} {"text": "#####################################################\n#\n# Usage: R --vanilla --slave < linear_reqgression.r\n# \thttp://d.hatena.ne.jp/n_shuyo/20090709/predictive\n#\n#####################################################\n\nM <- 9\t\t# number of basis function\nalpha <- 2\t# hyper parameter α\nbeta <- 25\t# hyper parameter β\nLattice <- 30\t# number of graph's lattice\ns<-0.1\nu_i<-0.5\n\n# training data\nxlist <- seq(0, 1, length=25)\ntlist <- sin(2*pi*xlist) + rnorm(length(xlist), sd=0.2)\nD0 <- data.frame(x=xlist, t=tlist)\n\npredictive <- function(D) {\n # design matrix\n gauss_base_func <- function(x)exp(-(x-u_i)^2/(2*s*s))\n phi <- function(x) sapply(x,function(x){exp(-(x-seq(0,1,length=9))^2/(2*s*s))})\n PHI <- t(phi(D$x))\n\n # convariance matrix & means\n S_N_inv <- alpha * diag(9) + beta * t(PHI) %*% PHI\n S_N <- solve(S_N_inv)\n m_N <- beta * S_N %*% t(PHI) %*% D$t\n\n # regression function\n y <- function(x)(t(phi(x)) %*% m_N)\n plot(y, xlim=c(0,1), ylim=c(-1.2, 1.2))\n par(new=T)\n plot(D, xlim=c(0,1), ylim=c(-1.2, 1.2), ylab=\"\")\n\n # predictive distribution\n var_N <- function(x) {1/beta + (t(phi(x)) %*% S_N %*% phi(x))[1]}\n function(x,t) {\n mapply(function(x,t)dnorm(t,m=(t(m_N) %*% phi(x))[1], s=var_N(x), log=T), x, t)\n }\n}\ndraw_dist <- function(p){\n x <- seq(0, 1, length=Lattice)\n t <- seq(-1.5, 1.5, length=Lattice*2)\n z <- outer(x, t, p)\n persp(x, t, z, theta=0, phi=60, shade=0.4)\n}\n\np <- predictive(D0[sample(length(D0$x))[1:1],])\ndraw_dist(p);\np <- predictive(D0[sample(length(D0$x))[1:2],])\ndraw_dist(p);\np <- predictive(D0[sample(length(D0$x))[1:4],])\ndraw_dist(p);\np <- predictive(D0)\ndraw_dist(p);\n\n\n# pdf(\"PRML_graph.pdf\")\n# dev.off()\n", "meta": {"hexsha": "f755c20f652d68c8e5d18cd539b598c01304a260", "size": 1712, "ext": "r", "lang": "R", "max_stars_repo_path": "meeting/9th/example/linear_regression.r", "max_stars_repo_name": "nichiyoubi/temporal_logic_ml", "max_stars_repo_head_hexsha": "bbd0909ed379a4a5f636931f4fe8dc3523c8163d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-11-07T16:34:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-27T16:18:57.000Z", "max_issues_repo_path": "meeting/9th/example/linear_regression.r", "max_issues_repo_name": "nichiyoubi/temporal_logic_ml", "max_issues_repo_head_hexsha": "bbd0909ed379a4a5f636931f4fe8dc3523c8163d", "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": "meeting/9th/example/linear_regression.r", "max_forks_repo_name": "nichiyoubi/temporal_logic_ml", "max_forks_repo_head_hexsha": "bbd0909ed379a4a5f636931f4fe8dc3523c8163d", "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.6129032258, "max_line_length": 87, "alphanum_fraction": 0.5432242991, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6724520727919078}} {"text": "# https://fivethirtyeight.com/features/who-will-win-the-lucky-derby/\n# The bugle sounds, and 20 horses make their way to the starting gate for the first annual Lucky Derby. \n# These horses, all trained at the mysterious Riddler Stables, are special. \n# Each second, every Riddler-trained horse takes one step. Each step is exactly one meter long. \n# But what these horses exhibit in precision, they lack in sense of direction. \n# Most of the time, their steps are forward (toward the finish line) but the rest of the time they are backward \n# (away from the finish line). As an avid fan of the Lucky Derby, you’ve done exhaustive research on these 20 competitors. \n# You know that Horse One goes forward 52 percent of the time, Horse Two 54 percent of the time, Horse Three 56 percent, and so on, \n# up to the favorite filly, Horse Twenty, who steps forward 90 percent of the time. \n# The horses’ steps are taken independently of one another, and the finish line is 200 meters from the starting gate.\n\n# Handicap this race and place your bets! In other words, what are the odds (a percentage is fine) that each horse wins?\n\n# Libraries\nlibrary(tidyverse)\n\n# Inputs\nn_horses <- 20 # horses in race\nstp <- 1 # length of each step\ndir_fwd <- seq(52, 90, 2) / 100 # chance each horse takes step forward\ndst <- 200 # length of race \n\n# Code\n# Odds each horse wins\ntrials <- 10000\nwinners <- rep(0, n_horses)\nfor (i in 1:trials) {\n track <- tibble(horses = 1:n_horses, \n pos = rep(0, n_horses),\n fwd = dir_fwd)\n a <- runif(1000, 0, 1)\n while(max(track$pos) < dst) {\n b <- sample(a, n_horses)\n track <- track %>% \n mutate(pos = pmax(0, pos + ifelse(fwd >= b, 1, -1)))\n }\n # Tally wins\n # Count ties as wins\n winners[which(track$pos >= dst)] <- winners[which(track$pos >= dst)] + 1\n}\n\n# Output\ntrack <- track %>% mutate(win = winners / sum(winners))\nprint(track)\nggplot(track) +\n geom_point(mapping = aes(win, horses))\n", "meta": {"hexsha": "a4a4d0234161c2c7b1eab94f436d7a59006fe291", "size": 2034, "ext": "r", "lang": "R", "max_stars_repo_path": "horseRace.r", "max_stars_repo_name": "sgranitz/riddler", "max_stars_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "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": "horseRace.r", "max_issues_repo_name": "sgranitz/riddler", "max_issues_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "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": "horseRace.r", "max_forks_repo_name": "sgranitz/riddler", "max_forks_repo_head_hexsha": "e77df77289f3e3710626b1eeb506a7b0cdf4ecd3", "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": 43.2765957447, "max_line_length": 132, "alphanum_fraction": 0.6710914454, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6724450521535353}} {"text": "\\name{generate_fit_only}\n\\alias{generate_fit_only}\n%- Also NEED an '\\alias' for EACH other topic documented here.\n\\title{\n Simulating networks from the Caldarelli model}\n\\description{\n This function generates networks from the Caldarelli model. In this model, the preferential attachment function is constant, i.e. \\eqn{A_k = 1}, and node fitnesses are sampled from some probability distribution. \n}\n\\usage{\ngenerate_fit_only(N = 1000 , \n num_seed = 2 , \n multiple_node = 1 , \n m = 1 ,\n mode_f = \"gamma\", \n s = 10 )\n}\n\n%- maybe also 'usage' for other objects documented here.\n\\arguments{\n The parameters can be divided into two groups. \n \n The first group specifies basic properties of the network:\n \\item{N}{\n Integer. Total number of nodes in the network (including the nodes in the seed graph). Default value is \\code{1000}.\n }\n \\item{num_seed}{\n Integer. The number of nodes of the seed graph (the initial state of the network). The seed graph is a cycle. Default value is \\code{2}.\n }\n \\item{multiple_node}{\n Positive integer. The number of new nodes at each time-step. Default value is \\code{1}.\n }\n \\item{m}{\n Positive integer. The number of edges of each new node. Default value is \\code{1}.\n }\n \n The final group of parameters specifies the distribution from which node fitnesses are generated:\n \\item{mode_f}{\n String. Possible values:\\code{\"gamma\"}, \\code{\"log_normal\"} or \\code{\"power_law\"}. This parameter indicates the true distribution for node fitness. \\code{\"gamma\"} = gamma distribution, \\code{\"log_normal\"} = log-normal distribution. \\code{\"power_law\"} = power-law (pareto) distribution. Default value is \"gamma\".\n }\n\\item{s}{\nNon-negative numeric. The inverse variance parameter. The mean of the distribution is kept at \\eqn{1} and the variance is \\eqn{1/s} (since node fitnesses are only meaningful up to scale). This is achieved by setting shape and rate parameters of the Gamma distribution to \\eqn{s}; setting mean and standard deviation in log-scale of the log-normal distribution to \\eqn{-1/2*log (1/s + 1)} and \\eqn{(log (1/s + 1))^{0.5}}; and setting shape and scale parameters of the pareto distribution to \\eqn{(s+1)^{0.5} + 1} and \\eqn{(s+1)^{0.5}/((s+1)^{0.5} + 1)}. If \\code{s} is \\code{0}, all node fitnesses \\eqn{\\eta} are fixed at \\code{1} (i.e., \\enc{Barabási}{Barabasi}-Albert model). The default value is \\code{10}.\n}\n}\n\n\\value{\n The output is a \\code{PAFit_net} object, which is a List contains the following four fields:\n \\item{graph}{a three-column matrix, where each row contains information of one edge, in the form of \\code{(from_id, to_id, time_stamp)}. \\code{from_id} is the id of the source, \\code{to_id} is the id of the destination.}\n \\item{type}{a string indicates whether the network is \\code{\"directed\"} or \\code{\"undirected\"}.}\n \\item{PA}{a numeric vector contains the true PA function.}\n \\item{fitness}{fitness values of nodes in the network. The name of each value is the ID of the node.}\n}\n\\author{\n Thong Pham \\email{thongpham@thongpham.net}\n}\n\\references{\n 1. Caldarelli, G., Capocci, A. , De Los Rios, P. & \\enc{Muñoz}{Munoz}, M.A. (2002). Scale-Free Networks from Varying Vertex Intrinsic Fitness. Phys. Rev. Lett., 89, 258702 (\\url{http://link.aps.org/doi/10.1103/PhysRevLett.89.258702}).\n}\n\\seealso{\n For subsequent estimation procedures, see \\code{\\link{get_statistics}}.\n \n For other functions to generate networks, see \\code{\\link{generate_net}}, \\code{\\link{generate_BA}}, \\code{\\link{generate_ER}} and \\code{\\link{generate_BB}}. }\n\n\\examples{\n library(\"PAFit\")\n # generate a network from the Caldarelli model with alpha = 1, N = 100, m = 1\n # the inverse variance of distribution of node fitnesses is s = 10\n net <- generate_fit_only(N = 100,m = 1,mode = 1, s = 10)\n str(net)\n plot(net)\n}\n\n% Add one or more standard keywords, see file 'KEYWORDS' in the\n% R documentation directory.\n\\concept{ fitness model }% __ONLY ONE__ keyword per line\n", "meta": {"hexsha": "e7f8e0b2e822acebdf73e382f3a791d63ef381c5", "size": 4129, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/generate_fit_only.rd", "max_stars_repo_name": "eddelbuettel/PAFit", "max_stars_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "man/generate_fit_only.rd", "max_issues_repo_name": "eddelbuettel/PAFit", "max_issues_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "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": "man/generate_fit_only.rd", "max_forks_repo_name": "eddelbuettel/PAFit", "max_forks_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.0533333333, "max_line_length": 708, "alphanum_fraction": 0.6863647372, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733979704703, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6723682774440013}} {"text": "=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Algebra::MPolynomial\n((*(Class of Multi-variate Polynomial Ring)*))\n\nThis class expresses the multi-variate polynomial ring over arbitrary ring.\nFor creating the actual class, use the class method ((<::create>))\nor (())(), giving the coefficient ring.\n\n== File Name:\n* ((|m-polynomial.rb|))\n\n== SuperClass:\n\n* ((|Object|))\n\n== Included Modules:\n\n* ((|Enumerable|))\n* ((|Comparable|))\n* (())\n\n== Associated Function:\n\n--- Algebra.MPolynomial(ring [, obj0 [, obj1 [, ...]]])\n Same as ((<::create>))(ring [, obj0[, obj1[, ...]]]).\n\n== Class Methods:\n\n--- ::create(ring [, obj0 [, obj1 [, ...]]])\n Creates a multi-variate polynomial ring class over the coefficient\n ring expressed by the class: ((|ring|)).\n\n The objects (({obj0, obj1, ...})) are reserved and represent variables.\n They are only to utilize for the names of variables (for ((|to_s|)) )\n and the distinction.\n \n The return value of this method is a sub-class of ((|Algebra::MPolynomial|)).\n This class has class-methods: ((|ground|)) and ((|vars|)), \n which return\n the coefficient ring ((|ring|)) and an array of variables.\n \n The variables represented by objects (({obj0, obj1, ...})) can be\n able to obtain as :(({var(obj0)})), (({var(obj1)})),... So, \n (({vars == [var(obj0), var(obj1), ...]})).\n \n The order of each variable is: (({obj0 > obj1 > ...})), and\n the order of monomials is determined by ((<::set_ord>)).\n\n Example: Polynomial ring over Integer\n require \"m-polynomial\"\n P = Algebra::MPolynomial.create(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -x^3 + x^2y + x^2z + xy^2 - 2xyz + xz^2 - y^3 + y^2z + yz^2 - z^3\n p P.ground #=> integer\n\n--- ::vars([obj0 [, obj1 [, ...]]])\n ((*When no parameter is designated*)), it returns the array of \n all variables, already reserved.\n \n Example:\n P = Algebra.MPolynomial(Integer, \"x\", \"y\", \"z\")\n p P.vars #=> [x, y, z]\n \n ((*When only one parameter of ((|String|)) is designated *)), \n splits the string into identifiers and reserves them, which\n represent variables. The string of \"AN ALPHABET + SOME DIGITS\" can be\n an identifier.\n \n If the object has been already reserved, no new reservation is done.\n The return value of this method is an array of variables corresponding\n to the objects.\n \n Example: \n P = Algebra.MPolynomial(Integer)\n x, y, z, w = P.vars(\"a0b10cd\")\n p P.vars #=> [a0, b10, c, d]\n p [x, y, z, w] #=> [a0, b10, c, d]\n\n ((*Otherwise*)), reserve objects (({obj0, obj1, ...})) which represent\n variables. If the object has been already reserved, no reservation is \n done. \n The return value of this method is an array of variables corresponding\n to the objects.\n\n Example:\n P = Algebra.MPolynomial(Integer)\n p P.vars(\"x\", \"y\", \"z\") #=> [x, y, z]\n\n--- ::mvar([obj0 [, obj1 [, ...]]])\n ((*When no parameter is designated*)), it returns the array of \n all variables, already reserved.\n \n ((*Otherwise*)), reserve objects (({obj0, obj1, ...})) which represent\n variables. If the object has been already reserved, no reservation is \n done. \n The return value of this method is an array of variables corresponding\n to the objects.\n\n--- ::to_ary\n Returns (({[self, *vars]})).\n\n Example: Define MPolynomial ring and variables simulteniously\n P, x, y, z, w = Algebra.MPolynomial(Integer, \"a\", \"b\", \"c\", \"d\")\n\n--- ::var(obj)\n Returns the variable, which is represented by ((|obj|)).\n \n Example: \n P = Algebra.MPolynomial(Integer, \"X\", \"Y\", \"Z\")\n x, y, z = P.vars\n P.var(\"Y\") == y #=> true\n\n--- ::variables\n Returns the array of reserved objects, which represent variables.\n\n--- ::indeterminate(obj)\n Same as ((<::var>)).\n\n--- ::zero?\n Returns true if ((|self|)) is zero.\n\n--- ::zero\n Returns zero.\n \n--- ::unity\n Returns unity.\n\n--- ::set_ord(ord [, v_ord])\n Sets the order of monomials as ((|ord|)) which is ((|Symbol|))\n of ordering type.\n The possible designations are ((|:lex|)) (lexicographic order (default)), \n ((|:grlex|)) (graded lexicographic order), ((|:grevlex|)) (graded\n reverse lexicographic order). \n \n The order of variables is the order of reservation.\n By the array ((|v_ord|)), we can transform the order.\n \n Example: the order of (({x, y, z = P.var(\"xyz\")}))\n require \"m-polynomial\"\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n\n P.set_ord(:lex)\n p f #=> -5x^3 + 7x^2z^2 + 4xy^2z + 4z^2\n\n f.method_cash_clear\n P.set_ord(:grlex)\n p f #=> 7x^2z^2 + 4xy^2z - 5x^3 + 4z^2\n\n f.method_cash_clear\n P.set_ord(:grevlex)\n p f #=> 4xy^2z + 7x^2z^2 - 5x^3 + 4z^2\n\n f.method_cash_clear\n P.set_ord(:lex, [2, 1, 0]) # z > y > x\n p f #=> 7x^2z^2 + 4z^2 + 4xy^2z - 5x^3\n\n See ((<::with_ord>)).\n\n--- ::ord=(x)\n Same as ((<::set_ord(x)>)).\n\n#--- ::order=(obj)\n# Same as ((<::set_ord(obj)>)).\n\n--- ::get_ord\n Returns the monomial order. (:lex, :grlex, :grevlex)\n\n--- ::ord\n Same as ((<::get_ord>)).\n\n#--- ::order\n# Same as ((<::get_ord>)).\n\n--- ::with_ord(ord [, v_ord[ [, array_of_polys]])\n Executes the block with monomial ordering ((|ord|)) and\n order of variables ((|v_ord|)). These ordering are\n available only in the block.(See ((<::set_ord>)).)\n When the array of polyomials ((|array_of_polys|)) is given,\n for each of them, (()) is invoked before\n the execution. (This is not a thread-safe block.)\n\n Example:\n require \"m-polynomial\"\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n\n P.with_ord(:lex, nil, [f]) do\n p f #=> -5x^3 + 7x^2z^2 + 4xy^2z + 4z^2\n p f.lt #=> -5x^3\n end\n\n P.with_ord(:grlex, nil, [f]) do\n p f #=> 7x^2z^2 + 4xy^2z - 5x^3 + 4z^2\n p f.lt #=> 7x^2z^2\n end\n\n P.with_ord(:grevlex, nil, [f]) do\n p f #=> 4xy^2z + 7x^2z^2 - 5x^3 + 4z^2\n p f.lt #=> 4xy^2z\n end\n\n P.with_ord(:lex, [2, 1, 0], [f]) do # z > y > x\n p f #=> 7x^2z^2 + 4z^2 + 4xy^2z - 5x^3\n p f.lt #=> 7x^2z^2\n end\n\n--- ::monomial(ind[, c])\n Returns the monomial of multi-degree ((|ind|)) and\n coefficient ((|c|)).\n ((()) is not extend.)\n If ((|c|)) is omitted, it is assumed to be the unity.\n\n#--- ::const(x)\n#--- ::regulate(x)\n#--- ::method_cash_clear(*m)\n\n== Methods:\n\n--- monomial(ind[, c])\n Same as ((<::monomial>))\n\n#--- each\n#--- keys\n#--- values\n#--- [](ind)\n#--- []=(ind, c)\n#--- constant_coeff\n#--- include?\n#--- compact!\n#--- rt!\n\n--- constant?\n Retruns true if ((|self|)) is a constant.\n\n--- monomial?\n Returns true if ((|self|)) is a monomial.\n\n--- zero?\n Returns true if ((|self|)) is zero.\n\n--- zero\n Returns zero.\n \n--- unity\n Retruns unity.\n\n--- method_cash_clear\n Clears the cashes of methods.\n \n In this library, some results of methods are stored so as not to\n do same calculations. When the order of monomials is changed, \n we must clear the cashes.\n \n The methods which have cashes are following:\n (()), (()), (()), (()), (()).\n \n Example:\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n P.set_ord(:lex)\n p f.lt #=> -5x^3\n P.set_ord(:grlex)\n p f.lt #=> -5x^3\n f.method_cash_clear\n p f.lt #=> 7x^2z^2\n\n--- ==(other)\n Returns true if ((|self|)) is equal to ((|other|)).\n\n--- <=>(other)\n Returns positive if ((|self|)) is greater than ((|other|)).\n\n--- +(other)\n Returns the sum of ((|self|)) and ((|other|)).\n\n--- -(other)\n Returns the difference of ((|self|)) from ((|other|)).\n\n--- *(other)\n Returns the product of ((|self|)) and ((|other|)).\n\n--- **(n)\n Returns the ((|n|))-th power of ((|self|)).\n\n--- /(other)\n Returns the quotient of ((|self|)) by ((|other|)).\n ((|other|)) must be constant.\n\n--- divmod(f0 [, f1 [,...]])\n Returns the array [the array of quotients, the remainder] \n by (({f0, f1,...})).\n\n P = Algebra.MPolynomial(Integer)\n x, y = P.vars(\"xy\")\n f = x**2*y + x*y**2 + y**2\n f0 = x*y - 1\n f1 = y**2 - 1\n p f.divmod(f0, f1) #=> [[x + y, 1], x + y + 1]\n p f % [f0, f1] #=> x + y + 1\n\n--- %(others)\n Returns the remainder of ((|self|)) by polynomials ((|others|)).\n It is equal to (({divmod(*others)[1]})).\n\n--- multideg\n Returns the multiple degree as an array.\n \n Example: in lex order,\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.multideg #=> [3, 1]\n\n--- totdeg\n Returns the total degree.\n\n Example:\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.totdeg #=> 4\n\n--- deg\n Same as multideg.\n\n--- lc\n Returns the leading coefficient.\n\n Example: in lex order,\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.lc #=> -5\n\n--- lm\n Returns the leading monomial.\n The return value is extended by (()).\n\n Example: in lex order,\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.lm #=> x^3y\n\n--- lt\n Returns leading term. This is equal to (({lc * lm})).\n\n Example: in lex order\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.lt #=> -5x^3y\n\n--- rt\n Returns the rest term. This is equal to (({self - lt})).\n\n Example: in lex order,\n f = 4*x*y**2*z + 4*z**2 - 5*x**3*y + 7*x**2*z**2\n p f.rt #=> 4*z**2 - 5*x**3*y + 7*x**2*z**2\n\n--- to_s\n Return the representation of ((|String|)). To change the format of\n expression, use ((|display_type|)).\n The values which are able to designate to ((|display_type|)) is: \n ((|:norm|)) (default) and ((|:code|)).\n \n Example:\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n p f #=> -5x^3 + 7x^2z^2 + 4xy^2z + 4z^2\n P.display_type = :code\n p f #=> -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n\n--- map_to(ring[, vs]){|c, ind| ... }\n Returns the sum over ((|ring|)) of the evaluations of ...\n for the multi-degree ((|ind|)) and coefficient ((|c|)).\n If ((|vs|)) is omitted, it is assumed to be ((<::vars>)).\n\n If (({f})) is the polynomial over (({P})), \n (({f.map_to(P) {|c, ind| c * P.monomial(ind)}})) equals to (({f})).\n\n--- project(ring[, vs]){|c, ind| ... }\n Returns the sum over ((|ring|)) of the evaluations of ...\n on the monomial \n for the multi-degree ((|ind|)) and coefficient ((|c|)).\n\n If (({f})) is the polynomial over (({P})), \n (({f.progect(P) {|c, ind| c}})) equals to (({f})).\n\n (({project(ring){|c, ind| f(c, ind)}})) equals to (({map_to(ring){|c, ind| f(c, ind) * self.class.monomial(ind)}})).\n\n If ((|vs|)) is omitted, it is assumed to be ((<::vars>)).\n \n Example:\n require \"m-polynomial\"\n require \"rational\"\n P = Algebra::MPolynomial(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n f = x**2 + 2*x*y - z**3\n PQ = Algebra::MPolynomial(Rational, \"x\", \"y\", \"z\")\n p f.project(PQ) {|c, ind| Rational(c) / (ind[0] + 1)}\n #=> 1/3x^2 + xy - z^3\n p f.convert_to(PQ) #=> x^2 + 2xy - z^3\n\n\n--- evaluate(obj0[, [obj1, [obj2,..]]])\n Reterns the value entering ((|obj0, obj1, obj2,...|)) for each value.\n This equivalent to\n (())(({(ground, [obj0, obj1, obj2,..]){|c, ind| c}})).\n\n Example:\n require \"m-polynomial\"\n P = Algebra::MPolynomial(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n f = x**2 + 2*x*y - z**3\n p f.evaluate(1, -1, -1) #=> 0 (in Integer)\n p f.evaluate(y, z, x) #=> -x^3 + y^2 + 2yz (in P)\n\n--- call(obj0[, [obj1, [obj2,..]]])\n Same as (()).\n\n--- sub(var, value)\n Returns the value of substitution of ((|var|)) by ((|value|)).\n\n Example:\n require \"m-polynomial\"\n P = Algebra::MPolynomial(Integer)\n x, y, z = P.vars(\"x\", \"y\", \"z\")\n f = (x - y)*(y - z - 1)\n p f.sub(y, z+1) #=> 0\n\n--- convert_to(ring)\n Returns the polynomial the one converted on ((|ring|)).\n This is equivalent to (())(({(ring){|c, ind| c}})).\n\n--- derivate(var)\n Returns the partial differential by the variable (()).\n\n \n= Algebra::MPolynomial::Monomial\n(Module of Monomial)\n\nThe return value of (()) and (()) is extended by this module.\n\n== Methods:\n\n#--- ind\n#--- coeff\n#--- <=>(other)\n--- divide?(other)\n Returns true if ((|self|)) is divided by ((|other|)), which is\n assumed to be a monomial.\n\n--- /(other)\n Returns the quotient of ((|self|)) by ((|other|)), which is\n assumed to be a monomial.\n\n--- prime_to?(other)\n Returns true if ((|self|)) is prime to ((|other|)), which is\n assumed to be a monomial.\n\n--- lcm(other)\n Returns the least common multiple of ((|self|)) and (()), which is\n assumed to be a monomial.\n\n--- divide_or?(other0, other1)\n Returns the same value as ((|divide?(other0.lcm(other1))|)).\n\n= Algebra::MPolynomialFactorization\n((*(Module of Factorization)*))\n\nThe module of factorization of polynomials.\n\n== File Name:\n((|m-polynomial-factor.rb|))\n\n== Methods:\n--- factorize\n Returns the factorization.\n \n The following type can be factorized:\n * Integer\n * Rational\n * prime field\n\n= Algebra::Groebner\n(Module of Groebner Basis)\n\n== File Name:\n* ((|groebner-basis.rb|))\n* ((|groebner-basis-coeff.rb|))\n\n== Class Methods:\n\n--- Groebner.basis(f)\n Returns the array of reduced Groebner basis from the array of basis\n ((|f|)).\n Equivalent to (()).\n \n Example:\n require \"m-polynomial\"\n require \"rational\"\n P = Algebra.MPolynomial(Rational)\n P.set_ord :grevlex\n x, y, z = P.vars(\"xyz\")\n f1 = x**2 + y**2 + z**2 -1\n f2 = x**2 + z**2 - y\n f3 = x - z\n b = Groebner.basis([f1, f2, f3])\n p b #=> [y^2 + y - 1, z^2 - 1/2y, x - z]\n\n--- Groebner.basis_159A(f)\n Returns the array of Groebner basis from the array of basis\n ((|f|)).\n\n--- Groebner.minimal_basis(f)\n Returns the array of minimal Groebner basis from the array of \n Groebner basis ((|f|)).\n\n--- Groebner.reduced_basis(f)\n Returns the array of reduced Groebner basis from the array of \n minimal Groebner basis ((|f|)). \n\n--- Groebner.basis_coeff(f)\n Returns the array of Groebner basis from the array of basis\n ((|f|)) and the array of coefficients to express them.\n \n Example:\n require \"m-polynomial\"\n require \"rational\"\n P = Algebra.MPolynomial(Rational)\n P.set_ord :grevlex\n x, y, z = P.vars(\"xyz\")\n f1 = x**2 + y**2 + z**2 -1\n f2 = x**2 + z**2 - y\n f3 = x - z\n fs = [f1, f2, f3]\n c, b = Groebner.basis_coeff(fs)\n p b #=> [y^2 + y - 1, z^2 - 1/2y, x - z]\n p c #=> [[1, -1, 0], [0, 1/2, -1/2x - 1/2z], [0, 0, 1]]\n for i in 0..2\n p c[i].inner_product(fs) == b[i] #=> true\n end\n\n--- Groebner.basis?(f)\n Return true if ((|f|)) is an array of Groebner basis.\n \n--- Groebner.minimal_basis?(f)\n Return true if ((|f|)) is an array of minimal Groebner basis.\n \n--- Groebner.reduced_basis?(f)\n Return true if ((|f|)) is an array of reduced Groebner basis.\n\n \n== Methods:\n--- S_pair(other)\n Returns the S-pair of ((|self|)) and ((|other|)).\n \n Example:\n (x**2*y + y**2 + z**2 -1).S_pair(x**2*z + z**2 - y)\n #=> y^2z + y^2 - yz^2 + z^3 - z\n\n--- divmod_s(f1[, f2[, f3...]])\n Returns a array (({[[q1, q2, q3, ...], r]})) \n of the array of quotients (coefficients of division) \n and the remainder of division of ((|self|)) by \n basis (({f1, f2, f3, ...})).\n \n We convert (({f1, f2, f3, ...})) into Groebner basis and make the division.\n So (({divmod(f1, f2, ...).last == 0})) is equivalent to that ((|self|))\n is in the ideal (({(f1, f2, ...)})).\n \n Example:\n require \"m-polynomial\"\n require \"rational\"\n P = Algebra.MPolynomial(Rational)\n P.set_ord :grevlex\n x, y, z = P.vars(\"xyz\")\n f1 = x**2 + y**2 + z**2 -1\n f2 = x**2 + z**2 - y\n f3 = x - z\n fs = [f1, f2, f3]\n f = x**3 + y**3 + z**3\n c, r = f.divmod_s(*fs)\n p r #=> yz + 2y - 1\n p c #=> [y - 1, -y + z + 1, x^2]\n p f == c.inner_product(fs) + r #=> true\n\n--- div_cg(f, cg)\n Returns (({[q, r]})) where q (quotients) and\n r (remain) of division, which are obtained from the basis\n ((|f|)) and (({cg}))=(())(f).\n (())(f) returns \n (({div_cg(f, Groebner.basis_coeff(f))})).\n\n=end\n\n", "meta": {"hexsha": "2a7e3a583bc933c87382e55db4a72ecd73680ef4", "size": 17170, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/m-polynomial.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/m-polynomial.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/m-polynomial.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.3801652893, "max_line_length": 120, "alphanum_fraction": 0.5426324985, "num_tokens": 5770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.672368270238808}} {"text": "=begin\n # sample-quotientfield02.rb\n\n require \"algebra\"\n \n F13 = ResidueClassRing(Integer, 13)\n \n P = Polynomial(F13, \"x\")\n Q = LocalizedRing(P)\n x = Q[P.var]\n p ( 1 / (x**2 - 1) - 1 / (x**3 - 1) )\n \n #This is equivalent to the following\n F = RationalFunctionField(F13, \"x\")\n x = F.var\n p ( 1 / (x**2 - 1) - 1 / (x**3 - 1) )\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "0e7bfc267f0ccc584e8c2d71eb1d88aef2521b42", "size": 361, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-quotientfield02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-quotientfield02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-quotientfield02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 19.0, "max_line_length": 39, "alphanum_fraction": 0.5457063712, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.672312556301899}} {"text": "###############################################################################\r\n# Pessismistic Open Field RL algorithm\r\n# \r\n# From Figure 1, Zorowitz et al. (2020)\r\n# Translated from Python to R\r\n# See https://github.com/ndawlab/seqanx for the original code\r\n# \r\n# Value iteration \r\n# \r\n###############################################################################\r\n\r\nlibrary(pheatmap)\r\nlibrary(proxy)\r\nlibrary(dplyr)\r\nlibrary(RColorBrewer)\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Define parameters.\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n\r\n# Variables\r\nreward = 10\r\npunishment = -10\r\nepsilon = 0\r\nstart = 116\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Environment setup and visualization.\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n\r\n# Initialize environment:\r\nsize <- 11\r\ngrid <- matrix(0, nrow = size, ncol = size)\r\ngrid[2,3] <- reward # number 14\r\ngrid[2,9] <- punishment # number 20\r\n\r\n# Visualize environment:\r\npheatmap::pheatmap(grid, legend = FALSE, cluster_col = FALSE, cluster_row = FALSE,\r\n display_numbers = TRUE, color = colorRampPalette(brewer.pal(n = 7, name = \"RdYlBu\"))(100))\r\n\r\n# Identify coordinates of viable states:\r\nviable_coordinates = data.frame(x = rep(1:size, each = size), y = rep(1:size))\r\n\r\n# Make transition matrix with NA's and 1's:\r\ntransition_matrix <- proxy::dist(viable_coordinates, viable_coordinates, method = \"Euclidean\")\r\ntransition_matrix <- ifelse(transition_matrix == 1, 1, NA)\r\n\r\ntransition_matrix[14,] <- NA\r\ntransition_matrix[20,] <- NA\r\ntransition_matrix[14,14] <- 1\r\ntransition_matrix[20,20] <- 1\r\n\r\n# Define rewards:\r\nR <- matrix(0, nrow = size*size, ncol = size*size)\r\nR[,14] <- reward; R[14,14] <- 0\r\nR[,20] <- punishment; R[20,20] <- 0\r\nR <- ifelse(transition_matrix == 1, R, NA)\r\n\r\n# Define state information:\r\nstates <- 1:(size*size)\r\nn_states <- length(states)\r\nviable_states <- states[-c(14,20)] # viable states are states minus terminal states\r\nn_viable_states <- length(viable_states)\r\n\r\n# Iteratively define MDP information:\r\ninfo <- data.frame(S = 0, S_prime = 0, R = 0)\r\nindex = 1\r\nfor (s in 1:n_states) {\r\n\r\n # What are the possible next states?\r\n s_prime = which(transition_matrix[s,] %in% 1) # check on which position are the ones\r\n\r\n # What are the rewards for these next states?\r\n r = R[s, s_prime]\r\n\r\n # What is the probability of transitioning to next state? \r\n # t = 1 # determinisitic \r\n\r\n for (i in 1:length(s_prime)) {\r\n info[index,1] = s; info[index,2] <- s_prime[i]; info[index,3] <- r[i]\r\n index = index + 1\r\n }\r\n}\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n# Value iteration and visualization.\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#\r\n\r\n# Function: Pessimism\r\npessimism <- function(arr, w) { \r\n return(w * max(arr) + (1 - w) * min(arr))\r\n}\r\n\r\n# Simulation parameters:\r\nweights <- c(1, 0.5, 0)\r\ngamma = 0.95\r\ntol = 0.0001\r\nmax_iter = 100\r\n\r\n# Initialize value iteration:\r\nfor (weight in weights) {\r\n \r\n # Initialize Q-values:\r\n Q <- matrix(rep(0, nrow(info)), ncol = 1) # Q is the expected reward for every possible transition\r\n copy <- info \r\n \r\n # Solve for Q-values:\r\n for (i in 1:max_iter) {\r\n \r\n # Make copy:\r\n q <- Q\r\n copy$Q <- q\r\n \r\n # Precompute successor value: \r\n V_prime <- c()\r\n for (s in 1:(size*size)) {\r\n arr <- copy %>% filter(S == s)\r\n V_prime[s] <- pessimism(arr$Q, weight) # V_prime is the value function for every possible state given the policy \r\n }\r\n \r\n # Compute Q-values:\r\n for (i in 1:nrow(info)) {\r\n Q[i] <- info$R[i] + gamma * V_prime[info$S_prime[i]]\r\n }\r\n \r\n # Compute delta:\r\n delta <- abs(Q - q) \r\n \r\n # Check for termination (i.e., all values of delta below threshold):\r\n if (all((delta < tol) == TRUE)) { break } \r\n }\r\n \r\n # Solve for values:\r\n copy = info\r\n copy$Q = Q\r\n \r\n # Identify max by state:\r\n V <- c()\r\n for (s in 1:(size*size)) {\r\n arr <- copy %>% filter(S == s)\r\n V[s] <- max(arr$Q) # V is the max value function for every possible state given the policy \r\n }\r\n \r\n # Fill in terminal states:\r\n grid_pessism <- matrix(V, nrow = size, ncol = size, byrow = TRUE)\r\n grid_pessism[2,3] = reward\r\n grid_pessism[2,9] = punishment\r\n \r\n # Visualize environment:\r\n pheatmap::pheatmap(grid_pessism, legend = FALSE, cluster_col = FALSE, cluster_row = FALSE,\r\n display_numbers = TRUE, color = colorRampPalette(brewer.pal(n = 7, name = \"RdYlBu\"))(100), \r\n main = paste0(\"Weight: \", weight)) \r\n \r\n # Compute policy: \r\n policy <- c()\r\n policy[1] <- s <- start\r\n i = 1\r\n while ( s != 14 && s != 20) {\r\n \r\n # Compute optimal q(s, a):\r\n temp <- copy %>% filter(S == s)\r\n s <- temp$S_prime[which.max(temp$Q)]\r\n \r\n # Append it to policy\r\n policy <- c(policy, s)\r\n \r\n # Make sure it doesn't get stuck: \r\n i = i + 1\r\n if (i > 100) { break }\r\n }\r\n}\r\n\r\n", "meta": {"hexsha": "92f0b4ac245f6aebd95a1c430a0231accd3801ed", "size": 4909, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Pessimistic_RL.r", "max_stars_repo_name": "ndawlab/seqanx", "max_stars_repo_head_hexsha": "de44aa1baeb10646d538c185f0428d53b00db4b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-04-12T21:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:45:44.000Z", "max_issues_repo_path": "R/Pessimistic_RL.r", "max_issues_repo_name": "ndawlab/seqanx", "max_issues_repo_head_hexsha": "de44aa1baeb10646d538c185f0428d53b00db4b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-26T10:07:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-26T16:23:34.000Z", "max_forks_repo_path": "R/Pessimistic_RL.r", "max_forks_repo_name": "ndawlab/seqanx", "max_forks_repo_head_hexsha": "de44aa1baeb10646d538c185f0428d53b00db4b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-06T21:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-06T21:29:52.000Z", "avg_line_length": 28.3757225434, "max_line_length": 120, "alphanum_fraction": 0.5522509676, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6721072468500328}} {"text": "# Getting Started in Fixed/Random Effects Models Using R.\n# Oscar Torres-Reyna, Princeton University.\n\n# Load Required Packages:\n require(foreign); library(foreign)\n require(car); library(car)\n require(gplots); library(gplots)\n\n# Read Data Examples from Web or Local System:\n Panel <- read.dta(\"http://dss.princeton.edu/training/Panel101.dta\")\n Panel <- read.dta(file = \"C:\\\\Users\\\\Pooya\\\\OneDrive\\\\MyThesis\\\\MyTutorials\\\\Panel_Data_using_R\\\\Data_Examples\\\\Data.dta\")\n Panel <- read.csv(file = \"C:\\\\Users\\\\Pooya\\\\OneDrive\\\\MyThesis\\\\MyTutorials\\\\Panel_Data_using_R\\\\Data_Examples\\\\Data.csv\", header = TRUE, sep = ',')\n\n# Exploring Panel Data:\n coplot(formula = y ~ year | country, data = Panel, type = \"l\")\n scatterplot(y ~ year | country, data = Panel, boxplot = FALSE, smooth = TRUE, reg.line = FALSE)\n \n# Fixed Effects: Plot Heterogeneity across Countries:\n plotmeans(formula = y ~ country, data = Panel, main = \"Heterogeineity across Countries\")\n \n# Fixed Effects: Plot Heterogeneity across Years\n plotmeans(formula = y ~ year, data = Panel, main = \"Heterogeineity across Years\")\n\n# OLS Regression:\n View(Panel)\n # y ~ x1:\n plot(x = Panel$x1, y = Panel$y, type = \"p\", xlab = \"x\", ylab = \"y\", pch = 19, col = \"green\")\n OLS <- lm(formula = y ~ x1, data = Panel)\n abline(OLS, lwd = 3, col = \"green\", lty = 2)\n summary(OLS)\n # y ~ x2:\n par(new = TRUE)\n plot(x = Panel$x2, y = Panel$y, type = \"p\", xlab = \"x\", ylab = \"y\", pch = 19, col = \"red\")\n OLS <- lm(formula = y ~ x2, data = Panel)\n abline(OLS, lwd = 3, col = \"red\", lty = 2)\n summary(OLS)\n # y ~ x3:\n par(new = TRUE)\n plot(x = Panel$x3, y = Panel$y, type = \"p\", xlab = \"x\", ylab = \"y\", pch = 19, col = \"blue\")\n OLS <- lm(formula = y ~ x3, data = Panel)\n abline(OLS, lwd = 3, col = \"blue\", lty = 2)\n summary(OLS)\n # y ~ x1 + x2 + x3:\n par(new = TRUE)\n OLS <- lm(formula = y ~ x1 + x2 + x3, data = Panel)\n abline(OLS, lwd = 3, col = \"black\", lty = 2)\n summary(OLS)\n\n# Fixed Effects Using Least Squares Dummy Variable Model:\n fixed.dum <- lm(y ~ x1 + x2 + x3 + factor(country) - 1, data = Panel)\n summary(fixed.dum)\n\n\n \n \n \n \n \n \n \n \n# Why Intercept Ignore: fixed.dum <- lm(y ~ x1 + factor(country), data = Panel)\n\nyhat <- fixed.dum$fitted.values\n\nscatterplot(yhat ~ Panel$x1 | Panel$country, boxplot = FALSE, xlab = \"x1\", ylab = \"yhat\", smooth = FALSE)\nabline(lm(Panel$y ~ Panel$x1), lwd = 3, col = \"red\")\n\n# Comparing OLS vs LSDV model: ----------------------------------------------------------------\n\napsrtable(ols, fixed.dum, model.names = c(\"OLS\", \"OLS_DUM\"))\n\n# Fixed effects: n entity-specific intercepts (using plm): ------------------------------------\n\nfixed.individual <- plm(formula = y ~ x1 + x2 + x3, data = Panel, index = c(\"country\", \"year\"), model = \"within\", effect = \"individual\")\nsummary(fixed.individual)\n\nfixed.time <- plm(formula = y ~ x1 + x2 + x3, data = Panel, index = c(\"country\", \"year\"), model = \"within\", effect = \"time\")\nsummary(fixed.time)\n\nfixed.twoways <- plm(formula = y ~ x1 + x2 + x3, data = Panel, index = c(\"country\", \"year\"), model = \"within\", effect = \"twoways\")\nsummary(fixed.twoways)\n\n# Extracts the fixed effects from a plm object: Fixed Effects (constants for each coun --------\n\nfixef(fixed.individual)\nfixef(fixed.time)\nfixef(fixed.twoways, effect = \"time\")\n\n# F Test for Individual and/or Time Effects: Testing for fixed effects, null - OLS better -----\n# than fixed (If the p-value is < 0.05 then the fixed effects model is a better choice)\n\npFtest(fixed.individual,ols)\npFtest(fixed.time, ols)\npFtest(fixed.twoways, ols)\n\n# RANDOM-EFFECTS MODEL: -----------------------------------------------------------------------\n\nrandom <- plm(formula = y ~ x1 + x2 + x3, data = Panel, effect = \"individual\", model =\"random\", index = c(\"country\", \"year\"))\nsummary(random)\n\n# Fixed or Random: Hausman Test ---------------------------------------------------------------\n\nphtest(fixed.individual, random)\n\n# Testing for Time-Fixed Effects --------------------------------------------------------------\nfixed.time.dummy <- plm(formula = y ~ x1 + x2 + x3 + factor(year), data = Panel, model =\"within\", index = c(\"country\", \"year\"))\nsummary(fixed.time.dummy)\n\n# Testing time-fixed effects: The null is that no time-fixed effects needed ------------------\n\npFtest(fixed.time.dummy, fixed.individual)\n\n# Lagrange Multiplier Test - time effects (Breusch-Pagan): ------------------------------------\n\nplmtest(fixed.individual, c(\"time\"), type = (\"bp\"))\n\n# Testing for random effects: Breusch-Pagan Lagrange multiplier (LM) --------------------------\n\npool <- plm(formula = y ~ x1 + x2 + x3, data = Panel, index = c(\"country\", \"year\"), effect = \"individual\", model = \"pooling\")\nsummary(pool)\n\n# Breusch-Pagan Lagrange Multiplier for random effects. Null is no panel effect (i.e. --------\n\nplmtest(pool, type = c(\"bp\"))\n\n# Testing for cross-sectional dependence/contemporaneous correlation: -------------------------\n# using Breusch-Pagan LM test of independence and Pasaran CD test.\n# The null hypothesis in the B-P/LM and Pasaran CD tests of independence is that residuals across entities are not correlated.\n\npcdtest(fixed.individual, test = c(\"lm\"))\n\npcdtest(fixed.individual, test = c(\"cd\"))\n\n# Testing for serial correlation --------------------------------------------------------------\n# The null is that there is not serial correlation:\n\npbgtest(fixed.individual)\n\n# Testing for unit roots/stationarity ---------------------------------------------------------\n# The Dickey-Fuller test to check for stochastic trends\n# The null hypothesis is that the series has a unit root (i.e. non-stationary).\n\nPanel.set <- plm.data(Panel, index = c(\"country\", \"year\"))\nadf.test(Panel.set$y, k = 2)\n\n# Testing for heteroskedasticity: -------------------------------------------------------------\n\n\n\n\n", "meta": {"hexsha": "59237d2df4d310c4634ac8e1d6da974264fbed9b", "size": 5825, "ext": "r", "lang": "R", "max_stars_repo_path": "Code.r", "max_stars_repo_name": "jngod2011/Panel-Data-Using-R", "max_stars_repo_head_hexsha": "952e20c1c111051da7fb92c27936554ef75c5003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-04T19:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T23:14:51.000Z", "max_issues_repo_path": "Code.r", "max_issues_repo_name": "jngod2011/Panel-Data-Using-R", "max_issues_repo_head_hexsha": "952e20c1c111051da7fb92c27936554ef75c5003", "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": "jngod2011/Panel-Data-Using-R", "max_forks_repo_head_hexsha": "952e20c1c111051da7fb92c27936554ef75c5003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-04T02:59:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T19:17:55.000Z", "avg_line_length": 38.3223684211, "max_line_length": 150, "alphanum_fraction": 0.6017167382, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6720069929106194}} {"text": "muX <- 3.68\nsigma1 <- 0.64\n\nmuY <- 4.8\nsigma2 <- 0.49\n\ndomanda1 <- 9.51\n\nmuSomma <- muX + muY\nsigmaQuadratoSomma <- sigma1^2 + sigma2^2\nsigmaSomma <- sqrt(sigmaQuadratoSomma)\n\nrisposta1 <- pnorm(domanda1, muSomma, sigmaSomma, FALSE);\n\nrisposta2 <- sigmaQuadratoSomma / ((domanda1-muSomma)^2)\n\nprint(risposta1)\nprint(risposta2)\n", "meta": {"hexsha": "159bdd89903af321d441cd6916a1711af7a855b5", "size": 327, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 51.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 51.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 51.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": 17.2105263158, "max_line_length": 57, "alphanum_fraction": 0.7094801223, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6718824933196947}} {"text": "x1 <- 18.91\nx2 <- 22.81\n\nprMinore <- 6/100\nprMaggiore <- 7/100\n\npr2C <- 1-prMaggiore\n\npr3 <- 10/100\n\nx4 <- 4.64\n\nq1 <- qnorm(prMinore)\nq2 <- qnorm(pr2C)\n\nmu <- ((-q2*x1)/q1 + x2)/(1-q2/q1);\n\nsigma <- (x1-mu)/q1;\n\nrisposta4 <- pnorm(x4^2, mu, sigma);\n\nprint(mu)\n\nprint(sigma);\n\nq1 <- qnorm(1-pr3);\n\nrisposta3 <- (x2 - mu)/q1\n\nprint(risposta3)\n\nprint(risposta4)\n", "meta": {"hexsha": "97e40805250c41dcf3f02f7c00b2c14adeaa3c7b", "size": 360, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 44.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 44.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 44.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": 10.9090909091, "max_line_length": 36, "alphanum_fraction": 0.5916666667, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6718108145307019}} {"text": "johnson_tol <- function(xall, alpha=0.01, P=0.99, side=1) {\r\n\r\n ## xall = data set\r\n ## alpha = 1 - confidence\r\n ## P = pvalue = coverage (tolerance interval only)\r\n pvalue <- P\r\n \r\n ## install.packages('tolerance')\r\n library(tolerance)\r\n ## install.packages('SuppDists')\r\n library(SuppDists)\r\n\r\n ## Johnson distribution calculations from SuppDists package\r\n jparms <- JohnsonFit(xall)\r\n ## transform xall dataset to normally distributed z using Johnson distribution\r\n zall <- john_z(xall, jparms)\r\n df <- as_tibble( data.frame(x=xall, z=zall) )\r\n\r\n na_rows <- df[is.na(df$z),]\r\n if (nrow(na_rows) != 0) {\r\n\r\n ## z values could not be calculated for all x values\r\n cat('\\n')\r\n cat('##############################\\n')\r\n cat(' ERROR IN JOHNSON_TOL \\n')\r\n cat(' z(x) = NA for some x values \\n')\r\n cat('##############################\\n')\r\n print(jparms)\r\n print(na_rows)\r\n ztol_out <- normtol.int(zall, alpha = alpha, P=pvalue, side=side)\r\n ztol_upper <- NA\r\n xtol_upper <- NA\r\n \r\n } else {\r\n \r\n ## johnson fit returned z values for all x values so possibly a decent fit\r\n\r\n ## xz_plot <- plot(xall, zall)\r\n \r\n ## define function to find x for a given z\r\n ## zero <- function(x, parms=jparms, ztarget) john_z(x, parms) - ztarget\r\n zero <- function(x, parms, z) john_z(x, parms) - z\r\n \r\n ## check use of uniroot\r\n ## xcheck <- 13\r\n ## ztarget <- john_z(xcheck)\r\n ## ztox <- uniroot(zero, lower=min(xall), tol=1E-10, upper=2*max(xall), ztarget=ztarget)$root\r\n ## x_from_z <- uniroot(zero, ztarget=ztarget,\r\n ## lower=min(xall), upper=2*max(xall), tol=1E-10)$root\r\n \r\n ## find tolerance limits using normal distribution calculations on z\r\n ztol_out <- normtol.int(zall, alpha = alpha, P=pvalue, side=side)\r\n xmin <- min(xall)\r\n xmax <- max(xall)\r\n if (side == 1) {\r\n ztol_upper <- ztol_out$'1-sided.upper'\r\n ztol_lower <- ztol_out$'1-sided.lower'\r\n } else if (side == 2) {\r\n ztol_upper <- ztol_out$'2-sided.upper'\r\n ztol_lower <- ztol_out$'2-sided.lower'\r\n }\r\n\r\n ## transform z back to u\r\n ## uniroot is not very robust so try newton raphson\r\n ## xrange <- max(xall) - min(xall)\r\n ## xtol_upper <- uniroot(zero, ztarget=ztol_upper,\r\n ## lower=xmax, upper=xmax + xrange, tol=1E-10)$root\r\n\r\n if (jparms$type == 'SB') {\r\n ## Not sure tolerance limits have meaning for a bounded fit\r\n xtol_lower <- NA\r\n xtol_upper <- NA\r\n } else {\r\n ## Tolerance limits should have meaning for SU and SN\r\n ## Upper tolerance limit should have meaning for SL\r\n xtol_upper <- newton.raphson(zero, parms=jparms, z=ztol_upper, xguess=mean(xall), tol=1E-10)\r\n if (jparms$type == 'SL') {\r\n xtol_lower <- NA\r\n } else {\r\n xtol_lower <- newton.raphson(zero, parms=jparms, z=ztol_lower, xguess=mean(xall), tol=1E-10)\r\n }\r\n }\r\n }\r\n return(list(xz=df, jparms=jparms, ztol_out=ztol_out, \r\n ztol_upper=ztol_upper, xtol_upper=xtol_upper,\r\n ztol_lower=ztol_lower, xtol_lower=xtol_lower))\r\n}\r\n\r\n## ## test\r\n##\r\n## set.seed(1)\r\n## x <- rnorm(n=1E5, mean=10, sd=1)\r\n## tol_out_john <- johnson_tol(x, alpha=0.1, P=0.99, side=1)\r\n## jparms <- tol_out_john$jparms\r\n## ztol_upper <- tol_out_john$ztol_upper\r\n## ztol_upper\r\n## upper_tolerance_limit_john <- tol_out_john$xtol_upper$`root approximation`\r\n## upper_tolerance_limit_john\r\n## \r\n## xz <- tol_out_john$xz\r\n## plotspace(1,3)\r\n## hist(xz$x)\r\n## hist(xz$z)\r\n## plot(xz$x, xz$z)\r\n", "meta": {"hexsha": "b14f2b9bb00e5c6af5aa33344c61db4c9a3432ef", "size": 3963, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/johnson_tol.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/johnson_tol.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/johnson_tol.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "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.7428571429, "max_line_length": 109, "alphanum_fraction": 0.5354529397, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6716835520393927}} {"text": "designBased = function(gamma, outcome_vec, pcf_cat_vec, instid_vec){\r\n\t#' Compute Design Based Draper-Gittoes Z-Scores\r\n\t#'\r\n\t#'\t\\code{designBased} implements design based approach and\r\n\t#' computes O, E, and z vectors following Draper-Gittoes (2004)\r\n\t#'\r\n\t#' @param gamma Parameter in [0,1] controling pooling.\r\n\t#' Gamma = 1 is complete global pooling, gamma = 0 is complete local pooling.\r\n\t#' @param outcome_vec Vector with elements in {0,1} denoting the binary outcome.\r\n\t#' @param pcf_cat_vec Vector with unique values for each PCF category.\r\n\t#' @param instid_vec Vector with unique values for each institution.\r\n\tstopifnot( all( outcome_vec %in% c(0,1)) )\t\r\n\t#Some of the inputs need to be factors\r\n\tpcf_cat_vec = as.factor(pcf_cat_vec)\r\n\tinstid_vec = as.factor(instid_vec)\r\n\t\r\n\t#Summarize\r\n\tinstid_unique = levels(instid_vec)\r\n\tn_students = length(outcome_vec)\r\n\tn_u = length(levels(instid_vec))\r\n\tn_cat = length(levels(pcf_cat_vec))\r\n\tp_global = mean(outcome_vec)\r\n\t#Compute Table 2 in Draper-Gittoes\r\n\ty_mat = n_mat = matrix(0, nrow =n_u, ncol = n_cat)\r\n\r\n\tfor (i in 1:n_students){\r\n inst = as.integer(instid_vec[i])\r\n categ = as.integer(pcf_cat_vec[i])\r\n n_mat[inst,categ] = n_mat[inst,categ] + 1\r\n y_mat[inst, categ] = y_mat[inst, categ] + outcome_vec[i]\r\n\t} \r\n\tp_mat = y_mat / n_mat\r\n\tp_mat[n_mat == 0] = 0\r\n\t\r\n\t#Marginal summaries\r\n\tpcf_p_vec = apply(y_mat, 2, sum) / apply(n_mat, 2, sum)\r\n\tn_u_vec = apply(n_mat, 1, sum)\r\n\tn_cat_vec = apply(n_mat, 2, sum)\r\n\r\n\t#Equation (2) in Draper-Gittoes (2004)\r\n\tO = apply(y_mat, 1, sum) / apply(n_mat, 1, sum)\r\n\t#Equation (3) in D-G\r\n\tE = apply(t(t(n_mat) * pcf_p_vec), 1, sum) / n_u_vec\r\n\t#Equation (4) in D-G\r\n\tD = O - E\r\n\t\r\n\t#Variance\r\n\tlambdaFun = function(i,k,j){\r\n\t\t#Equation (7) in D-G\r\n\t\tif (i == k){\r\n\t\t\treturn(n_mat[i,j]/n_u_vec[i] * (1 - (n_mat[i,j]/n_cat_vec[j])))\r\n\t\t} else{\r\n\t\t\treturn( -1 * (n_mat[i,j] * n_mat[k,j]) / (n_u_vec[i] * n_cat_vec[j]) )\r\n\t\t}\r\n\t}\r\n\tvFun = function(k,j, gamma = 0.5){\r\n\t\t#Equation (11) in D-G\r\n\t\tn = n_mat[k,j]\r\n\t\tpcomb = function(p_local){gamma * p_global + (1-gamma) * p_local}\r\n\t\tif (n > 0){\r\n\t\t\tp_local = p_mat[k, j]\r\n\t\t\tp_star = pcomb(p_local)\r\n\t\t\treturn(p_star * (1-p_star)/n)\r\n\t\t} else {\r\n\t\t\treturn(0)\r\n\t\t}\r\n\t}\r\n\tcomputeVi = function(i, gamma){\r\n\t\t#Equation (8) in D-G\r\n\t\tv = 0\r\n\t\tfor (k in 1:n_u){\r\n\t\t\tfor (j in 1:n_cat){\r\n\t\t\t\tv = v + lambdaFun(i,k,j)^2 * vFun(k, j, gamma)\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn(v)\r\n\t}\r\n\t#Now compute w/ lapply\r\n\tV = sapply(1:n_u, computeVi, gamma)\r\n\tSE = sqrt(V)\r\n\t\r\n\tZ = (O - E) / SE\r\n\t\r\n\tout_df = data.frame(\r\n\t\t\tinst = as.numeric(as.character(instid_unique)),\r\n\t\t\teffect = O-E,\r\n\t\t\tO = O,\r\n\t\t\tE = E,\r\n\t\t\tD = D,\r\n\t\t\tSE = SE,\r\n\t\t\tZ = Z,\r\n\t\t\tn = n_u_vec\t\r\n\t)\r\n\treturn( out_df[order(out_df$inst), ])\r\n}\r\n", "meta": {"hexsha": "2815495556376ec5ec66b3f5c2d2ae0939536228", "size": 2739, "ext": "r", "lang": "R", "max_stars_repo_path": "R/designBased.r", "max_stars_repo_name": "dhelkey/babymonitor", "max_stars_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "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/designBased.r", "max_issues_repo_name": "dhelkey/babymonitor", "max_issues_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "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/designBased.r", "max_forks_repo_name": "dhelkey/babymonitor", "max_forks_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "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.53125, "max_line_length": 82, "alphanum_fraction": 0.6181087988, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6715914991529696}} {"text": "# A matrix is a collection of elements of the same data type (numeric, character, or logical) \n# arranged into a fixed number of rows and columns. Since you are only working with rows and columns, \n# a matrix is called two-dimensional.\n\n# Construct a matrix with 3 rows that contain the numbers 1 up to 9\nmatrix(1:9, byrow=TRUE, nrow=3)\n\n# byrow: indicates that the matrix is filled by row. For columns use param of FALSE\n# nrow: indicates the number of rows to fill\n\n# Box office Star Wars (in millions!)\nnew_hope <- c(460.998, 314.4)\nempire_strikes <- c(290.475, 247.900)\nreturn_jedi <- c(309.306, 165.8)\n\n# Create box_office\nbox_office <- c(new_hope, empire_strikes, return_jedi)\n\n# Construct star_wars_matrix\nstar_wars_matrix <- matrix(box_office, byrow=TRUE, nrow=3)\n", "meta": {"hexsha": "ca635a874d1d4a82bef98955f964b742f010a388", "size": 772, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DataAnalyst/Basics/matrix-create.r", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/matrix-create.r", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/matrix-create.r", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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.7619047619, "max_line_length": 102, "alphanum_fraction": 0.7512953368, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6712193182795959}} {"text": "# calculate probability in normal distribution with R\r\n# variable y with normal distribution N(??, ??), where ??=20 and ?? = 2\r\n# pnorm function gives the probability of a normally distributed random number to be less that the value of a given number.\r\n# the probability that a measurement will be less than 23 is given by \r\npnorm(23,mean =20,sd=2)\r\n", "meta": {"hexsha": "1a054f3025d37cf5a6ffe230c716cbda200bcb1a", "size": 352, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.15/Ex4_15.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.15/Ex4_15.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.15/Ex4_15.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 58.6666666667, "max_line_length": 124, "alphanum_fraction": 0.7357954545, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6711364592672971}} {"text": "#---------------------------------------------------------------------\n# nn_norm -- Utility function for normalizing matrices for neural\n# network analyses.\n#\n# Usage: normed_mat <- nn_norm(input, [type=c(\"mm\",\"z\")], [alt=normed_mat])\n#\n# Args:\n# input -- An input vector or matrix to be normalized by columns.\n# type -- One of \"mm\" for min-max normalization or \"z\" for z-scores\n# alt -- An already normalized matrix with the same number of columns\n# as the input from which the scaling and offset are used.\n#\n# Description:\n# By default, nn_norm applies min-max scaling to the input matrix and\n# returns a normalized copy of the input. The offset and scaling factor\n# used for normalization are returned as attributes of the output \n# matrix, specifically \"nn_norm:offset\" and \"nn_norm:scale\". These\n# attributes can then be used to restore the original matrix, or used\n# to apply equivalent normalization to another matrix when passed as\n# the alt argument.\n#\n# See nn_unnorm for the inverse of this.\n#\n# Author: Bunnell -- 1/4/20\n#----------------------------------------------------------------------\nnn_norm <- function(inp, type=\"mm\", alt=NULL) {\n#\n# Calculate or assign scale and offset\n#\n if (is.null(alt)) {\n if (type == \"mm\") {\n #cat(\"scale MM\\n\")\n if (is.null(dim(inp))) {\n coff <- min(inp)\n cscl <- max(inp) - coff\n if (cscl == 0) {\n cscl = 1\n }\n } else {\n cmax <- apply(inp, 2, max)\n coff <- apply(inp, 2, min)\n cscl <- cmax - coff\n j <- which(cscl == 0 | is.nan(cscl) | is.na(cscl))\n cscl[j] <- 1\n }\n } else {\n #cat(\"scale Z\\n\")\n if (is.null(dim(inp))) {\n coff <- mean(inp)\n cscl <- sd(inp)\n if (cscl == 0 || is.na(cscl) || is.nan(cscl))\n cscl = 1\n } else {\n cscl <- apply(inp, 2, sd)\n coff <- apply(inp, 2, mean)\n j <- which(cscl == 0 | is.nan(cscl) | is.na(cscl))\n cscl[j] <- 1\n }\n }\n } else {\n #cat(\"alt scaling\\n\")\n coff <- attr(alt, \"nn_norm:offset\")\n cscl <- attr(alt, \"nn_norm:scale\")\n }\n#\n# Apply the scaling\n#\n if (is.null(dim(inp))) { # Must be a vector\n oup <- (inp - coff) / cscl\n } else {\n oup <- t((t(inp) - coff) / cscl)\n }\n#\n# Save scaling parameters as attributes\n#\n attr(oup, 'nn_norm:offset') = coff\n attr(oup, 'nn_norm:scale') = cscl\n\n oup\n}\n\n#---------------------------------------------------------------------\n# nn_unnorm -- Utility function to undo normalization that was applied\n# to a matrix or vector.\n#\n# Usage: matrix <- nn_unnorm(input, [alt=normed_mat])\n#\n# Args:\n# input -- An previously normalized input vector or matrix or similar\n# object that is presumed to be in the normalized space of\n# another object passed as the alt argument.\n# alt -- An already normalized matrix with the same number of columns\n# as the input from which the scaling and offset are used.\n#\n# Description:\n# By default, nn_unnorm uses the attributes of the input matrix to\n# recover the offset and scaling parameters and applies the inverse\n# operation to restore the original unnormalized matrix.\n#\n# If the alt argument is provided, nn_unnorm instead uses the\n# scaling attributes from the alt matrix to apply to the input matrix.\n#\n# See nn_norm for the inverse of this.\n#\n# Author: Bunnell -- 1/4/20\n#----------------------------------------------------------------------\n#\nnn_unnorm <- function(inp, alt=NULL) {\n if (is.null(alt)) {\n coff <- attr(inp, \"nn_norm:offset\")\n cscl <- attr(inp, \"nn_norm:scale\")\n } else {\n coff <- attr(alt, \"nn_norm:offset\")\n cscl <- attr(alt, \"nn_norm:scale\")\n }\n\n if (is.null(dim(inp))) {\n oup <- cscl * inp + coff\n } else {\n oup <- t((t(inp) * cscl) + coff)\n }\n\n oup\n}", "meta": {"hexsha": "0066155b57586eb2296977914ca01ce130f8b616", "size": 3856, "ext": "r", "lang": "R", "max_stars_repo_path": "R/nn_norm.r", "max_stars_repo_name": "NemoursResearch/FormantTracking", "max_stars_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:47:04.000Z", "max_issues_repo_path": "R/nn_norm.r", "max_issues_repo_name": "NemoursResearch/FormantTracking", "max_issues_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "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/nn_norm.r", "max_forks_repo_name": "NemoursResearch/FormantTracking", "max_forks_repo_head_hexsha": "7053e6add8672dc00aa70f6549d90ff935f96748", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T18:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T18:20:28.000Z", "avg_line_length": 31.0967741935, "max_line_length": 76, "alphanum_fraction": 0.5619813278, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.6709219710909496}} {"text": "#' @title quantile_to_normal\n#' @description convert quantile to normal with mean 0.5 and variance such that ci% are found within the range (0,1)\n#' @family abysmally documented\n#' @author Jae Choi, \\email{jae.choi@@dfo-mpo.gc.ca}\n#' @export\nquantile_to_normal = function( x, mean =0.5, ci=0.999 ) {\n \n xmin = min( x[ which(x>0) ], na.rm=T )\n xmax = max( x[ which(x<1) ], na.rm=T )\n \n pr = (1 - ci) / 2 # one-tailed prob in normal approximation desired\n zsd = 2 * abs( qnorm( pr, mean=0, sd=1) ) # range in x required to have ci% of the population, two tailed\n rsd = 1 / zsd # sd required for population to fit in (0,1)\n\n zscore = qnorm( x, mean=mean, sd=rsd )\n \n xx = which( x>=1 | zscore > 1) \n if (length(xx) > 0 ) zscore[ xx ] = 1\n \n nn = which( x<=0 | zscore < 0) \n if (length(nn) > 0 ) zscore[ nn ] = 0 \n\n return (zscore) \n}\n\n\n", "meta": {"hexsha": "368a03f6344619b83a35e247dc1318f6c5d553de", "size": 850, "ext": "r", "lang": "R", "max_stars_repo_path": "R/quantile_to_normal.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/quantile_to_normal.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/quantile_to_normal.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.4814814815, "max_line_length": 116, "alphanum_fraction": 0.6141176471, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6708173012625817}} {"text": "library(MASS);\r\n\r\nintervallo1 <- c(0,9)\r\nintervallo2 <- c(9,16)\r\n\r\nk_coeffs <- c(1, -1/7);\r\n\r\ndomanda3 <- 9\r\n\r\nk <- 1\r\ndensity1 <- function(x){\r\n \r\n k*k_coeffs[1]\r\n \r\n}\r\n\r\ndensity2 <- function(x){\r\n \r\n k*k_coeffs[2]*(x-intervallo2[2]);\r\n \r\n}\r\n\r\nass1 <- function(x){\r\n \r\n x*k*k_coeffs[1];\r\n \r\n}\r\n\r\nass2 <- function(x){\r\n \r\n x*k*k_coeffs[2]*(x-16)\r\n \r\n}\r\n\r\nintegral1 <- integrate(Vectorize(density1), lower = intervallo1[1], upper = intervallo1[2])\r\nintegral2 <- integrate(Vectorize(density2), lower = intervallo2[1], upper = intervallo2[2])\r\nintegral <- integral1$value + integral2$value;\r\nrisposta1 <- 1/integral\r\nprint(fractions(risposta1));\r\n\r\nk <- risposta1\r\n\r\nintegral1 <- integrate(Vectorize(ass1), lower = intervallo1[1], upper = intervallo1[2])\r\nintegral2 <- integrate(Vectorize(ass2), lower = intervallo2[1], upper = intervallo2[2])\r\nintegral <- integral1$value + integral2$value;\r\n\r\nprint(integral);\r\n\r\nrisposta3 <- 0\r\nif( domanda3 >= intervallo1[1] && domanda3 <= intervallo2[2] ){\r\n if( intervallo1[1] <= domanda3 && domanda3 < intervallo1[2] ){\r\n integral <- integrate(Vectorize(density1), lower = intervallo1[1], upper= domanda3)\r\n integral <- integral$value\r\n } else{\r\n integral1 <- integrate(Vectorize(density1), lower = intervallo1[1], upper = intervallo1[2])\r\n integral2 <- integrate(Vectorize(density2), lower = intervallo2[1], upper = domanda3)\r\n integral <- integral1$value + integral2$value\r\n }\r\n risposta3 <- 1 - (integral);\r\n}\r\n\r\nprint(risposta3)", "meta": {"hexsha": "c3f03676b73d805cd723be331858d8017d60913e", "size": 1500, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 37.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 37.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 37.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": 24.1935483871, "max_line_length": 96, "alphanum_fraction": 0.6466666667, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7341195210831261, "lm_q1q2_score": 0.670747778695753}} {"text": "# Calculating a Confidence Interval From a Normal Distribution\r\nn<-50\r\n a<-2.8\r\n s<-0.6\r\n # we will use a 95% confidence level and wish to find the confidence interval\r\n margin <- qnorm(0.975)*s/sqrt(n)\r\n left_i <- a-margin\r\n right_i <- a+margin\r\n print(\"Confidence interval is\")\r\n print(left_i)\r\n print(right_i)", "meta": {"hexsha": "172e1dcf81fe4ca16dcb69c118a941b7c2dc563f", "size": 322, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.1/Ex5_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.1/Ex5_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.1/Ex5_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 29.2727272727, "max_line_length": 80, "alphanum_fraction": 0.6801242236, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6706019747680796}} {"text": "=begin\n # sample-geometry04.rb\n\n require 'algebra'\r\n \r\n R = MPolynomial(Rational)\r\n x,y,a1,a2,b1,b2,c1,c2 = R.vars('xya1a2b1b2c1c2')\r\n V = Vector(R, 2)\r\n X, A, B, C = V[x,y], V[a1,a2], V[b1,b2], V[c1,c2]\r\n \r\n def perpendicular(p0, p1, p2, p3)\r\n (p0-p1).inner_product(p2-p3)\r\n end\r\n \r\n def line(p1, p2, p3)\r\n SquareMatrix.det([[1, *p1], [1, *p2], [1, *p3]])\r\n end\r\n \r\n l1 = perpendicular(X, A, B, C)\r\n l2 = perpendicular(X, B, C, A)\r\n l3 = perpendicular(X, C, A, B)\r\n \r\n s = line(A, B, C)\r\n g = Groebner.basis [l1, l2, l3, s-1] #s-1 means non degeneracy\r\n \r\n g.each do |f|\r\n p f\r\n end\r\n #x + a1a2b1 - a1a2c1 - a1b1c2 + a1c1c2 + a2^2b2 - a2^2c2 - a2b1^2 + a2b1c1 - a2b2^2 + a2c2^2 + b1^2c2 - b1c1c2 - b1 + b2^2c2 - b2c2^2\r\n #y - a1^2b1 + a1^2c1 + a1b1^2 - a1c1^2 - a2^2b1 + a2^2c1 + a2b1b2 + a2b1c2 - a2b2c1 - a2c1c2 - a2 - b1^2c1 - b1b2c2 + b1c1^2 + b2c1c2\r\n #a1b2 - a1c2 - a2b1 + a2c1 + b1c2 - b2c1 - 1\r\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "4f1c68cfc06654fb395449bd6976f3d05432e425", "size": 961, "ext": "rd", "lang": "R", "max_stars_repo_path": "work/consider/algebra-0.72/doc/sample-geometry04.rb.v.rd", "max_stars_repo_name": "rubyworks/stick", "max_stars_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-04-24T05:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-24T05:51:21.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-geometry04.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "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": "work/consider/algebra-0.72/doc/sample-geometry04.rb.v.rd", "max_forks_repo_name": "rubyworks/stick", "max_forks_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "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.2647058824, "max_line_length": 136, "alphanum_fraction": 0.5452653486, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6706019698098372}} {"text": "comb.sort<-function(a){\n gap<-length(a)\n swaps<-1\n while(gap>1 & swaps==1){\n gap=floor(gap/1.3)\n if(gap<1){\n gap=1\n }\n swaps=0\n i=1\n while(i+gap<=length(a)){\n if(a[i]>a[i+gap]){\n a[c(i,i+gap)] <- a[c(i+gap,i)]\n swaps=1\n }\n i<-i+1\n }\n }\n return(a)\n}\n", "meta": {"hexsha": "33036b385547b0731733829a56ac976d444e6030", "size": 319, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sorting-algorithms-Comb-sort/R/sorting-algorithms-comb-sort.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/Sorting-algorithms-Comb-sort/R/sorting-algorithms-comb-sort.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/Sorting-algorithms-Comb-sort/R/sorting-algorithms-comb-sort.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": 15.1904761905, "max_line_length": 38, "alphanum_fraction": 0.4200626959, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6705983123506141}} {"text": "### fimd1.R\n### R code from Van Buuren, S. (2012). \n###\t\tFlexible Imputation of Missing Data. \n###\t\tCRC/Chapman & Hall, Boca Raton, FL.\n### (c) 2012 Stef van Buuren, www.multiple-imputation.com\n### Version 1, 21mar2012\n### Version 2, 4nov2015\n### Tested with Mac OS X 10.7.3, R2.14-2, mice 2.12\n\n### Chapter 1 \tIntroduction\n### Section 1.1 The problem of missing data\n\n### calculate the mean of three numbers\ny <- c(1, 2, 4) \nmean(y)\n\n### calculate the mean of three numbers, where one is missing\ny <- c(1, 2, NA)\nmean(y)\n\n### repeat, but with any missing data removed\nmean(y, na.rm=TRUE)\n\n### store your current options (safety measure)\nyouroptions <- options()\n\n### demo regression that generates an error message using default na.fail\noptions(na.action = na.fail)\n\n### uncomment to see the error\n### lm(Ozone ~ Wind, data=airquality)\n\n### remove incomplete observations by 'na.action = na.omit'\nfit <- lm(Ozone ~ Wind, data = airquality, na.action = na.omit)\ncoef(fit)\n\n### set automatic na.action = na.omit\noptions(na.action = na.omit)\n\n### find out how many rows were deleted\ndeleted <- na.action(fit)\nnaprint(deleted)\n\n### more incomplete rows if we add Solar.R as predictor\nfit2 <- lm(Ozone ~ Wind+Solar.R, data=airquality)\nnaprint(na.action(fit2))\n\n### restore your original options, but set na.omit\noptions(youroptions)\noptions(na.action=na.omit)\n\n### Section 1.3.2 Pairwise deletion\n\n### note: mean() is deprecated\ncolMeans(airquality, na.rm=TRUE)\ncor(airquality, use=\"pair\")\ncov(airquality, use=\"pair\")\n\n\n### Section 1.3.3 Mean imputation\n\n### install the mice package from CRAN if you have not yet done so\n### by uncommenting and running the next line\n# install.packages(\"mice\")\n\nlibrary(\"mice\")\nlibrary(\"lattice\")\n\n### impute the mean\nimp <- mice(airquality, method=\"mean\", m=1, maxit=1)\n\n\n### Figure 1.1\nlwd <- 1.5\npar(mfrow=c(1,2))\nbreaks <- seq(-20, 200, 10)\nnudge <- 1\nx <- matrix(c(breaks-nudge, breaks+nudge), ncol=2)\nobs <- airquality[,\"Ozone\"]\nmis <- imp$imp$Ozone[,1]\nfobs <- c(hist(obs, breaks, plot=FALSE)$counts, 0)\nfmis <- c(hist(mis, breaks, plot=FALSE)$counts, 0)\ny <- matrix(c(fobs, fmis), ncol=2)\nmatplot(x, y, type=\"s\",\n col=c(mdc(4),mdc(5)), lwd=2, lty=1,\n xlim = c(0, 170), ylim = c(0,40), yaxs = \"i\",\n xlab=\"Ozone (ppb)\",\n ylab=\"Frequency\")\nbox()\n\ntp <- xyplot(imp, Ozone~Solar.R, na.groups=ici(imp),\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\nprint(tp, newpage = FALSE, position = c(0.48,0.08,1,0.92))\n\n### Section 1.3.4 Regression imputation\n\nfit <- lm(Ozone ~ Solar.R, data=airquality)\npred <- predict(fit, newdata=ic(airquality))\n\n### alternative using mice\nimp <- mice(airquality[,1:2], method=\"norm.predict\", m=1, maxit=3,seed=1)\n\n### Figure 1.2\npar(mfrow = c(1,2))\nfmis <- c(hist(pred, breaks, plot=FALSE)$counts, 0)\ny <- matrix(c(fobs, fmis), ncol=2)\nmatplot(x, y, type=\"s\",\n col=c(mdc(4),mdc(5)), lwd=2, lty=1,\n xlim = c(0, 170), ylim = c(0,40), yaxs = \"i\",\n xlab=\"Ozone (ppb)\",\n ylab=\"Frequency\")\nbox()\n\ntp <- xyplot(imp, Ozone~Solar.R,\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\nprint(tp, newpage = FALSE, position = c(0.48,0.08,1,0.92))\n\n\n### Section 1.3.5 Stochastic regression imputation\n\nimp <- mice(airquality[,1:2],method=\"norm.nob\",m=1,maxit=1,seed=1)\n\n### Figure 1.3\npar(mfrow = c(1,2))\nmis <- imp$imp$Ozone[,1]\nfmis <- c(hist(mis, breaks, plot=FALSE)$counts, 0)\ny <- matrix(c(fobs, fmis), ncol=2)\nmatplot(x, y, type=\"s\",\n col=c(mdc(4),mdc(5)), lwd=2, lty=1,\n xlim = c(0, 170), ylim = c(0,40), yaxs = \"i\",\n xlab=\"Ozone (ppb)\",\n ylab=\"Frequency\")\nbox()\n\ntp <- xyplot(imp, Ozone~Solar.R, na.groups=ici(imp),\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\nprint(tp, newpage = FALSE, position = c(0.48,0.08,1,0.92))\n\n\n### Section 1.3.6 LOCF and BOCF\n\npar(mfrow=c(1,1))\nOz <- airquality$Ozone\nlocf <- function(x) {\n a <- x[1]\n for (i in 2:length(x)) {\n if (is.na(x[i])) x[i] <- a\n else a <- x[i]\n }\n return(x)\n}\nOzi <- locf(Oz)\ncolvec <- ifelse(is.na(Oz),mdc(2),mdc(1))\n\n### Figure 1.4\n\nplot(Ozi[1:80],col=colvec,type=\"l\",xlab=\"Day number\",ylab=\"Ozone (ppb)\")\npoints(Ozi[1:80],col=colvec,pch=20,cex=1)\n\n\n### Section 1.4.3 Example of multiple imputation\n\nimp <- mice(airquality, seed=1, print=FALSE)\nfit <- with(imp, lm(Ozone ~ Wind + Temp + Solar.R))\ntab <- round(summary(pool(fit)),3)\ntab[,c(1:3,5)]\n\nfit <- lm(Ozone~Wind+Temp+Solar.R,data=airquality,na.action=na.omit)\nround(coef(summary(fit)),3)\n\n### Figure 1.6\npar(mfrow = c(1,2))\nmis <- imp$imp$Ozone[,1]\nfmis <- c(hist(mis, breaks, plot=FALSE)$counts, 0)\ny <- matrix(c(fobs, fmis), ncol=2)\nmatplot(x, y, type=\"s\",\n col=c(mdc(4),mdc(5)), lwd=2, lty=1,\n xlim = c(0, 170), ylim = c(0,40), yaxs = \"i\",\n xlab=\"Ozone (ppb)\",\n ylab=\"Frequency\")\nbox()\n\ntp <- xyplot(imp, Ozone~Solar.R, subset = .imp==1,\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\nprint(tp, newpage = FALSE, position = c(0.48,0.08,1,0.92))\n\n### scatterplot of all imputed data sets (not in the book)\nxyplot(imp, Ozone~Solar.R | .imp,\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\n\n### Figure 1.7\n\nOz <- airquality$Ozone\ncolvec <- ifelse(is.na(Oz),mdc(2),mdc(1))\npar(mfrow=c(1,1))\nplot(Oz[1:80],col=mdc(1),type=\"l\",xlab=\"Day number\",ylab=\"Ozone (ppb)\")\npoints(Oz[1:80],col=mdc(1),pch=20,cex=1)\n\nidx <- ici(airquality$Ozone) & (1:153)<81 \nx <- (1:153)[idx]\npoints(x=x,y=complete(imp,1)$Ozone[idx],col=mdc(2),pch=20,cex=1)\npoints(x=x,y=complete(imp,2)$Ozone[idx],col=mdc(2),pch=20,cex=1)\npoints(x=x,y=complete(imp,3)$Ozone[idx],col=mdc(2),pch=20,cex=1)\npoints(x=x,y=complete(imp,4)$Ozone[idx],col=mdc(2),pch=20,cex=1)\npoints(x=x,y=complete(imp,5)$Ozone[idx],col=mdc(2),pch=20,cex=1)\n\n### figure of the autocorrelation function\n### (not in the book)\n\npar(mfrow=c(2,5))\nacf.ozone <- with(imp,acf(Ozone))\nmodel <- expression(acf(resid(lm(Ozone ~ Wind + Temp + Solar.R))))\nacf.resid <- with(imp,model)\ncalcacf <- function(acf.list) {\n k <- length(acf.list)\n acc <- acf.list[[1]]$acf\n for (i in 2:k) acc <- acc + acf.list[[i]]$acf\n return(acc/k)\n }\noz <- round(calcacf(acf.ozone$analyses),2)\nre <- round(calcacf(acf.resid$analyses),2)\n\n\n", "meta": {"hexsha": "7ebafd22532841d5a28f528bd3b3065aaa8b6965", "size": 6562, "ext": "r", "lang": "R", "max_stars_repo_path": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd1.r", "max_stars_repo_name": "Chicago-R-User-Group/2017-n3-Meetup-RStudio", "max_stars_repo_head_hexsha": "71a3204412c7573af2d233208147780d313430af", "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": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd1.r", "max_issues_repo_name": "Chicago-R-User-Group/2017-n3-Meetup-RStudio", "max_issues_repo_head_hexsha": "71a3204412c7573af2d233208147780d313430af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-12T14:06:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T23:26:27.000Z", "max_forks_repo_path": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd1.r", "max_forks_repo_name": "Chicago-R-User-Group/2017-n3-Meetup-RStudio", "max_forks_repo_head_hexsha": "71a3204412c7573af2d233208147780d313430af", "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.0427350427, "max_line_length": 73, "alphanum_fraction": 0.6229807985, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.670585015142014}} {"text": "options(scipen = 999)\n\nset.seed(082421)\n# creating 5 different categories, with different amounts of time they show up in the data\ncategories = rep(letters[1:5], times = c(5, 4, 6, 8, 7))\n\n# 30 observations with the mean and standard deviation\ntest_scores = rnorm(n = 30, mean = 7.14, sd = 2.16)\n\n# Making the categories act like categories rather than numerical values\ncategories = as.factor(categories)\n\n# Observations (be careful R is case sensitive)\nN = 30\n\n\n\n\n# Getting frequencies by using R as a calculator\n\n# get the frequencies of all the categories\ntable(categories)\n\n# Frequency & Percentage of A\n5/30\n(5/30)*100\n\n# Frequency & Percentage of B\n4/30\n(4/30)*100\n\n# Frequency & Percentage of C\n6/30\n(6/30)*100\n\n# Frequency & Percentage of D\n8/30\n(8/30)*100\n\n# Frequency & Percentage of E\n7/30\n(7/30)*100\n\n# cumulative frequencies of categories A & B\n(5/30) + (4/30)\n# another option is to do the calculations above and then just add up the frequency of A with the frequency of B\n.167 + .133\n\n# To get the cumlative percentage of all 5 categories\n(5/30)*100 + (4/30)*100 + (6/30)*100 + (8/30)*100 + (7/30)*100\n# you can also use the calculations above to add up all the percentages\n16.667 + 13.333 + 20 + 26.667 + 23.333\n\n\n# Now getting frequencies by using objects\n\n#remember that N is the number of observations\nN\n\nfreq_a <- 5/N\nfreq_a\n\n# Percent of category A\npercent_a <- freq_a*100\npercent_a\n\nfreq_b <- 4/N\nfreq_b\n\npercent_b <- freq_b*100\npercent_b\n\nfreq_c <- 6/N\nfreq_c\n\npercent_c <- freq_c*100\npercent_c\n\nfreq_d <- 8/N\nfreq_d\n\npercent_d <- freq_d*100\npercent_d\n\nfreq_e <- 7/N\nfreq_e\n\npercent_e <- freq_e*100\npercent_e\n\n# cumulative frequency of A & B\nfreq_ab = freq_a + freq_b\nfreq_ab\n\n# To get the cumlative percentage of all 5 categories\ntotal_percent = percent_a + percent_b + percent_c + percent_d + percent_e\ntotal_percent\n\n\n\n\n# find the mode\n# which value occurs most often\ntable(categories)\n\n\n\n\n# Finding the mean\nsort(test_scores)\n\n#look for the middle value or in this case the 15th and 16th observations\n# 7.060384 & 7.212301 and then divide by 2\n(7.06 + 7.21)/2\n\n# find the median using objects\nsort(test_scores)\nsort(test_scores)[15:16]\n\nget_median = (7.06 + 7.21)/2\nget_median\n\nmedian(test_scores)\n\n\n\n# Finding the mean\n# look at test scores first in order for lowest to highest\nsort(test_scores)\n\n# Now let's get the sum of the scores\n1.98 + 3.54 + 3.57 + 4.28 + 4.40 + 4.51 + 4.98 + 5.67 + 5.90 + 6.09 + 6.44 + 6.44 + 6.59 + 6.82 + 7.06 +\n 7.21 + 7.29 + 7.82 + 7.87 + 7.87 + 8.24 + 8.69 + 8.85 + 8.92 + 9.38 + 9.41 + 10.67 + 10.95 + 12.06 + 12.59\n\n# Now let's divide the sum of the scores by the number of observations to get the mean\n(1.98 + 3.54 + 3.57 + 4.28 + 4.40 + 4.51 + 4.98 + 5.67 + 5.90 + 6.09 + 6.44 + 6.44 + 6.59 + 6.82 + 7.06 +\n 7.21 + 7.29 + 7.82 + 7.87 + 7.87 + 8.24 + 8.69 + 8.85 + 8.92 + 9.38 + 9.41 + 10.67 + 10.95 + 12.06 + 12.59)/30\n\n# 7.20 is the mean of our scores\n\n\n# Now getting the mean with objects\nsort(test_scores)\n\n# look at how many observations we have\nN\n\n# Now lets get the sum of the scores\nsum_of_scores = sum(test_scores)\nsum_of_scores\n\n# get the mean\nxbar = sum_of_scores/N\n# could also look at it this way\nxbar2 = sum_of_scores/30\n\nxbar\nxbar2\n\n# we get the same mean\n\n\n\n\n#Finding how far each participant deviates from the mean value/score\nsort(test_scores)\n# look at how far students deviated from the average score by doing each one individually\n1.98 - 7.20\n3.54 - 7.20\n3.57 - 7.20\n4.28 - 7.20\n4.40 - 7.20\n4.51 - 7.20\n4.98 - 7.20\n5.67 - 7.20\n5.90 - 7.20\n6.09 - 7.20\n6.44 - 7.20\n6.44 - 7.20\n6.59 - 7.20\n6.82 - 7.20\n7.06 - 7.20\n7.21 - 7.20\n7.29 - 7.20\n7.82 - 7.20\n7.87 - 7.20\n7.87 - 7.20\n8.24 - 7.20\n8.69 - 7.20\n8.85 - 7.20\n8.92 - 7.20\n9.38 - 7.20\n9.41 - 7.20\n10.67 - 7.20\n10.95 - 7.20\n12.06 - 7.20\n12.59 - 7.20\n\n# now to get the sum of the deviations\n# this is right, you might just have to go past two decimal points\n(-5.22) + (-3.66) + (-3.63) + (-2.92) + (-2.8) + (-2.69) + (-2.22) + (-1.53) + (-1.3) + (-1.11) + (-.76) + (-.76) +\n (-.61) + (-.38) + (-.14) + .01 + .09 + .62 +.67 + .67 + 1.04 + 1.49 + 1.65 + 1.72 + 2.18 +2.21 + 3.47 + 3.75 + 4.86 + 5.39\n\n# Now getting the deviations from the mean score/value using objects\n# remember to look at the test scores\nsort(test_scores)\n\n# lets remember what the mean was\nxbar\n\n# look at how far students deviated from the average score using the objects we created earlier\ndeviation = test_scores - xbar\ndeviation\n\n# look to see how far the worse test score was from the mean\nsort(deviation)\n\n# getting the sum of the deviations\nsum(deviation)\n\n\n\n\n\n\n", "meta": {"hexsha": "21b3f881eb4850ab68d551aac2669e4ac96e9faf", "size": 4570, "ext": "r", "lang": "R", "max_stars_repo_path": "problem_set1_script.r", "max_stars_repo_name": "jpedroza1228/cpp_3307", "max_stars_repo_head_hexsha": "ed9dec1b2fb03883efd36fa0dc64bb82bff248be", "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": "problem_set1_script.r", "max_issues_repo_name": "jpedroza1228/cpp_3307", "max_issues_repo_head_hexsha": "ed9dec1b2fb03883efd36fa0dc64bb82bff248be", "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": "problem_set1_script.r", "max_forks_repo_name": "jpedroza1228/cpp_3307", "max_forks_repo_head_hexsha": "ed9dec1b2fb03883efd36fa0dc64bb82bff248be", "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.2212389381, "max_line_length": 124, "alphanum_fraction": 0.6693654267, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6705316304167387}} {"text": "# Example : 4 Chapter : 2.7 Pageno : 110\n# Product of matrix and its trnspose gives symmetric matrix\nR<-matrix(c(-1,0,1,-1,0,1),ncol=3)\nRT<-t(R)\nprint(\"R * t(R)\")\nprint(R%*%RT)\nprint(\"t(R) * R\")\nprint(RT%*%R)", "meta": {"hexsha": "f02ef37a9e82f1709b76d38c5d7aa069408cc8c8", "size": 212, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.4/Ex2.7_4.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.4/Ex2.7_4.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.7.4/Ex2.7_4.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 26.5, "max_line_length": 59, "alphanum_fraction": 0.6132075472, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6705031006499966}} {"text": "## ----echo=FALSE---------------------------------------------------------------\nrequire(Hmisc)\nknitrSet('gen')\n\n\n## ----lspline2,echo=FALSE,child='lspline.Rnw'----------------------------------\n\n## ----lspline,echo=FALSE,bty='l',cap='A linear spline function with knots at $a = 1, b = 3, c = 5$.'----\nx <- c(0,1,3,5,6)\ny <- c(4,3,5.5,5,2)\nplot(x, y, type=\"l\", xlab=expression(X), ylab=expression(f(X)), axes=FALSE)\naxis(1)\naxis(2, labels=FALSE)\n\n\n\n## ----rcscomp2,child='rcscomp.Rnw'---------------------------------------------\n\n## ----rcscomp,mfrow=c(1,2),left=-2,h=3.5,w=4.5,cap='Restricted cubic spline component variables for $k = 5$ and knots at $X = .05, .275, .5, .725$, and $.95$. Nonlinear basis functions are scaled by $\\\\tau$. The left panel is a $y$--magnification of the right panel. Fitted functions such as those in Figure \\\\ref{fig:gen-rcsex} will be linear combinations of these basis functions as long as knots are at the same locations used here.',scap='Restricted cubic spline component variables for 5 knots'----\nrequire(Hmisc)\nx <- rcspline.eval(seq(0,1,.01),\n knots=seq(.05,.95,length=5), inclx=T)\nxm <- x\nxm[xm > .0106] <- NA\nmatplot(x[,1], xm, type=\"l\", ylim=c(0,.01),\n xlab=expression(X), ylab='', lty=1)\nmatplot(x[,1], x, type=\"l\",\n xlab=expression(X), ylab='', lty=1)\n\n\n\n## ----rcsex2,child='rcsex.Rnw'-------------------------------------------------\n\n## ----rcsex,h=6,w=5.5,left=-2,bot=2,mfrow=c(2,2),ps=13,cap='Some typical restricted cubic spline functions for $k = 3, 4, 5, 6$. The $y$--axis is $X\\\\beta$. Arrows indicate knots. These curves were derived by randomly choosing values of $\\\\beta$ subject to standard deviations of fitted functions being normalized.',scap='Some typical restricted cubic spline functions'----\nx <- seq(0, 1, length=300)\nfor(nk in 3:6) {\n set.seed(nk)\n knots <- seq(.05, .95, length=nk)\n xx <- rcspline.eval(x, knots=knots, inclx=T)\n for(i in 1 : (nk - 1))\n xx[,i] <- (xx[,i] - min(xx[,i])) /\n (max(xx[,i]) - min(xx[,i]))\n for(i in 1 : 20) {\n beta <- 2*runif(nk-1) - 1\n xbeta <- xx %*% beta + 2 * runif(1) - 1\n xbeta <- (xbeta - min(xbeta)) /\n (max(xbeta) - min(xbeta))\n if(i == 1) {\n plot(x, xbeta, type=\"l\", lty=1,\n xlab=expression(X), ylab='', bty=\"l\")\n title(sub=paste(nk,\"knots\"), adj=0, cex=.75)\n for(j in 1 : nk)\n arrows(knots[j], .04, knots[j], -.03,\n angle=20, length=.07, lwd=1.5)\n }\n else lines(x, xbeta, col=i)\n }\n}\n\n\n\n## ----regass2,child='regass.Rnw'-----------------------------------------------\n\n## ----regass,echo=FALSE,cap='Regression assumptions for one binary and one continuous predictor',axes=FALSE----\nplot(0:1, 0:1, xlab=expression(X[2]), ylab=expression(C(Y)),\n axes=FALSE, type='n')\naxis(1, at=0:1, labels=rep('',2))\naxis(2, at=0:1, labels=rep('',2))\nlines(c(.05, .8), c(.05, .5))\nlines(c(.05, .8), c(.30, .75))\ntext(.9, .5, expression(X[1]==0), adj=.5)\ntext(.9, .75,expression(X[1]==1), adj=.5)\n\n\n\nx <- c(0,1,3,5,6)\ny <- c(4,3,5.5,5,2)\nplot(x, y, type=\"l\", xlab=expression(X), ylab=expression(f(X)), axes=FALSE)\naxis(1)\naxis(2, labels=FALSE)\n\n\n\nrequire(Hmisc)\nx <- rcspline.eval(seq(0,1,.01),\n knots=seq(.05,.95,length=5), inclx=T)\nxm <- x\nxm[xm > .0106] <- NA\nmatplot(x[,1], xm, type=\"l\", ylim=c(0,.01),\n xlab=expression(X), ylab='', lty=1)\nmatplot(x[,1], x, type=\"l\",\n xlab=expression(X), ylab='', lty=1)\n\n\n\nx <- seq(0, 1, length=300)\nfor(nk in 3:6) {\n set.seed(nk)\n knots <- seq(.05, .95, length=nk)\n xx <- rcspline.eval(x, knots=knots, inclx=T)\n for(i in 1:(nk-1))\n xx[,i]<-(xx[,i] - min(xx[,i])) /\n (max(xx[,i]) - min(xx[,i]))\n for(i in 1:20) {\n beta <- 2*runif(nk-1) - 1\n xbeta <- xx%*%beta+2*runif(1) - 1\n xbeta <- (xbeta - min(xbeta)) /\n (max(xbeta) - min(xbeta))\n if(i==1) {\n plot(x, xbeta, type=\"l\", lty=1,\n xlab=expression(X), ylab='', bty=\"l\")\n title(sub=paste(nk,\"knots\"), adj=0, cex=.75)\n for(j in 1:nk)\n arrows(knots[j], .04, knots[j], -.03,\n angle=20, length=.07, lwd=1.5)\n }\n else lines(x, xbeta, col=i)\n }\n}\n\n\n\nplot(0:1, 0:1, xlab=expression(X[2]), ylab=expression(C(Y)),\n axes=FALSE, type='n')\naxis(1, at=0:1, labels=rep('',2))\naxis(2, at=0:1, labels=rep('',2))\nlines(c(.05, .8), c(.05, .5))\nlines(c(.05, .8), c(.30, .75))\ntext(.9, .5, expression(X[1]==0), adj=.5)\ntext(.9, .75,expression(X[1]==1), adj=.5)\n\n\n", "meta": {"hexsha": "6b391ac3e4d7d44487b44213ec577dbc5241a733", "size": 4491, "ext": "r", "lang": "R", "max_stars_repo_path": "RMScode/2_general_regression.r", "max_stars_repo_name": "fabarrios/Regression", "max_stars_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:27:09.000Z", "max_issues_repo_path": "RMScode/2_general_regression.r", "max_issues_repo_name": "fabarrios/Regression", "max_issues_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T23:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T23:59:10.000Z", "max_forks_repo_path": "RMScode/2_general_regression.r", "max_forks_repo_name": "fabarrios/Regression", "max_forks_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T03:43:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:43:53.000Z", "avg_line_length": 33.7669172932, "max_line_length": 507, "alphanum_fraction": 0.535738143, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.670178154752922}} {"text": "func1 <- function(x) {\n \n result <- c()\n \n for(i in 1:length(x)) {\n\n result<-append(result, x[i]**i)\n }\n return(result)\n \n}\n\nfunc2 <- function(x) {\n \n result <- c()\n \n for(i in 1:length(x)) {\n \n result<-append(result, (x[i]**i)/i)\n }\n return(result)\n \n}\n\nfunc3 <- function(x, n) {\n \n if(n<=0) {\n return(\"n must be a positive number\")\n }\n \n result = 1\n \n for(i in 1:n) {\n result = result + (x**i)/i\n }\n \n return(result)\n \n}\n\nl = func1(c(2,3,4,5,7,9))\n\nfunc2(c(4,3,5,2))\n\nfunc3(3,3)\n\n\n\n\n\n", "meta": {"hexsha": "af4d75d99a98f51e2639096ed40ca16299269924", "size": 596, "ext": "r", "lang": "R", "max_stars_repo_path": "exercise1/exercise1NikosKougianos.r", "max_stars_repo_name": "kougianos/R-code", "max_stars_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": "exercise1/exercise1NikosKougianos.r", "max_issues_repo_name": "kougianos/R-code", "max_issues_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": "exercise1/exercise1NikosKougianos.r", "max_forks_repo_name": "kougianos/R-code", "max_forks_repo_head_hexsha": "9e582d7f44e151242bb02f8dbf386eac0e703c9a", "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": 11.6862745098, "max_line_length": 45, "alphanum_fraction": 0.4295302013, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6699788746014015}} {"text": "# install.packages(\"Exact\", repos=\"https://cloud.r-project.org\")\nlibrary(\"Exact\")\n\nf_obs <- matrix(c(15, 0, 38, 47), nrow=2, ncol=2, byrow=TRUE)\nresult <- exact.test(f_obs, alternative=\"two.sided\", method=\"csm\", model=\"Binomial\", cond.row=FALSE)\nresult\n\nf_obs <- matrix(c(16, 13, 37, 34), nrow=2, ncol=2, byrow=TRUE)\nresult <- exact.test(f_obs, alternative=\"two.sided\", method=\"csm\", model=\"Binomial\", cond.row=FALSE)\nresult", "meta": {"hexsha": "d44c36f1ed0a8333daf4728c7e8f09758b9e4abb", "size": 424, "ext": "r", "lang": "R", "max_stars_repo_path": "ATNx/barnard.r", "max_stars_repo_name": "shanemomara/omaraneurolab", "max_stars_repo_head_hexsha": "a724efab3a13e762755e23050ba54b72d9ac739b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-13T16:18:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T09:23:18.000Z", "max_issues_repo_path": "ATNx/barnard.r", "max_issues_repo_name": "shanemomara/omaraneurolab", "max_issues_repo_head_hexsha": "a724efab3a13e762755e23050ba54b72d9ac739b", "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": "ATNx/barnard.r", "max_forks_repo_name": "shanemomara/omaraneurolab", "max_forks_repo_head_hexsha": "a724efab3a13e762755e23050ba54b72d9ac739b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-03T13:29:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-03T13:29:21.000Z", "avg_line_length": 42.4, "max_line_length": 100, "alphanum_fraction": 0.6910377358, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6699392803084773}} {"text": "# Euler/Milstein\n\nr <- 2; K <- 1; beta <- 0.25; Xzero <- 0.5; # problem parameters\nT <- 1; N <- 2^(11); dt <- T/N; # \nM <- 500; # number of paths sampled\nR <- c(1, 16, 32, 64, 128); # Milstein stepsizes are R*dt\n\ndW <- sqrt(dt)* matrix(runif(M*N),M);\nXmil <- matrix(M, 5);\nfor(p in 1:5) {\n Dt = R[p]*dt;\n L = N/R[p];\n Xtemp = Xzero*rep(M,1);\n for(j in 1:L) {\n Winc = sum(dW[, seq(R[p]*(j-1)+1, R[p]*(j))]);\n Xtemp = Xzero + Dt*r*Xtemp*(K-Xtemp) + beta*Xtemp*Winc + .5*beta^2*Xtemp*(Winc*Winc - Dt);\n }\n Xmil[,p] <- Xtemp; #store Milstein solution at t=1\n}\n\nXref = Xmil[,1]; # Reference solution\nXerr = abs(Xmil[,2:5] - repmat(Xref,1,4)); # Error in each path\nmean(Xerr); # Mean pathwise errors\nDtvals = dt*R(2:5); # Milstein timesteps used\n\n#subplot(224)\nplot(Dtvals, \n mean(Xerr), \n log = \"xy\", \n type = \"l\");\nlines(Dtvals, Dtvals, log = \"xy\",\n# axis([1e-3 1e-1 1e-4 1],\n xlab = 'dt',\n ylab = 'Sample average of | X(T) - X_L|',\n main = 'milstein')", "meta": {"hexsha": "2b1bb76164fa91aaea3a50539f4e0f82f38c9589", "size": 1181, "ext": "r", "lang": "R", "max_stars_repo_path": "simulations/Euler-Milstein/euler-milstein.r", "max_stars_repo_name": "SUNY-SDE-2015/REU15", "max_stars_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "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": "simulations/Euler-Milstein/euler-milstein.r", "max_issues_repo_name": "SUNY-SDE-2015/REU15", "max_issues_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-06-04T17:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-09T15:38:17.000Z", "max_forks_repo_path": "simulations/Euler-Milstein/euler-milstein.r", "max_forks_repo_name": "SUNY-SDE-2015/REU15", "max_forks_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "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.7428571429, "max_line_length": 98, "alphanum_fraction": 0.4614733277, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6699392656308727}} {"text": "#' Calculate Unobserved Selection Bias\n#'\n#' @description We calculate an effect of selection on unobservables\n#' on estiamted coefficient of treatment. This method is presented by\n#' Oster (2019, Journal of Business & Economic Statistics).\n#' Let b0 and r0 be the coefficient of treatment and R-squared\n#' resulting from the regression of outcome on treatment.\n#' Let b1 and r1 be the coefficient of treatment and R-squared\n#' resulting from the regression of outcome on\n#' treatment and observed covariates.\n#' Let rmax be the R-squared resulting from the hypothetical regression\n#' of outcome on treatment, observed covairates, and unobserved covariates.\n#' The value rmax depends on researchers.\n#' Oster' suggestion is `rmax = r1 * 1.3`\n#' (See a paper for detailed discussion).\n#' Define b^ = b1 - (b0 - b1)*(rmax - r1)/(r1 - r0).\n#' Under the following assumpetions,\n#' the value b^ converges to a true b in probability one.\n#' Assumption 1 is that\n#' covariates are orthogonal to unobservables.\n#' Assumption 2 is that\n#' the unobservable and observables are equally related to the treatment.\n#' Assumption 3 is that\n#' the coefficient of covariates on treatment is same as\n#' the coefficient of covairates on outcome.\n#' These assumptions are not precise. See a paper for detailed discussion.\n#'\n#'\n#' @param x an object whose class is `RCT`.\n#' @param r_max a numerical value of rmax. Default is null.\n#' @param r_multiply a numerical value of multiple of r1. Default is `1.3`.\n#'\n#' @return a numeric vector whose class is `RCT` and `OsterBias`.\n#'\n#' @importFrom stringr str_split\n#' @importFrom purrr map\n#' @importFrom purrr as_vector\n#' @importFrom magrittr %>%\n#' @importFrom stats coef\n#'\n#' @export\n#+\nosterbias <- function(x, r_max = NULL, r_multiply = 1.3) {\n\n # class check\n if (sum(class(x) == \"RCT\") == 0) stop(\"Unsupported class.\")\n\n # extract treatment variables\n d <- str_split(x$treat, \"\\\\+\") %>%\n map(~ gsub(\" \", \"\", .)) %>%\n as_vector()\n\n # extract coefficients\n b0 <- coef(x$fit[[1]])[d]\n r0 <- summary(x$fit[[1]])$r.squared\n\n b1 <- coef(x$fit[[2]])[d]\n r1 <- summary(x$fit[[2]])$r.squared\n\n\n if (!is.null(r_max)) {\n bias <- d %>%\n map(~ (b0[.] - b1[.]) * ((r_max - r1) / (r1 - r0))) %>%\n as_vector()\n } else {\n bias <- d %>%\n map(~ (b0[.] - b1[.]) * ((r_multiply * r1 - r1) / (r1 - r0))) %>%\n as_vector()\n }\n\n names(bias) <- d\n class(bias) <- append(c(\"RCT\", \"OsterBias\"), class(bias))\n\n return(bias)\n}\n", "meta": {"hexsha": "8861b2f97ee39b1f07b5a8cd98090207531169dc", "size": 2573, "ext": "r", "lang": "R", "max_stars_repo_path": "R/osterbias.r", "max_stars_repo_name": "KatoPachi/Rkato", "max_stars_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T14:16:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T14:16:05.000Z", "max_issues_repo_path": "R/osterbias.r", "max_issues_repo_name": "KatoPachi/Rkato", "max_issues_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-03T20:33:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T12:19:54.000Z", "max_forks_repo_path": "R/osterbias.r", "max_forks_repo_name": "KatoPachi/Rkato", "max_forks_repo_head_hexsha": "383d78c19201e7099324cbabbae9b89602e6e3d9", "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.8552631579, "max_line_length": 79, "alphanum_fraction": 0.6389428682, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6697640585018104}} {"text": "# Diffuse_fraction_of_solar_radiation.R\n#\n# Pieter Beck (psabeck@gmail.com)\n# 09-12-2013\n# Modified by S.R. Supp 2014 (sarah@weecology.org)\n# \n# functions to calculate what fraction of incoming solar radiation reaches the surface as diffuse radiation\n#\n# Changelog:\n# VERS | DATE \t\t | CHANGES\t\t\t\t| BY\n# ------|------------|----------------|---- \n#\t\t1.0.0\t|\t09-12-2013 | Wrote script\t\t| PB\n\n#Id is diffuse radiation\n#I is 'global radiation' (DSWRF) (for a horizontal plane, global irradiance is the sum of the diffuse and the direct component)\n#Id/I (IdoverI) is the fraction of diffuse radiation in global radiation \n#IdoverI is estimated as a function of kt (Liu and Jordan 1960) (and in some cases solar zenith angle)\n\n#kt is the clearness index\n#The clearness index measures the proportion of horizontal extraterrestrial radiation (Io)\n#reaching the surface.\n#it is defined as kt = I / (Io cos solarzen).\n#DSWRF = Downward short wave radiation flux \n\nIdoverI.calc <- function(kt,solarzen){\n #calculate the fraction of diffuse radiation in global radiation\n #using the Reindl* method (Helbig 2009)\n # Args: \n # kt: The clearness index (sensu Liu and Jordan 1960)\n # solarzen: solar zenith angle in radians\n # Returns:\n # the fraction of diffuse radiation (Id) in global radiation (I)\n \n if (kt <= 0.3) {IdoverI <- 0.1020 - 0.248*kt}else{\n if(kt < 0.78){\n solar.elev <- pi/2 - solarzen\n IdoverI <- 1.4 - 1.749*kt + 0.177*sin(solar.elev)}else{\n IdoverI <- 0.147}\n }\n return(IdoverI)\n}\n\nSpSd.calc <- function(Rsurface, R_extra_terr, solarzen, Rup){\n #calculate direct (Sp) and diffuse (Sd) radiation from global radiation\n #and horizontal extraterrestrial radiation \n # Args: \n # Rsurface: incoming shortwave radiation at the surface\n # Rup: upward shortwave radiation, which should be added to diffuse radiation calculated from downward shortwave radiation\n # R_extra_terr: horizontal extraterrestrial radiation \n # solarzen: solar zenith angle in radians\n # Returns:\n # A two-column matrix giving incoming direct [,1], and diffuse [,2] radiation at the surface\n \n if (solarzen > 2*pi){cat(\"STOP STOP STOP provide solarzenith in radiance to SpSd.calc\\n\");browser()}\n kt <- Rsurface/R_extra_terr\n #TODO: Added this check (e.g. if Rsurface and R_extra_terr == 0, kt == NaN which is a problem)\n if (is.na(kt)){\n kt = 0\n }\n #the formula in Lanini 2010 p1 is\n #kt <- Rsurface/(Io*cos(solarzen))\n #but this is for Io*cos(solarzen) being the horizontal extraterrestrial radiation\n #and thus is adjusted for latitude/solarzen before comparison with Rsurface\n #I believe sirad:extrat provides latitude-corrected (ie horizontal) extraterrestrial radiation\n IdoverI <- IdoverI.calc(kt,solarzen)\n IdoverI[IdoverI < 0] <- 0 ; IdoverI[IdoverI > 1] <- 1\n SpSd <- Rsurface * cbind(1-IdoverI,IdoverI)\n SpSd[2] <- SpSd[2] + Rup\n return(SpSd)\n}\n\nsolarzen.calc <- function(coords,datetimePOSIXct){\n #calculate solar zenith based on lat, lon & time of day\n # Args: \n # coords: coordinates\n # datetimePOSIXct: a POSIXct object giving date and time\n # Returns:\n # solar zenith angle\n\n require(maptools)\n solarelv <- solarpos(crds=coords,dateTime=datetimePOSIXct)\n solarelv <- solarelv[,2]\n #convert to radians\n solarelv <- pi*solarelv/180\n #convert to solar zenith (0 when sun is overhead) in radians\n solarzen <- pi/2 - solarelv\n #set below-horizon zeniths to pi/2\n solarzen[solarzen > pi/2] <- pi/2\n cat(\"in zolar zenith values, pi/2 (90degs) represents horizon/sub-horizon\\n\n while 0 represents directly over-head\\n\")\n return(solarzen) \n}\n\nR_extra_terr.calc<-function(thisdate,lat.in.deg){\n #calculate hourly extraterrestrial irradiance in W/m2 using sirad package\n # Args: \n # thisdate: string object giving date, e.g. \"2011-12-31\"\n # lat.in.deg: lattitude in degrees\n # Returns:\n # hourly extraterrestrial radiation\n # Example:\n # R_extra_terr.calc(thisdate=c(\"2012-01-19\",\"2012-01-19\"),lat.in.deg=c(-69))\n \n require(sirad)\n JulianDay <- sirad::dayOfYear(thisdate)#dayOfYear(\"2011-01-01\")\n lat.in.rad <- lat.in.deg*pi/180\n R_extra_terr <- extrat(i=JulianDay,lat.in.rad)#[[2]]\n #extrat[[1]] uses MJ/(day m^2) units\n #extrat[[2]] uses MJ/(hr m^2) units\n #convert output to W/m2\n conv.fac.daily <- (1000000/ 86400)\n conv.fac.hourly <- (1000000/ 86400)*24\n R_extra_terr[[1]] <- conv.fac.daily * R_extra_terr[[1]]\n R_extra_terr[[2]] <- conv.fac.hourly * R_extra_terr[[2]]\n #set negative hourly extrat irrad to 0\n #R_exta_terr <- R_exta_terr[[2]]\n R_extra_terr[[2]][R_extra_terr[[2]]<0] <- 0\n R_extra_terr <- R_extra_terr[[2]]\n R_extra_terr <- matrix(R_extra_terr,ncol=24)\n #cat(\"calculated 24hrs of extraterrestrial irradiance for\\n\", nrow(R_extra_terr),\" latitude-date combinations\\n\")\n #output is hourly starting at solar midning\n return(R_extra_terr)\n}\n\nshift.vec <- function(vec,n,wrap=TRUE,pad=FALSE){\n # Shift a vector over by n spots\n #Args: \n # vec: vector to be shifted\n # n: number of spots to shift the vector over\n # Wrap adds the entry at the beginning to the end\n # pad does nothing unless wrap is false, in which case it specifies whether to pad with NAs\n # Returns:\n # the vector vec, shifted over n sots\n # Source:\n # http://stackoverflow.com/questions/6828937/what-to-do-with-imperfect-but-useful-functions\n \n if(length(vec)0) {\n returnvec <- vec[seq(n+1,length(vec) )]\n if(wrap) {\n returnvec <- c(returnvec,vec[seq(n)])\n } else if(pad) {\n returnvec <- c(returnvec,rep(NA,n))\n }\n } else if(n<0) {\n returnvec <- vec[seq(1,length(vec)-abs(n))]\n if(wrap) {\n returnvec <- c( vec[seq(length(vec)-abs(n)+1,length(vec))], returnvec )\n } else if(pad) {\n returnvec <- c( rep(NA,abs(n)), returnvec )\n }\n \n }\n return(returnvec)\n}\n\nshift_to_UTC <- function(hourly_tser,original.zone){\n #shift an hourly vector starting at midnight to start at midnight UTC\n # Args: \n # hourly_tser: an hourly vector starting at midnight local time\n # original.zone: the local time zone\n # Returns:\n # an hourly vector, starting at midnight UTC\n # Example:\n # shift_to_UTC(hourly_tser=1:24,original.zone=\"America/Mexico_City\")\n \n require(timeDate)\n tt1<-timeDate(\"2010-01-01 00:00:00\",zone=original.zone)\n tt2<-timeDate(\"2010-01-01 00:00:00\",zone=\"UTC\")\n shift.by <- as.numeric(tt2-tt1)\n cat(\"the 24 hour series will be shifted earlier hrs by \",shift.by,\" hours to match UTC\\n\")\n if (is.matrix(hourly_tser)){\n shifted_tser<-t(apply(hourly_tser,1,shift.vec,n=shift.by))\n }else{shifted_tser <- shift.vec(hourly_tser,n=shift.by)}\n return(shifted_tser)\n}\n\nR_extra_for_site.vec <- function(thisdate,lat.in.deg,original.zone){\n #given a date, latitude, and time zone, calculate extraterrestrial radiation\n #for that latitude\n #Args:\n # thisdate: date\n # lat.in.deg: latitude in degrees\n # original.zone: timezone\n # Returns:\n # Extraterrestrial radiation for the given latitude and day, in 6 hour steps\n \n if(length(thisdate)!=length(lat.in.deg)){\n cat(\"Please provide thisdate and lat.in.deg of equal length\\n\");browser()}\n #get the 24 R_extra_terr values for this lat & date\n R_extra_terr_24 <- R_extra_terr.calc(thisdate=thisdate,lat.in.deg=lat.in.deg)\n #determine by how many hours the series need to be shifted\n R_extra_terr_24UTC <- shift_to_UTC(R_extra_terr_24,original.zone=original.zone)\n #convert the R_extra_terr values from 24 hour to epoch\n epochmn <- function(x){tapply(x,rep(1:4,each=6),mean)}\n R_extra_terr_epochUTC <- t(apply(R_extra_terr_24UTC,1,epochmn))\n cat(\"all 24 hour series of extra-terrestrial R converted to 4 6-hour UTC epochs\\n\")\n rm(R_extra_terr_24,R_extra_terr_24UTC)\n return(R_extra_terr_epochUTC)\n}\n", "meta": {"hexsha": "8d3b9ac07b7802bc3e8f406939a14730e5df2226", "size": 7958, "ext": "r", "lang": "R", "max_stars_repo_path": "Diffuse_fraction_of_solar_radiation.r", "max_stars_repo_name": "sarahsupp/hb-migration", "max_stars_repo_head_hexsha": "c6697210d21b9af25985308e5874f7e927c8cfe2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-20T13:35:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T15:13:40.000Z", "max_issues_repo_path": "Diffuse_fraction_of_solar_radiation.r", "max_issues_repo_name": "sarahsupp/hb-migration", "max_issues_repo_head_hexsha": "c6697210d21b9af25985308e5874f7e927c8cfe2", "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": "Diffuse_fraction_of_solar_radiation.r", "max_forks_repo_name": "sarahsupp/hb-migration", "max_forks_repo_head_hexsha": "c6697210d21b9af25985308e5874f7e927c8cfe2", "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": 38.0765550239, "max_line_length": 127, "alphanum_fraction": 0.6984166876, "num_tokens": 2473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6697640536097852}} {"text": " DGGEV Example Program Results\n\n Eigenvalue( 1) = 20.000\n\n Eigenvector( 1)\n 10.00000\n 0.05714\n 0.62857\n 0.62857\n\n Eigenvalue( 2) = ( 30.000, -40.000)\n\n Eigenvector( 2)\n ( 7.12215, 0.00000)\n ( 1.42443, -0.00000)\n ( 0.85466, 1.13954)\n ( 0.85466, 1.13954)\n\n Eigenvalue( 3) = ( 30.000, 40.000)\n\n Eigenvector( 3)\n ( 7.12215, -0.00000)\n ( 1.42443, 0.00000)\n ( 0.85466, -1.13954)\n ( 0.85466, -1.13954)\n\n Eigenvalue( 4) = 40.000\n\n Eigenvector( 4)\n 10.00000\n 0.11111\n -0.33333\n 1.55556\n", "meta": {"hexsha": "a9e22e6f493734137049ecd12182c4129a73e766", "size": 575, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dggev_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/dggev_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/dggev_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": 16.9117647059, "max_line_length": 43, "alphanum_fraction": 0.5113043478, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6697297812440899}} {"text": "# Coeficientes\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n## Tu estaras a cargo en esta clase. Siguiendo este script, haras una regresion\n## lineal usando las tecnicas de algebra de matrices. \n\n## Aunque hemos visto en clases lo que un coeficiente es, el enfasis hasta ahora \n## ha sido puesto en que los coeficientes son simples numeros. Lo son. Pero ya \n## la proxima clase veremos mas en detalle por que es importante entender \n## lo que ellos representan. \n\n## Por el momento, recuerda (para siempre) la formula de beta. \n## b = (x'x)^-1x'y\n\n## Tambien recuerda la forma de la ecuacion de la regresion lineal:\n## y = b0 + b1x1 + e\n\n\n## Usando la formula para sacar betas, hoy calcularas beta0 (intercepto) y \n## beta1 (coeficiente).\n\n\n## En esta clase, pensaremos en la relacion que hay entre 'educacion' y \n## 'prestigio'. Sera positiva? Negativa? Para responder esta pregunta,\n## debes calcular beta1. Creo que estaremos de acuerdo en que la \n## variable independiente ('x', o 'la causa') es 'educacion', y la dependiente\n## ('y', o 'el efecto') es 'prestigio'. Seria raro pensar que \"el prestigio\n## causa la educacion\", no? Cuanto sube mi prestigio cuando aumenta una unidad\n## de educacion? Eso es precisamente lo que significa un coeficiente.\n\n## Recuerda...\n## prestigio <- educacion # Si\n## educacion <- prestigio # No!\n\n## Esto significa que,\n## Prestigio = b0 + b1*Educacion + e\n\n## Recuerda que todo esta indexado, menos los betas. Es decir, la formula real\n## es asi:\n## Prestigio_{i} = b0 + b1*Educacion_{i} + e_{i}\n## \"i\" significa \"individuo\". Y representa a cada observacion. \n## Esto significa que Pedro, Juan y Diego tienen, cada uno,\n## sus propios niveles de prestigio,\n## sus propios niveles de educacion,\n## y su propio error. Recuerda, el error es la diferencia entre lo que \n## predecimos (beta0 y beta1) y lo que observamos para Pedro, Juan y Diego.\n## Es decir, si tenemos esto:\n\n## Nombre Educacion (x) Prestigio (y) beta0 Beta1 Error\n# -----------------------------------------------------------------------\n## Pedro 10 15 1 2 -6\n## Juan 5 10 1 2 ?\n## Diego 2 8 1 2 ?\n\n## Recuerda (1): son los mismos betas para todos.\n## Recuerda (2): Por ej., para el caso de Pedro, la formula \n## \"Prestigio = b0 + b1Educacion + e\", \n## o \"Prestigio_{i} = b0 + b1Educacion_{i} + e_{i}\", que es lo mismo, \n## seria asi:\n\n## Pedro: \n## 15 = 1 + 2*10 - 6\n\n######################################################################\n## (1)\n## Como seria para el caso de Juan y Diego?\n## Responde\n######################################################################\n\n## Juan?\n\n\n## Diego?\n\n######################################################################\n## OK; sigamos. Ahora carguemos una base de datos real.\n\nif (!require(\"pacman\")) install.packages(\"pacman\"); library(pacman)\np_load(car) # En este paquete, \"vive\" la base \"Prestige\" (\"Prestigio\").\n\n# Carga la base\ndata(Prestige)\n\n# Mira como se ve la base de datos\nhead(Prestige)\n\n# Extrae la 'x' para conseguir beta1\nx = Prestige$education\n\n# Ve como se ve \"x\"\nx\n\n\n## Recuerda que para conseguir beta0 debes anexar una columna de 1's.\n\n## Aqui le decimos a R que repita 1s, del largo (o \"lenght\") de 'x'.\nunos = rep(1,length(x)) \n\n# Ve como se ve \"unos\"\nunos\n\n# Ahora junta ambas cosas (\"x\" y \"unos\")\n\nx = matrix(\n c(unos,x), # meter vectores 'unos' y 'x'\n ncol = 2 # y organizarlos en 2 columnas.\n )\n\nx # mira como se ve la nueva matrix \"x\"\n \n# Extrae la 'y'\ny = matrix(Prestige$prestige)\n\ny\n\n######################################################################\n## (2)\n## Calcula beta0 y beta1\n######################################################################\n\n## Recuerda los operadores\n\n# Transponer \n# t()\n\n# Invertir\n# inv()\n## Recuerda cargar \"matlib\" para usar la funcion \"inv()\".\nif (!require(\"pacman\")) install.packages(\"pacman\"); library(pacman)\np_load(matlib)\n\n# Multiplicar matrices\n# Por ejemplo x*x es x%*%x\n\n# OK; ahora tu. Calcula b = (x'x)^-1x'y\n\n######################################################################\n# Problema\n######################################################################\n\n# Funciona\ninv(t(x) %*% x) %*% t(x) %*% y\n\n# No Funciona\ninv(x) # Matrix debe ser cuadrada, pero \"x\" es rectancular.\n\n# Por que?\n\ninv(t(x) %*% x) # funciona\n# Porque para multiplicar una matriz, debe ser CONFORMABLE.\n# La dimension de \"x\" es 2x102 (dos columnas, 102 filas). Si \"x\" fuera 2x2, se podria.\n# Sin embargo, al multiplicar x' (que es 102x2) y x (que es 2x102), por \n# el \"inner rule\" (no se el espanol), es decir, el 2 y el otro 2, \n# sabemos que la invertidad de x'x esta definida, porque x'x es cuadrado.\n\n\n######################################################################\n## (3) \n## Comprueba que hiciste todo bien.\n## Estima una regresion lineal, pero ocupando\n## el comando \"lm\" (por \"linear model\"). El comando \"lm\" se ocupa asi:\n## lm(y ~ x). Define 'y' como 'Prestige$prestige' y 'x' como 'Prestige$education'.\n\nmodelo = lm(Prestige$prestige ~ Prestige$education)\n\noptions(scipen=9999)\nsummary(modelo)\n\n######################################################################\n## (4) Usando el comando 'plot', haz un grafico entre Prestigio y Educacion.\ndata(Prestige)\n\n\n\n######################################################################\n## (5) Usando tus propias palabras, y usando los resultados \n## de tu regresion lineal y el grafico, interpreta que significa\n## beta0 y que significa beta1.\n\n\n\n## (5.1) Que significa beta0? Responde.\n\n\n\n## (5.2) Que significa beta1? Responde.\n\n\n", "meta": {"hexsha": "a81ddd0b0e687e5bca66035ed2014f7a8eece8c5", "size": 5754, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase10/Clase10.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": "Lectures/Clase10/Clase10.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": "Lectures/Clase10/Clase10.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "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": 29.96875, "max_line_length": 86, "alphanum_fraction": 0.5610010428, "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6695591340362668}} {"text": "\t# DATA SETUP\n\n\t\tcharity = read.csv(\"E:/STAT 897/Group Project/charity.csv\")\n\t\tcharity.t = charity\n\t\tcharity.t$avhv = log(charity.t$avhv)\n\t\tcharity.t$agif = log(charity.t$agif)\n\t\tcharity.t$inca = log(charity.t$inca)\n\t\tcharity.t$incm = log(charity.t$incm)\n\t\tcharity.t$lgif = log(charity.t$lgif)\n\t\tcharity.t$rgif = log(charity.t$rgif)\n\t\tcharity.t$tgif = log(charity.t$tgif)\n\t\tcharity.t$tlag = log(charity.t$tlag)\n\n\t\tdata.train = charity.t[charity$part==\"train\",]\n\t\tx.train = data.train[,2:21]\n\t\tc.train = data.train[,22] # donr\n\t\tn.train.c = length(c.train) # 3984\n\t\ty.train = data.train[c.train==1,23] # damt for observations with donr=1\n\t\t# x.train.mat = model.matrix(damt~., data.train[c.train==1,2:23])[,-22]\n\t\tn.train.y = length(y.train) # 1995\n\n\t\tdata.valid = charity.t[charity$part==\"valid\",]\n\t\tx.valid = data.valid[,2:21]\n\t\tc.valid = data.valid[,22] # donr\n\t\tn.valid.c = length(c.valid) # 2018\n\t\ty.valid = data.valid[c.valid==1,23] # damt for observations with donr=1\n\t\t#x.valid.mat = model.matrix(damt~., data.valid[c.valid==1,2:23])[,-22]\n\t\tn.valid.y = length(y.valid) # 999\n\n\t\tdata.test = charity.t[charity$part==\"test\",]\n\t\tn.test = dim(data.test)[1] # 2007\n\t\tx.test = data.test[,2:21]\n\n\t\tx.train.mean = apply(x.train, 2, mean)\n\t\tx.train.sd = apply(x.train, 2, sd)\n\t\tx.train.std = t((t(x.train)-x.train.mean)/x.train.sd) # standardize to have zero mean and unit sd\n\t\t# x.train.mat.mean = apply(x.train.mat, 2, mean)\n\t\t# x.train.mat.sd = apply(x.train.mat, 2, sd)\n\t\t# x.train.mat.std = t((t(x.train.mat)-x.train.mat.mean)/x.train.mat.sd) # standardize to have zero mean and unit sd\n\t\tapply(x.train.std, 2, mean) # check zero mean\n\t\tapply(x.train.std, 2, sd) # check unit sd\n\t\tdata.train.std.c = data.frame(x.train.std, donr=c.train) # to classify donr\n\t\tdata.train.std.y = data.frame(x.train.std[c.train==1,], damt=y.train) # to predict damt when donr=1\n\n\t\tx.valid.std = t((t(x.valid)-x.train.mean)/x.train.sd) # standardize using training mean and sd\n\t\t# x.valid.mat.std = t((t(x.valid.mat)-x.train.mat.mean)/x.train.mat.sd) # standardize to have zero mean and unit sd\n\t\tdata.valid.std.c = data.frame(x.valid.std, donr=c.valid) # to classify donr\n\t\tdata.valid.std.y = data.frame(x.valid.std[c.valid==1,], damt=y.valid) # to predict damt when donr=1\n\n\t\tx.test.std = t((t(x.test)-x.train.mean)/x.train.sd) # standardize using training mean and sd\n\t\tdata.test.std = data.frame(x.test.std)\n\n\t\ttrain.dat = data.frame(x = x.train.std, y = as.factor(data.train.std.c$donr))\n\t\tvalid.dat = data.frame(x = x.valid.std, y = as.factor(data.valid.std.c$donr))\n\n\t#LIBRARIES\n\n\t\tlibrary(MASS)\n\t\tlibrary(tree)\n\t\tlibrary(randomForest)\n\t\tlibrary(gbm)\n\t\tlibrary(e1071)\n\t\tlibrary(lars)\n\t\tlibrary(leaps)\n\t\tlibrary(glmnet)\n\t\tlibrary(pls)\n\t\tlibrary(splines)\n\t\tlibrary(gam)\n\t\tlibrary(ISLR)\n\t\tlibrary(magrittr)\n\t\tlibrary(stringr)\n\t\tlibrary(lubridate)\n\t\tlibrary(dplyr)\n\t\tlibrary(ggplot2)\n\t\tlibrary(ggthemes)\n\n\t\t#EXPLORATORY DATA ANALYSIS\n\t\t# Helper Functions \n\t\tdensity_plots <- function( df , main = 'Density Plots') {\n\t\t df %>% \n\t\t gather(\n\t\t key = measure ,\n\t\t value = value \n\t\t ) %>% \n\t\t ggplot( \n\t\t aes(\n\t\t value ,\n\t\t color = measure ,\n\t\t group = measure\n\t\t )) +\n\t\t geom_density() +\n\t\t facet_wrap( ~measure , scales = 'free' ) +\n\t\t ggtitle( label = main ) +\n\t\t theme_gdocs() +\n\t\t theme( plot.title = element_text( face = 'bold' , size = rel(1.5) , hjust = .5 ) )\n\t\t}\n\t\t\n\t\t## EDA Visuals ################################################################\n\t\tp <- list()\n\t\tdata <- charity %>% tbl_df\n\t\tcfg.predictors <-\n\t\t c( \"reg1\" , \"reg2\" , \"reg3\" , \"reg4\" , \"home\" , \"chld\" , \"hinc\" , \n\t\t \"genf\" , \"wrat\" , \"avhv\" , \"incm\" , \"inca\" , \"plow\" , \"npro\" , \n\t\t \"tgif\" , \"lgif\" , \"rgif\" , \"tdon\" , \"tlag\" , \"agif\" )\n\t\t\n\t\t# raw data density plots\n\t\tp$density_raw <- {\n\t\t data %>% \n\t\t filter( part == 'train' ) %>% \n\t\t dplyr::select( avhv , npro , tgif , lgif , rgif , agif , tdon , tlag , incm , inca ) %>% \n\t\t density_plots( 'Density Plots of Raw Data' )\n\t\t}\n\t\t\n\t\t# log-transformed density plots\n\t\tp$density_logtransformed <- {\n\t\t data %>% \n\t\t filter( part == 'train' ) %>% \n\t\t dplyr::select( avhv , npro , tgif , lgif , rgif , agif , tdon , tlag , incm , inca ) %>% \n\t\t mutate_all( log ) %>% \n\t\t density_plots( 'Density Plots of Log-Transformed Data' )\n\t\t}\n\t\t\n\t\t# correlation plot\n\t\tp$correlations <- {\n\t\t data %>% \n\t\t filter( part == 'train' ) %>% \n\t\t select( cfg.predictors ) %>% \n\t\t select( -matches('reg') ) %>% \n\t\t cor() %>% \n\t\t round( 3 ) %>% \n\t\t ggcorrplot(\n\t\t ggtheme = theme_gdocs ,\n\t\t legend.title = 'r' ,\n\t\t hc.order = T ,\n\t\t colors = c('red' , 'white' , 'green') ,\n\t\t show.diag = F ,\n\t\t outline.color = 'black' ,\n\t\t lab = T ,\n\t\t lab_col = 'black' ,\n\t\t lab_size = rel(2.5) ,\n\t\t tl.cex = 13 \n\t\t ) + \n\t\t ggtitle( 'Predictor Correlations' ) +\n\t\t theme(\n\t\t axis.ticks = element_blank() ,\n\t\t panel.grid.major = element_blank() ,\n\t\t panel.grid.minor = element_blank() ,\n\t\t axis.text = element_text(face = 'bold', size = rel(3.5) , hjust = 0 ) ,\n\t\t plot.title = element_text( face = 'bold' , size = rel(1.5) , hjust = .5 )\n\t\t )\n\t\t}\n\n\t\t# predictors to damt - previously identified predictors are log-transformed first\n\t\tp$predstodamt <- {\n\t\t data %>% \n\t\t filter( part == 'train' ) %>% \n\t\t filter( damt > 0 ) %>% \n \t\t mutate_at( \n \t\t vars( avhv , tgif , lgif , rgif , agif , tlag , incm , inca ) , \n \t\t log ) %>% \n\t\t select( cfg.predictors , damt , -matches('reg') , -home , -genf ) %>% \n\t\t gather( predictor , value , -damt ) %>% \n\t\t ggplot( aes( value , damt , color = predictor , group = predictor ) ) +\n\t\t geom_point() + \n\t\t geom_density2d( color = 'gray' ) +\n\t\t geom_smooth( method = 'loess' , color = 'black') +\n\t\t facet_wrap( ~ predictor , scales = 'free' ) +\n\t\t theme_gdocs() + \n\t\t theme(\n\t\t legend.position = 'none' \n\t\t )\n\t\t} \n\t\t\n\t\t# save plots to png\n\t\tp %>% \n\t\t names %>% \n\t\t lapply( function(x){ \n\t\t ggsave( \n\t\t filename = paste0( 'plot-' , x , '.png' ) , \n\t\t plot = p[[x]] ,\n\t\t path = './output' \n\t\t ) \n\t\t })\n\t\t\n\t\t\n\t\t#CLASSIFICATION MODELS: LOGIT, LDA, TREES-BASED, AND SVM\n\t\t\n\t\t#LOGISTIC REGRESSION\n\t\tmodel.logit <- glm(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t x.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t x.tlag + x.agif, \n\t\t train.dat, family=binomial(\"logit\"))\n\t\t\n\t\tpost.valid.logit = predict(model.logit, valid.dat, type=\"response\") # n.valid.c post probs\n\t\t\n\t\tprofit.logit = cumsum(14.5*c.valid[order(post.valid.logit, decreasing=T)]-2)\n\t\tplot(profit.logit) # see how profits change as more mailings are made\n\t\tn.mail.valid = which.max(profit.logit) # number of mailings that maximizes profits\n\t\tc(n.mail.valid, max(profit.logit)) # report number of mailings and maximum profit\n\t\t\n\t\tcutoff.logit = sort(post.valid.logit, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid\n\t\tchat.valid.logit = ifelse(post.valid.logit>cutoff.logit, 1, 0) # mail to everyone above the cutoff\n\t\tlogit.table = table(chat.valid.logit, c.valid) # classification table\n\t\tlogit.mail = sum(logit.table[2,])\n\t\tlogit.mail.tp = logit.table[2,2]\n\t\tlogit.error = (logit.table[2,1]+logit.table[1,2])/2018\n\t\tlogit.profit = 14.5*logit.mail.tp - 2*logit.mail\n\t\t\n\t\tlogit.error #validation error rate: 0.2215\n\t\tlogit.mail #total mailings: 1,406\n\t\tlogit.profit #total profit: $11,383.50 \n\t\t\n\t\t#LDA Model Base\t\n\t\tmodel.ldaB = lda(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t x.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t x.tlag + x.agif, \n\t\t train.dat) # include additional terms on the fly using I()\n\t\t\n\t\tpost.valid.ldaB = predict(model.ldaB, valid.dat)$posterior[,2] # n.valid.c post probs\n\t\t\n\t\tprofit.ldaB = cumsum(14.5*c.valid[order(post.valid.ldaB, decreasing=T)]-2)\n\t\tplot(profit.ldaB) # see how profits change as more mailings are made\n\t\tn.mail.valid = which.max(profit.ldaB) # number of mailings that maximizes profits\n\t\tc(n.mail.valid, max(profit.ldaB)) # report number of mailings and maximum profit\n\t\t\n\t\tcutoff.ldaB = sort(post.valid.ldaB, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid\n\t\tchat.valid.ldaB = ifelse(post.valid.ldaB>cutoff.ldaB, 1, 0) # mail to everyone above the cutoff\n\t\tldaB.table = table(chat.valid.ldaB, c.valid) # classification table\n\t\tldaB.mail = sum(ldaB.table[2,])\n\t\tldaB.mail.tp = ldaB.table[2,2]\n\t\tldaB.error = (ldaB.table[2,1]+ldaB.table[1,2])/2018\n\t\tldaB.profit = 14.5*ldaB.mail.tp - 2*ldaB.mail\n\t\t\n\t\tldaB.error #validation error rate: 0.2235\n\t\tldaB.mail #total mailings: 1,406\n\t\tldaB.profit #total profit: $11,354.50\n\t\t\n\t\t#LDA Model Base + Quad (hinc, chld, tdon, tlag, wrat, inca, npro, tgif)\n\t\tmodel.ldaF = lda(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t x.avhv + x.plow + x.npro + x.tgif + x.tdon + \n\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2) + \n\t\t I(x.npro^2) + I(x.tgif^2), \n\t\t train.dat) # include additional terms on the fly using I()\n\t\t\n\t\tpost.valid.ldaF = predict(model.ldaF, valid.dat)$posterior[,2] # n.valid.c post probs\n\t\t\n\t\tprofit.ldaF = cumsum(14.5*c.valid[order(post.valid.ldaF, decreasing=T)]-2)\n\t\tplot(profit.ldaF) # see how profits change as more mailings are made\n\t\tn.mail.valid = which.max(profit.ldaF) # number of mailings that maximizes profits\n\t\tc(n.mail.valid, max(profit.ldaF)) # report number of mailings and maximum profit\n\t\t\n\t\tcutoff.ldaF = sort(post.valid.ldaF, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid\n\t\tchat.valid.ldaF = ifelse(post.valid.ldaF>cutoff.ldaF, 1, 0) # mail to everyone above the cutoff\n\t\tldaF.table = table(chat.valid.ldaF, c.valid) # classification table\n\t\tldaF.mail = sum(ldaF.table[2,])\n\t\tldaF.mail.tp = ldaF.table[2,2]\n\t\tldaF.error = (ldaF.table[2,1]+ldaF.table[1,2])/2018\n\t\tldaF.profit = 14.5*ldaF.mail.tp - 2*ldaF.mail\n\t\t\n\t\tldaF.error #validation error rate: 0.1457\n\t\tldaF.mail #total mailings: 1,267\n\t\tldaF.profit #total profit: $11,763.00\n\t\t\n\t\t#CLASSIFICATION TREE, BASE MODEL\n\t\t\n\t\tmodel.treeB=tree(y~.,train.dat)\n\t\tsummary(model.treeB)\n\t\tmodel.treeB\n\t\t\n\t\ttree.pred=predict(model.treeB,valid.dat,type=\"class\")\n\t\ttreeB.table = table(tree.pred,valid.dat$y)\n\t\ttreeB.mail = sum(treeB.table[2,])\n\t\ttreeB.mail.tp = treeB.table[2,2]\n\t\ttreeB.error = (treeB.table[2,1]+treeB.table[1,2])/2018\n\t\ttreeB.profit = 14.5*treeB.mail.tp - 2*treeB.mail\n\t\t\n\t\ttreeB.error #validation error rate: 0.1516\n\t\ttreeB.mail #total mailings: 1,165\n\t\ttreeB.profit #total profit: $11,140.50\n\t\t\n\t\t#CLASSIFICATION TREE, RANDOM FORESTS MODEL\n\t\t\n\t\t#THE BELOW LOOP TO DISCOVER WHICH SEED RETURNS MAXIMUM PROFIT (SET.SEED(53) RETURNED MAXIMUM)\n\t\t# mat = matrix(, ncol=4)\n\t\t\n\t\t# for(i in 1:100){\n\t\t# iter = i\n\t\t# set.seed(i)\n\t\t# model.rf = randomForest(y~., train.dat, mtry = 4, importance = TRUE)\n\t\t\n\t\t# summary(model.rf)\n\t\t# model.rf\n\t\t\n\t\t# tree.pred=predict(model.rf, valid.dat, type = \"class\")\n\t\t# rf.table = table(tree.pred, valid.dat$y)\n\t\t# rf.mail = sum(rf.table[2,])\n\t\t# rf.mail.tp = rf.table[2,2]\n\t\t# rf.error = (rf.table[2,1]+rf.table[1,2])/2018\n\t\t# rf.profit = 14.5*rf.mail.tp - 2*rf.mail\n\t\t\n\t\t# vec = c(iter, rf.error, rf.mail, rf.profit)\n\t\t# mat = rbind(mat, vec)\n\t\t# # print(i)\n\t\t# # print(rf.error) #validation error rate: \n\t\t# # print(rf.mail) #total mailings: \n\t\t# # print(rf.profit) #total profit: $\n\t\t# }\n\t\t\n\t\tset.seed(53)\n\t\tmodel.rf = randomForest(y~., train.dat, mtry = 4, importance = TRUE)\n\t\t\n\t\tsummary(model.rf)\n\t\tmodel.rf\n\t\t\n\t\ttree.pred=predict(model.rf,valid.dat,type=\"class\")\n\t\trf.table = table(tree.pred,valid.dat$y)\n\t\trf.mail = sum(rf.table[2,])\n\t\trf.mail.tp = rf.table[2,2]\n\t\trf.error = (rf.table[2,1]+rf.table[1,2])/2018\n\t\trf.profit = 14.5*rf.mail.tp - 2*rf.mail\n\t\t\n\t\trf.error #validation error rate: 0.1070\n\t\trf.mail #total mailings: 1,063\n\t\trf.profit #total profit: $11,257.50\n\t\t\n\t\t#SVM CLASSIFICATION MODEL\n\t\t\n\t\tsvm.train = svm(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t x.avhv + x.plow + x.npro + x.tgif + x.tdon + \n\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2)\n\t\t + I(x.npro^2) + I(x.tgif^2),\n\t\t data = train.dat, kernel = \"linear\", cost=10,scale = FALSE)\n\t\t\n\t\tsummary(svm.train)\n\t\tset.seed(53)\n\t\ttune.charity = tune(svm, y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t x.avhv + x.plow + x.npro + x.tgif + x.tdon + \n\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2)\n\t\t + I(x.npro^2) + I(x.tgif^2), \n\t\t data = train.dat, kernel = \"linear\", ranges = list(cost = c(0.001, 0.005, 0.01, 0.05, 0.1, 1, 5, 10)))\n\t\t\n\t\tsummary(tune.charity)\n\t\tbestmod = tune.charity$best.model\n\t\tsummary(bestmod)\n\t\t\n\t\tsvm.pred = predict(bestmod, valid.dat)\n\t\tsvm.table = table(predict = svm.pred, truth = valid.dat$y)\n\t\tsvm.mail = sum(svm.table[2,])\n\t\tsvm.mail.tp = svm.table[2,2]\n\t\tsvm.error = (svm.table[2,1]+svm.table[1,2])/2018\n\t\tsvm.profit = 14.5*svm.mail.tp - 2*svm.mail\n\t\t\n\t\tsvm.error #validation error rate: 0.1115\n\t\tsvm.mail #total mailings: 1,072\n\t\tsvm.profit #total profit: $11,239.50\n\t\t\t\n# PREDICTION MODELING\n\n\t\t# LEAST SQUARES REGRESSION\n\t\t\n\t\t#LEAST SQUARES MODEL (LM)\n\t\t\t\n\t\t\tmodel.ls3 = lm(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif,\n\t\t\t\t\t\tdata.train.std.y)\n\t\t\t\t\t\t\n\t\t\tpred.valid.ls3 = predict(model.ls3, newdata = data.valid.std.y) # validation predictions\n\t\t\tls3.mse = mean((y.valid - pred.valid.ls3)^2) # mean prediction error\n\t\t\tls3.se = sd((y.valid - pred.valid.ls3)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tls3.mse\n\t\t\tls3.se\n\t\t\t\n\t\t#BEST SUBSETS (BSS)\n\t\t\n\t\t\tbss.train.fit = regsubsets(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif,\n\t\t\t\tdata=data.train.std.y, nvmax=17)\n\t\t\t\t\n\t\t\twhich.min(summary(bss.train.fit)$bic)\n\t\t\tcoef(bss.train.fit,which.min(summary(bss.train.fit)$bic))\n\t\t\tpredict.regsubsets = function(object, newdata, id, ...){\n\t\t\t\tform = as.formula(object$call[[2]])\n\t\t\t\tmat = model.matrix(form, newdata)\n\t\t\t\tcoefi = coef(object, id = id)\n\t\t\t\txvars = names(coefi)\n\t\t\t\tmat[, xvars]%*%coefi\n\t\t\t}\n\t\t\tbss.pred = predict.regsubsets(bss.train.fit, data.valid.std.y, which.min(summary(bss.train.fit)$bic))\n\t\t\tbss.mse = mean((y.valid - bss.pred)^2) # mean prediction error\n\t\t\tbss.se = sd((y.valid - bss.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tbss.mse\n\t\t\tbss.se\n\t\n\t\t#BEST SUBSETS 10-FOLD VALIDATION (BSSF)\n\t\t\n\t\t\tk=10\n\t\t\tset.seed(53)\n\t\t\tbssf.folds = sample(1:k,nrow(data.train.std.y),replace=TRUE)\n\t\t\tbssf.cv.errors = matrix(NA, k, 10, dimnames=list(NULL, paste(1:10)))\n\t\t\tfor (j in 1:k){\n\t\t\t\tbssf.train.fit=regsubsets(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t\t tgif + tdon + tlag + I(tlag^2) + agif, \n\t\t\t\t\tdata=data.train.std.y[bssf.folds!=j,], nvmax=17)\n\t\t\t\tfor (i in 1:10){\n\t\t\t\t\tbssf.pred = predict(bssf.train.fit, data.train.std.y[bssf.folds==j,], id=i)\n\t\t\t\t\tbssf.cv.errors[j, i] = mean((bssf.pred - data.train.std.y$damt[bssf.folds==j])^2)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbssf.mcv.errors = apply(bssf.cv.errors, 2, mean)\n\t\t\twhich.min(bssf.mcv.errors) #Returns the number of variables in the Cross-Validation Selected model\n\t\t\tcoef(bssf.train.fit, which.min(bssf.mcv.errors)) #Returns the coefficients for the CV selected model\n\t\t\tbssf.pred = predict.regsubsets(bssf.train.fit, data.valid.std.y, which.min(bssf.mcv.errors)) #Predicts y using the CV Selected model\n\t\t\tbssf.mse = mean((y.valid - bssf.pred)^2) #Calculates test MSE for the CV Selected model\n\t\t\tbssf.se = sd((y.valid - bssf.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tbssf.mse\n\t\t\tbssf.se\n\t\t\t\n\t\t#RIDGE REGRESSION (RR)\n\t\t\n\t\t\t#make x matrix and y from data.train.std.y\n\t\t\trr.train.x = model.matrix(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif, data.train.std.y)[,-21]\n\t\t\trr.train.y = data.train.std.y$damt\n\t\t\trr.valid.x = model.matrix(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif, data.valid.std.y)[,-21]\n\t\t\trr.valid.y = data.valid.std.y$damt\n\t\t\t\n\t\t\tset.seed(53)\n\t\t\trr.cv.out = cv.glmnet(rr.train.x, rr.train.y, alpha=0)\n\t\t\t\n\t\t\trr.bestlam = rr.cv.out$lambda.min\n\t\t\trr.bestlam\n\t\t\t\n\t\t\trr.train.fit = glmnet(rr.train.x, rr.train.y, alpha=0, lambda=rr.bestlam)\n\t\t\tcoef(rr.train.fit)[, 1]\n\t\t\t\n\t\t\trr.pred = predict(rr.train.fit, s=rr.bestlam, newx=rr.valid.x)\n\t\t\trr.mse = mean((y.valid - rr.pred)^2) # mean prediction error\n\t\t\trr.se = sd((y.valid - rr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\trr.mse\n\t\t\trr.se\n\t\t\t\n\t\t#LASSO\n\t\t\n\t\t\tset.seed(53)\n\t\t\tlasso.cv.out = cv.glmnet(rr.train.x, rr.train.y, alpha=1)\n\t\t\t\n\t\t\tlasso.bestlam = lasso.cv.out$lambda.min\n\t\t\tlasso.bestlam\n\t\t\t\n\t\t\tlasso.train.fit = glmnet(rr.train.x, rr.train.y, alpha=1, lambda=lasso.bestlam)\n\t\t\tcoef(lasso.train.fit)[, 1]\n\t\t\t\n\t\t\tlasso.pred = predict(lasso.train.fit, s=lasso.bestlam, newx=rr.valid.x)\n\t\t\tlasso.mse = mean((y.valid - lasso.pred)^2)\n\t\t\tlasso.se = sd((y.valid - lasso.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tlasso.mse\n\t\t\tlasso.se\n\t\t\t\n\t\t#PRINCIPAL COMPONANTS\n\t\t\n\t\t\tset.seed(53)\n\t\t\tpcr.train.fit = pcr(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif,\n\t\t\t\tdata=data.train.std.y, scale=TRUE, validation=\"CV\")\n\t\t\t\n\t\t\tvalidationplot(pcr.train.fit,val.type=\"MSEP\")\n\t\t\t\n\t\t\t#PCR (M=10)\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=10)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t\t#PCR (M=13)\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=13)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t\t#PCR (M=16)\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=16)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t#PARTIAL LEAST SQUARES\n\t\t\n\t\t\tset.seed(53)\n\t\t\tpls.train.fit = plsr(damt ~ reg1 + reg2 + reg3 + reg4 + chld + hinc + \n\t\t\t wrat + I(wrat^2) + I(wrat^3) + I(wrat^4) + avhv + plow + npro + \n\t\t\t tgif + tdon + tlag + I(tlag^2) + agif,\n\t\t\t\tdata=data.train.std.y, scale=TRUE, validation=\"CV\")\n\t\t\t\n\t\t\tvalidationplot(pls.train.fit,val.type=\"MSEP\")\n\t\t\t\n\t\t\t#PLS (M=3)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=3)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t\t#PLS (M=7)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=7)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t\t#PLS (M=14)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=14)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t#GAM\n\n\t\t\t#GAM - removed correlated variables\n\t\t\tgam.train.fit3 = gam(damt ~ reg1 + reg2 + reg3 + reg4 + s(chld,3) + s(hinc, 3) + \n\t\t\t poly(wrat, 3) + s(avhv, 3) + s(plow, 4) + s(npro, 3) + \n\t\t\t s(tgif, 4) + s(tdon, 3) + poly(tlag, 2) + s(agif, 4),\n\t\t\t data=data.train.std.y)\n\t\t\t\n\t\t\tgam.pred = predict(gam.train.fit3, data.valid.std.y)\n\t\t\tgam.mse = mean((y.valid - gam.pred)^2) # mean prediction error\n\t\t\tgam.se = sd((y.valid - gam.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tgam.mse\n\t\t\tgam.se\n\t\t\t\n\t#MODEL LDAF FINAL CLASSIFICATION MODEL\n\n\t\tmodel.ldaF = lda(donr ~ reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + wrat + \n\t\t avhv + plow + npro + tgif + tdon + \n\t\t tlag + agif + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) + I(wrat^2) + \n\t\t I(npro^2) + I(tgif^2), \n\t\t\t\t\t data.train.std.c) # include additional terms on the fly using I()\n\t\t\n\t\tn.mail.valid = which.max(profit.ldaF)\n\t\ttr.rate = .1 # typical response rate is .1\n\t\tvr.rate = .5 # whereas validation response rate is .5\n\t\tadj.test.1 = (n.mail.valid/n.valid.c)/(vr.rate/tr.rate) # adjustment for mail yes\n\t\tadj.test.0 = ((n.valid.c - n.mail.valid)/n.valid.c)/((1 - vr.rate)/(1 - tr.rate)) # adjustment for mail no\n\t\tadj.test = adj.test.1/(adj.test.1+adj.test.0) # scale into a proportion\n\t\tn.mail.test = round(n.test*adj.test, 0) # calculate number of mailings for test set\n\t\tpost.test = predict(model.ldaF, data.test.std)$posterior[,2] # post probs for test data\n\t\t\n\t\tcutoff.test = sort(post.test, decreasing=T)[n.mail.test+1] # set cutoff based on n.mail.test\n\t\tchat.test = ifelse(post.test>cutoff.test, 1, 0) # mail to everyone above the cutoff\n\t\ttable(chat.test)\n\t\t\n\t#GAM1 FINAL PREDICTION MODEL\n\t\tyhat.test = predict(gam.train.fit3, newdata = data.test.std) # test predictions\n\t\t\n\t#OUTPUT\n\tip = data.frame(chat=chat.test, yhat=yhat.test) # data frame with two variables: chat and yhat\n\twrite.csv(ip, file=\"E:/STAT 897/Group Project/Report/Report Elements/ip.csv\", \n row.names=FALSE) # use group member initials for file name", "meta": {"hexsha": "11227594e40e02d2ed5e31a7d2a269e16d13b36d", "size": 22444, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Prep Classification and Prediction Analyis v6.r", "max_stars_repo_name": "ericsgagnon/psustat897groupproject", "max_stars_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "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 Prep Classification and Prediction Analyis v6.r", "max_issues_repo_name": "ericsgagnon/psustat897groupproject", "max_issues_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "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 Prep Classification and Prediction Analyis v6.r", "max_forks_repo_name": "ericsgagnon/psustat897groupproject", "max_forks_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "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.6965517241, "max_line_length": 135, "alphanum_fraction": 0.5936553199, "num_tokens": 7716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.669298221820872}} {"text": "options(digits = 2) #limits decimal points\n\nStudent <- c(\"John Davis\", \"Angela Williams\", \"Bullwinkle Moose\",\n \"David Jones\", \"Janice Markhammer\", \"Cheryl Cushing\",\n \"Reuven Ytzrhak\", \"Greg Knox\", \"Joel England\",\n \"Mary Rayburn\")\n \n Math <- c(502, 600, 412, 358, 495, 512, 410, 625, 573, 522)\n Science <- c(95, 99, 80, 82, 75, 85, 80, 95, 89, 86)\n English <- c(25, 22, 18, 15, 20, 28, 15, 30, 27, 18)\n \n roster <- data.frame(Student, Math, Science, English, stringsAsFactors = FALSE)\n \n z <- scale(roster[, 2:4]) #scale function provides in SD units\n \n score <- apply(z,1, mean) #calculate row means using mean function \n roster<- cbind(roster, score) #add to roster\n \n y<- quantile(score,c(.8,.6,.4,.2)) #quantile function gives %tile rankj\n roster$grade[score >= y[1]] <- \"A\"\n roster$grade[score < y[1] & score >=y[2]] <- \"B\"\n roster$grade[score < y[2] & score >=y[3]] <- \"C\"\n roster$grade[score < y[3] & score >=y[4]] <- \"D\"\n roster$grade[score < y[4]] <- \"F\"\n \n name<-strsplit((roster$Student), \" \") #extract last and first names\n lastname <- sapply(name, \"[\", 2) # 2nd element \n firstname <- sapply(name, \"[, 1) #1st element\n roster <- cbind(firstname, lastname, roster[,-1]) #add to roster drop name\n \n roster<- roster[order(lastname,firstname),] #sort by last and first names\n ", "meta": {"hexsha": "b9dfa286678484f92c98a0f64c4d2b6d8674815c", "size": 1308, "ext": "r", "lang": "R", "max_stars_repo_path": "Basic Graph/roster.r", "max_stars_repo_name": "loangelak/Data-Analysis-and-Graphics", "max_stars_repo_head_hexsha": "b48b0fb3f2cb2a69ae453532381ea4f2d98161f5", "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 Graph/roster.r", "max_issues_repo_name": "loangelak/Data-Analysis-and-Graphics", "max_issues_repo_head_hexsha": "b48b0fb3f2cb2a69ae453532381ea4f2d98161f5", "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 Graph/roster.r", "max_forks_repo_name": "loangelak/Data-Analysis-and-Graphics", "max_forks_repo_head_hexsha": "b48b0fb3f2cb2a69ae453532381ea4f2d98161f5", "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.875, "max_line_length": 81, "alphanum_fraction": 0.629969419, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6692449301547579}} {"text": "#' Activates the categories in an ART network\n#' \n#' This function returns a vector of category activations for the given \n#' input vector, weight matrix, and bias value\n#' @title ART_Activate_Categories\n#' @param input A vector of size NumFeatures that contains the input signal into the network\n#' @param weight Matrix of size NumFeatures-by-NumCategories which holds the weights of the network\n#' @param bias Constant that is used to differentiate between very similar category activation values\n#' @return Vector of size NumCategories that holds the activation value for each category\n#' @details The length of the INPUT vector must equal the number of rows in the WEIGHT matrix, \n#' and the BIAS value must be within the range [0, 1] (although values very near 0 are best).\n\nART_Activate_Categories = function(input, weight, bias)\n{ \n # Make sure the user supplied the required parameters.\n if(nargs() != 3)\n {\n stop('You must specify the 3 input parameters.');\n }\n \n # Check the size and range of the parameters.\n numFeatures=ncol(weight);\n numCategories= nrow(weight);\n \n if(length(input)!=numFeatures)\n {\n stop('The length of the input and rows of the weights do not match.');\n }\n if((bias < 0) | (bias > 1))\n {\n stop('The bias must be within the range [0, 1].');\n }\n \n # Set up the return variable.\n categoryActivation = matrix(1,numCategories,1);\n \n # Calculate the activation for each category.\n # This is done according to the following equation:\n # Activation(j) = |Input^Weight(j)| / (bias + |Weight(j)|)\n for (j in 1:numCategories) \n {\n matchVector = pmin(input, weight[j,]);\n weightLength = sum(weight[j,]);\n categoryActivation[j,1] = sum(matchVector) / (bias + weightLength);\n }\n \n return (categoryActivation);\n}", "meta": {"hexsha": "4c883e421256cc93f57f5c328250728b57108b58", "size": 1783, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ART_Activate_Categories.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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/ART_Activate_Categories.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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/ART_Activate_Categories.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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.1458333333, "max_line_length": 101, "alphanum_fraction": 0.7066741447, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.669215903743143}} {"text": "\n#------------------------------------ Dirichlet process et echantillonnage de Gibbs-------------------------------------------\nDirichlet<- function(observations,iterations,alpha) {\n nbrp <- c(length(observations[,1])) \n print(nbrp); \n ParamOfClusters <- list()\n saving <- rep(1,iterations)\n clusters <- rep(1,nrow(observations))\n for (i in 1:max(clusters)) ParamOfClusters [[i]] <-Param_Update(observations[clusters==i,]) \n for (m in 1:iterations) {\n for (i in 1:nrow(observations) ){\n \n nbrp [clusters[i]] <- nbrp [clusters[i]] - 1\n if (nbrp [clusters[i]]!=0) {\n\n ParamOfClusters [[clusters[i]]] <- Param_Update(observations[clusters == clusters[i],]) \n\n } else { \n ParamOfClusters [[ clusters[i] ]] <- NULL\n nbrp <- nbrp [-clusters[i]]\n clusters[ clusters>clusters[i] ] <- clusters[ clusters>clusters[i] ] - 1 \n }\n \n process <- log(c(nbrp,alpha)) \n for (k in 1:length(ParamOfClusters)){\n process[k] <- process[k] + LogofLik(ParamOfClusters[[k]],observations[i,]);\n }\n process <- exp(process - max(process)); \n process <- process / sum(process);\n \n \n clusters[i] <- Tirage_multinomial(process)\n if (length(nbrp ) < clusters[i]) nbrp [clusters[i]]<-0 \n nbrp [clusters[i]] <- nbrp [clusters[i]] + 1\n ParamOfClusters [[clusters[i]]] <- Param_Update(observations[clusters == clusters[i],])\n }\n\nsaving[m] <- max(clusters)\n}\nprint(saving);\nprint(table(factor(saving)));\nplot(observations,col=clusters)\nreturn(clusters);\n \n}\n\n#--------------------------------------Fonctions utilisées à l'intérieur de l'algorithme---------------------------------------------------\nTirage_multinomial <- function (x) {\n a <- runif(1)\n b <- 0\n for (i in 1:length(x)) {\n b <- b + x[i]\n if (a (x + a)^3(x - a + 1)\n \n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "f01b9e5033d3fd63e69c32740a890b4fae6915d7", "size": 298, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-factorize03.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-factorize03.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-factorize03.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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": 19.8666666667, "max_line_length": 63, "alphanum_fraction": 0.4899328859, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.668851478983277}} {"text": "#' Weighted Least Squares\n#'\n#' @param y outcome vector.\n#' @param x design matrix\n#' @param w weight matrix\n#' @param se character.\n#' How to calculate robust variance-covariance matrix\n#' (\"HC0\", \"HC1\", \"HC2\", \"HCj\", \"HC3\", and \"HC4\")\n#' If \"standard\", calculate conventional variance-covariance matrix\n#' @param cluster cluster variable.\n#' @param cholesky logical (default is TRUE).\n#' When solving normal equation, use cholesky decomposition.\n#'\n#' @examples\n#' \\dontrun{\n#' x <- cbind(x1 = rnorm(100), x2 = rnorm(100))\n#' y <- x[, 1] + 2 * x[, 2] + rnorm(100)\n#' w <- sample(c(1, 0.5), 100, TRUE)\n#' est <- lm_internal(y, x)\n#' est$estimate\n#' }\n#'\n#'\nwls <- function(y,\n x,\n w,\n se = \"HC0\",\n cluster,\n cholesky = TRUE) {\n # check matrix\n if (!is.matrix(y)) y <- matrix(y, ncol = 1)\n if (!is.matrix(x)) x <- as.matrix(x)\n x <- cbind(\"(Intercept)\" = 1, x)\n if (nrow(y) != nrow(x)) stop(\"different number of rows x and y\")\n if (missing(w)) w <- rep(1, nrow(x))\n omega <- diag(w)\n\n # output list\n output <- list()\n output$input$response <- y\n output$input$design <- x\n output$input$weights <- w\n\n # observation and degree of freedom\n n <- nrow(x)\n df <- nrow(x) - ncol(x)\n\n output$N <- n\n output$df <- df\n\n ##########################################################################\n # **solve normal equation**\n # Note: When using cholesky decomposition, there is another way to solve\n # 1. run `forwardsolve(t(cholesky), t(x) %*% w %*% y)`\n # 2. use its return value (ghat) and run `backsolve(cholesky, ghat)`\n ##########################################################################\n\n if (cholesky) {\n cholesky <- chol(t(x) %*% omega %*% x)\n xx <- solve(cholesky) %*% t(solve(cholesky))\n } else {\n xx <- solve(t(x) %*% omega %*% x)\n }\n\n p <- xx %*% t(x) %*% omega\n b <- p %*% y\n\n # predictions, residuals, and residual std.err.\n proj <- x %*% p\n yh <- proj %*% y\n eh <- y - yh\n\n yh <- c(yh)\n eh <- c(eh)\n\n s2 <- sum(eh ^ 2) / df\n\n output$yhat <- yh\n output$ehat <- eh\n output$resid.std.err <- s2\n\n # variance-covariance matrix\n if (missing(cluster)) {\n ## quotation\n standard <- rlang::quo(s2 * xx)\n hce <- rlang::quo(p %*% sigma %*% t(p))\n\n ## component of hce\n ## reference: https://economics.mit.edu/files/7422\n h <- diag(proj)\n util <- eh / (1 - h)\n mutil <- matrix(util, ncol = 1)\n sigma <- switch(se,\n \"HC0\" = diag(eh^2),\n \"HC1\" = diag(eh^2) * (n / df),\n \"HC2\" = diag(eh^2 / (1 - h)),\n \"HCj\" = (diag(util^2) - mutil %*% t(mutil) / n) * (n - 1) / n,\n \"HC3\" = diag(util^2),\n \"HC4\" = diag(eh^2 / (1 - h)^min(4, n * h / (n - df)))\n )\n\n vcov <- if (se == \"standard\") {\n rlang::eval_tidy(standard)\n } else {\n rlang::eval_tidy(hce, list(sigma = sigma))\n }\n\n output$vcov$matrix <- vcov\n output$vcov$type <- se\n } else {\n ## cluster-robust estimate of the variance matrix\n ## see http://cameron.econ.ucdavis.edu/research/\n ## Cameron_Miller_JHR_2015_February.pdf\n g <- unique(cluster)\n gvcov <- lapply(g, function(i) {\n bool <- cluster == i\n gx <- x[bool, ]\n gomega <- diag(w[bool])\n geh <- matrix(eh[bool], ncol = 1)\n t(gx) %*% gomega %*% geh %*% t(geh) %*% gomega %*% gx\n })\n gvcov <- Reduce(\"+\", gvcov)\n vcov <- xx %*% gvcov %*% xx\n\n output$vcov$matrix <- vcov\n output$vcov$type <- \"cluster-robust\"\n output$vcov$cluster <- cluster\n\n df <- length(g) - 1\n\n output$df <- df\n }\n\n # create coefficient table\n bmat <- cbind(b, sqrt(diag(vcov)))\n t <- sapply(seq_len(nrow(bmat)), function(i) bmat[i, 1] / bmat[i, 2])\n bmat <- cbind(bmat, t)\n p <- apply(bmat, 2, function(t) 2 * pt(-abs(t), df))[, 3]\n bmat <- cbind(bmat, p)\n colnames(bmat) <- c(\"Estimate\", \"Std.Err.\", \"t\", \"P(>|t|)\")\n\n output$estimate <- bmat\n output\n}\n\n#'\n#' Fit weighted least squares\n#'\n#' @param y outcome variable\n#' @param data data which is generated by [clean_rd_data()]\n#' @param global logical. use all observations?\n#' @param kernel character of kernel density (\"uniform\" or \"triangular\")\n#' @param bw bandwidth.\n#' @param point value of the running variable that\n#' the kernel weights weigh the most.\n#' @param \\dots se and cholesky arguments\n#'\n#' @importFrom rlang eval_tidy\n#' @importFrom rlang as_label\n#'\nfit_wls <- function(y,\n data,\n global = TRUE,\n kernel,\n bw,\n point,\n ...){\n # outcome vector and design matrix\n args <- list(...)\n quo_y <- rlang::enquo(y)\n args$y <- rlang::eval_tidy(quo_y, data)\n\n exclude_x <- c(rlang::as_label(quo_y), \"(weights)\", \"(cluster)\", \"d\")\n args$x <- as.matrix(data[, !(names(data) %in% exclude_x), drop = FALSE])\n\n # weight vector\n if (global) {\n if (!is.null(data$\"(weights)\")) args$w <- data$\"(weights)\"\n } else {\n w <- if (!is.null(data$\"(weights)\")) data$\"(weights)\" else 1\n\n u <- abs(data$x - point) / bw\n kw <- switch(kernel,\n \"triangular\" = ifelse(u <= 1, (1 - u), 0),\n \"uniform\" = ifelse(u <= 1, 1 / 2, 0)\n )\n\n args$w <- w * kw\n }\n\n # cluster vector\n if (!is.null(data$\"(cluster)\")) args$cluster <- data$\"(cluster)\"\n\n # fit weighted least squares\n fit.wls <- do.call(\"wls\", args)\n\n # output\n if (!global) {\n if (!is.null(data$\"(weights)\")) {\n fit.wls$input$local.wls$given.w <- w\n }\n fit.wls$input$local.wls$kernel.w <- kw\n fit.wls$input$local.wls$kernel <- kernel\n fit.wls$input$local.wls$data.point <- point\n fit.wls$input$local.wls$bandwidth <- bw\n fit.wls$input$local.wls$effective.nobs <- sum(kw > 0)\n }\n\n class(fit.wls) <- append(\"fit_wls\", class(fit.wls))\n fit.wls\n}\n\n#' Re-fit Local Linear Regression\n#'\n#' @param object object with fit_wls class\n#' @param extend numeric vector outside input data\n#' @param force logical. Whether to ignore error about estimation\n#'\n#' @importFrom rlang quo\n#' @importFrom rlang eval_tidy\n#' @importFrom dplyr bind_rows\n#' @importFrom stats predict\n#'\nfit_local_lm <- function(object,\n extend,\n force = TRUE) {\n outcome <- l <- NULL\n\n # recover data from input elements\n dt <- data.frame(object$input$response, object$input$design[, -1])\n colnames(dt) <- c(\"outcome\", colnames(object$input$design)[-1])\n\n if (!is.null(object$input$local.wls$given.w)) {\n dt$\"(weights)\" <- object$input$local.wls$given.w\n }\n\n if (object$vcov$type == \"cluster-robust\") {\n dt$\"(cluster)\" <- object$vcov$cluster\n }\n\n # list of arguments for fit_wls\n args <- list()\n args$y <- rlang::quo(outcome)\n args$global <- FALSE\n args$data <- dt\n args$se <- object$vcov$type\n args$kernel <- object$input$local.wls$kernel\n args$bw <- object$input$local.wls$bandwidth\n\n # collect data point\n point <- unique(dt$x)\n if (!missing(extend)) point <- unique(c(extend, point))\n point <- sort(point)\n\n # fittted\n fit_quo <- rlang::quo(predict(do.call(\"fit_wls\", l)))\n pred <- lapply(point, function(x) {\n args$point <- x\n if (force) {\n tryCatch({\n rlang::eval_tidy(fit_quo, list(l = args))\n }, error = function(e) {})\n } else {\n rlang::eval_tidy(fit_quo, list(l = args))\n }\n })\n\n # output\n dplyr::bind_rows(pred)\n\n}\n", "meta": {"hexsha": "302440b607633665f34aa01d2a8923925a32ea8f", "size": 7340, "ext": "r", "lang": "R", "max_stars_repo_path": "R/internal-lm.r", "max_stars_repo_name": "KatoPachi/discreteRD", "max_stars_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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/internal-lm.r", "max_issues_repo_name": "KatoPachi/discreteRD", "max_issues_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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/internal-lm.r", "max_forks_repo_name": "KatoPachi/discreteRD", "max_forks_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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.9852941176, "max_line_length": 76, "alphanum_fraction": 0.559400545, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6687687842221994}} {"text": "#' @title folded_root\n#' @description This is a placeholder for a description.\n#' @param x default is x\n#' @param p default is \\code{1}.\n#' @param inverse default is \\code{NULL}.\n#' @param ... other arguments passed to methods\n#' @return This is a placeholder for what it returns.\n#' @author Jae Choi, \\email{choi.jae.seok@gmail.com}\n#' @export\nfolded_root = function(x, p=1, inverse=FALSE, ... ) {\n # as with Box-Cox transformation as (yp−1)/p,\n # limit when p→0, the logit function logit(p)=log(p)−log(1−p).\n # reference: https://stats.stackexchange.com/questions/399916/how-to-back-transform-a-folded-root/400119\n # default p = 1 .. ie. expand scale from (0,1) to (-1, 1)\n # if p = 1/2 .. ie. expand scale from (0,1) to (-2, 2), etc\n # if p -> 0 .. ie. expand scale from (0,1) to (-Inf, Inf), .. ie. logit ..etc\n\n if (!inverse) {\n i = which(x < 0)\n if ( length(i) > 0 ) {\n x[i] = 0\n message( \"folded_root:: x was less than 0; truncating to 0\" )\n }\n i = which(x > 1)\n if ( length(i) > 0 ) {\n x[i] = 1\n message( \"folded_root:: x was greater than 1; truncating to 1\" )\n }\n (x^p - (1-x)^p)/p\n } else {\n out = NULL\n Q = x # rename to make it less confusing\n for ( i in 1:length(Q)) {\n q = Q[i]\n out = c(out,\n stats::uniroot( function(z) { folded_root(z, p) - q} , interval=c(0, 1), extendInt=\"no\", ...)$root\n )\n }\n return(out)\n }\n}\n", "meta": {"hexsha": "cbbcd2ecde11f581dcec6a2975a0ad42196c5210", "size": 1433, "ext": "r", "lang": "R", "max_stars_repo_path": "R/folded_root.r", "max_stars_repo_name": "jae0/adapt", "max_stars_repo_head_hexsha": "05e7ec1bf3fd328f0045491d4b589656940756f5", "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/folded_root.r", "max_issues_repo_name": "jae0/adapt", "max_issues_repo_head_hexsha": "05e7ec1bf3fd328f0045491d4b589656940756f5", "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/folded_root.r", "max_forks_repo_name": "jae0/adapt", "max_forks_repo_head_hexsha": "05e7ec1bf3fd328f0045491d4b589656940756f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-22T23:44:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T13:32:34.000Z", "avg_line_length": 34.119047619, "max_line_length": 106, "alphanum_fraction": 0.5729239358, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6684742426924247}} {"text": "#' MLE for the Zero-truncated Poisson Lognormal distribution\n#'\n#' `ztplnMLE` fits the Zero-truncated Poisson lognormal distribution to data and\n#' estimates parameters mean `mu` and standard deviation `sig` in the lognormal\n#' distribution\n#'\n#' The function searches the maximum likelihood estimates of mean `mu` and\n#' standard deviation `sig` using the optimization procedures in\n#' \\code{\\link{nlminb}}.\n#'\n#' @param n a integer vector of counts\n#' @param lower_mu,upper_mu numeric values of lower and upper bounds for mean of\n#' the variables's natrual logarithm.\n#' @param lower_sig,upper_sig numeric values of lower and upper bounds for\n#' standard deviatoin of the variables's natrual logarithm\n#' @param type1 logical; if TRUE, Use type 1 ztpln else use type 2. \n#' @return \\item{convergence}{An integer code. 0 indicates successful\n#' convergence.}\n#' @return \\item{iterations}{Number of iterations performed.}\n#' @return \\item{message}{A character string giving any additional information\n#' returned by the optimizer, or NULL. For details, see PORT documentation.}\n#' @return \\item{evaluation}{Number of objective function and gradient function\n#' evaluations}\n#' @return \\item{mu}{Maximum likelihood estimates of mu}\n#' @return \\item{sig}{Maximum likelihood estimates of sig}\n#' @return \\item{loglik}{loglikelihood}\n#' @examples\n#' y <- rztpln(100, 3, 2)\n#' ztplnMLE(y)\n#' @export\nztplnMLE <- function(n,\n lower_mu = 0,\n upper_mu = log(max(n)),\n lower_sig = 0.001,\n upper_sig = 10,\n type1 = TRUE) {\n\n n <- n[n > 0]\n # set initial values using medians and sd for fast convergence\n params <- c(log(median(n)), sd(log(n)))\n\n loglik <- function(params, n) {\n mu <- params[1]\n sig <- params[2]\n if (type1) {\n lik <- do_dztpln(n, mu, sig)\n } else lik <- do_dztpln2(n, mu, sig)\n return(-sum(log(lik), na.rm = TRUE))\n }\n # faster than Nelder-Mead and BFGS in optim\n fit <- try(nlminb(params, # initial parameters\n loglik, # function to be minimized (i.e., -logLike)\n gradient = NULL,\n lower = c(lower_mu, lower_sig),\n upper = c(upper_mu, upper_sig),\n n = n,\n TRUE))\n fit$mu <- fit$par[1]\n fit$sig <- fit$par[2]\n fit$par <- NULL\n fit$loglik <- -fit$objective\n fit$objective <- NULL\n return(fit)\n}\n", "meta": {"hexsha": "856e885237cf4a3ce21ecd10528115315c2f2871", "size": 2457, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ztplnMLE.r", "max_stars_repo_name": "mattocci27/poilog2", "max_stars_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "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/ztplnMLE.r", "max_issues_repo_name": "mattocci27/poilog2", "max_issues_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "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/ztplnMLE.r", "max_forks_repo_name": "mattocci27/poilog2", "max_forks_repo_head_hexsha": "5d2a6e6dc4238a9bb61a02126a99fe8b8205ef35", "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.8, "max_line_length": 80, "alphanum_fraction": 0.6357346357, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389111, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6683577949012511}} {"text": "#' @useDynLib cop cop_allreduce_mat_qr\nqr_reducer = function(x, root, comm=0L, type)\n{\n comm_check_is_matrix(x, comm)\n comm_check_common_matrix_dims(x, comm)\n comm_check_is_int(root, comm)\n type = comm.match.arg(tolower(type), TYPES_STR_NUMERIC, comm=comm)\n type_int = type_str2int(type)\n \n root = as.integer(root)\n \n if (!is.double(x))\n storage.mode(x) = \"double\"\n \n comm = as.integer(comm)\n comm_ptr = pbdMPI::get.mpi.comm.ptr(comm)\n \n ret = .Call(cop_allreduce_mat_qr, x, comm_ptr, root, type_int)\n ret\n}\n\n\n\n#' QR Reduction\n#' \n#' Given an R matrix from a QR factorization on each process, this computes the\n#' R matrix which is conceptually calculated by \"stacking\" all R matrices on top\n#' of each other (like \\code{do.call(rbind, R_list)}). The way this is actually\n#' calculated is much more memory efficient, and probably more run time\n#' efficient as well, if the local R matrices aren't very small.\n#' \n#' This can be used to create a TSQR. If the tall matrix is split by rows across\n#' processes, compute the R matrix on the local chunk and then hand it to\n#' \\code{qr_reduce()}.\n#' \n#' @details\n#' This works by defining a custom MPI data type (dense matrix) with a custom\n#' reduction operation (given 2 R matrices, \"stack\" them, compute the stacked\n#' QR and emit R). Each local operation uses the LAPACK functions\n#' \\code{_geqp3()}, similar to R's \\code{qr()} with \\code{LAPACK=TRUE}.\n#' \n#' @param x\n#' The input data. Should be a numeric matrix. The matrix should be the same\n#' dimensions across all processes.\n#' @param comm\n#' MPI communicator number.\n#' @param type\n#' The precision used for the intermediate calculations. Should be one of\n#' \"double\" or \"float\".\n#' @param root\n#' MPI rank that should receive the return in the non-all version.\n#' \n#' @return\n#' If the all version is called or if the calling rank is equal to \\code{root},\n#' then a numeric matrix is returned, and otherwise \\code{NULL}.\n#' \n#' @examples\n#' \\dontrun{\n#' suppressMessages(library(cop))\n#' \n#' x = matrix(1:4, 2) + 10*comm.rank()\n#' out = qr_reduce(x)\n#' mpi_print(out)\n#' \n#' finalize()\n#' }\n#' \n#' @seealso \\code{\\link{cop_allreduce}()}\n#' \n#' @name qr_allreduce\n#' @rdname qr_allreduce\nNULL\n\n\n\n#' @rdname qr_allreduce\n#' @export\nqr_allreduce = function(x, comm=0L, type=\"double\")\n{\n qr_reducer(x, root=REDUCE_TO_ALL, comm=comm, type=type)\n}\n\n#' @rdname qr_allreduce\n#' @export\nqr_reduce = function(x, root=0L, comm=0L, type=\"double\")\n{\n qr_reducer(x, root=root, comm=comm, type=type)\n}\n", "meta": {"hexsha": "d4deefdafa3010301092334879253abc199ab964", "size": 2514, "ext": "r", "lang": "R", "max_stars_repo_path": "R/qr_allreduce.r", "max_stars_repo_name": "RBigData/cop", "max_stars_repo_head_hexsha": "00dd424f9e02c53ec88c999bf5ed265c1e8e01a3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-07T00:06:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T00:06:58.000Z", "max_issues_repo_path": "R/qr_allreduce.r", "max_issues_repo_name": "RBigData/cop", "max_issues_repo_head_hexsha": "00dd424f9e02c53ec88c999bf5ed265c1e8e01a3", "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/qr_allreduce.r", "max_forks_repo_name": "RBigData/cop", "max_forks_repo_head_hexsha": "00dd424f9e02c53ec88c999bf5ed265c1e8e01a3", "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": 28.2471910112, "max_line_length": 80, "alphanum_fraction": 0.6980906921, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6683254735252847}} {"text": "# Calculate temperature uncertainty and offset relative to pre-existing calibrations\r\n\r\nTemperature_offset <- function(D47_mean, D47_err, known_T, slope, int){\r\n mean_T <- sqrt(slope * 10 ^ 6 / (D47_mean - int)) - 273.15\r\n diff_T <- mean_T - known_T\r\n T_upr <- sqrt(slope * 10 ^ 6 / (D47_mean - D47_err - int)) - 273.15\r\n diff_T_upr <- T_upr - known_T\r\n T_lwr <- sqrt(slope * 10 ^ 6 / (D47_mean + D47_err - int)) - 273.15\r\n diff_T_lwr <- T_lwr - known_T\r\n T_err <- (T_upr - T_lwr) / 2\r\n result <- c(mean_T, T_upr, T_lwr, diff_T, diff_T_upr, diff_T_lwr, T_err)\r\n names(result) <- c(\"reconstructed Temperature\", \"max reconstructed Temperature\", \"min reconstructed Temperature\", \"Temperature offset\", \"max Temperature offset\", \"min Temperature offset\", \"Temperature uncertainty\")\r\n return(result)\r\n}\r\n", "meta": {"hexsha": "81c1c53003df895434f887ebbd3d13918b996f07", "size": 828, "ext": "r", "lang": "R", "max_stars_repo_path": "04_Temperature_offset.r", "max_stars_repo_name": "japhir/Aragonite_clumped", "max_stars_repo_head_hexsha": "498ccff398279b18ed176aaeac1faa0415659419", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-27T09:11:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T09:11:14.000Z", "max_issues_repo_path": "04_Temperature_offset.r", "max_issues_repo_name": "japhir/Aragonite_clumped", "max_issues_repo_head_hexsha": "498ccff398279b18ed176aaeac1faa0415659419", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:17:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T11:17:53.000Z", "max_forks_repo_path": "04_Temperature_offset.r", "max_forks_repo_name": "japhir/Aragonite_clumped", "max_forks_repo_head_hexsha": "498ccff398279b18ed176aaeac1faa0415659419", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-27T09:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T09:24:23.000Z", "avg_line_length": 55.2, "max_line_length": 219, "alphanum_fraction": 0.672705314, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6682552828814413}} {"text": "# Covariance structure: Compound symmetry\n#\n# This function generates a covariance matrix with compound symmetry structure.\n#\n# @param p Dimension.\n# @param rho Correlation strength.\n# @return A covariance matrix (p by p).\n# @export\n# @examples\n# library(NRRR)\n# CorrCS(10, 0.5)\nCorrCS <- function(p,rho){\n Sigma <- matrix(nrow=p,ncol=p,rho)\n diag(Sigma) <- 1\n Sigma\n}\n\n# Covariance structure: Autoregressive\n#\n# This function generates a covariance matrix with autoregressive structure.\n#\n# @param p Dimension.\n# @param rho Correlation strength.\n# @return A covariance matrix (p by p).\n# @export\n# @examples\n# library(NRRR)\n# CorrAR(10, 0.5)\nCorrAR <- function(p,rho){\n Sigma <- matrix(nrow=p,ncol=p,NA)\n for(i in 1:p){\n for(j in 1:p){\n Sigma[i,j] <- rho^(abs(i-j))\n }\n }\n Sigma\n}\n\n# Compute || Y - XC ||_F^2\n#\n# This function computes the sum of squared errors\n# with given (A,B,U,V) and (X,Y).\n#\n# @param Y Response matrix with n rows and jy*d columns.\n# @param X Design matrix with n rows and jx*p columns.\n# @param Ag Matrix U.\n# @param Bg Matrix V.\n# @param Al Matrix A.\n# @param Bl Matrix B.\n# @param jx Number of basis functions to expand x(s).\n# @param jy Number of basis functions to expand y(t).\n# @export\n# @return The returned items\n# \\item{C}{the NRRR estimator of the coefficient matrix C.}\n# \\item{XC}{a matrix, prediction of Y.}\n# \\item{E}{a matrix, estimated error matrix.}\n# \\item{sse,obj}{ a scaler, the sum of squared errors.}\nObj <- function(Y,X,Ag,Bg,Al,Bl,jx,jy){\n\n if(nrow(Bg)!=ncol(Bg)){\n Bl <- kronecker(diag(jx),Bg)%*%Bl\n }\n if(nrow(Ag)!=ncol(Ag)){\n Al <- kronecker(diag(jy),Ag)%*%Al\n }\n C <- Bl%*%t(Al)\n XC <- X%*%C\n E <- Y - XC\n sse <- sum(E^2)\n\n return(list(C=C,XC=XC,E=E,sse=sse,obj=sse))\n}\n\n\ncv.rrr <- function (Y,\n X,\n nfold = 10,\n maxrank = min(dim(Y), dim(X)),\n norder = NULL,\n coefSVD = FALSE)\n{\n ## record function call\n Call <- match.call()\n\n p <- ncol(X)\n q <- ncol(Y)\n n <- nrow(Y)\n\n ndel <- round(n / nfold)\n if (is.null(norder))\n norder <- sample(seq_len(n), n)\n\n cr_path <- matrix(ncol = nfold, nrow = maxrank + 1, NA)\n for (f in seq_len(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 idkeep <- (seq_len(n))[-iddel]\n Xf <- X[-iddel,]\n Xfdel <- X[iddel,]\n Yf <- Y[-iddel,]\n Yfdel <- Y[iddel,]\n ini <- rrr.fit(Yf, Xf, nrank = maxrank, coefSVD = coefSVD)\n C_ls <- ini$coef.ls\n A <- ini$A\n tempFit <- Xfdel %*% C_ls\n tempC <- matrix(nrow = q, ncol = q, 0)\n for (i in seq_len(maxrank)) {\n tempC <- tempC + tcrossprod(A[, i])\n cr_path[i + 1, f] <-\n sum((Yfdel - tempFit %*% tempC) ^ 2)\n }\n cr_path[1, f] <- sum(Yfdel ^ 2)\n }\n index <- order(colSums(cr_path))\n crerr <- rowSums(cr_path[, index]) / length(index) * nfold\n minid <- which.min(crerr)\n rankest <- minid - 1\n ini <- rrr.fit(Y, X, nrank = maxrank)\n C_ls <- ini$coef.ls\n A <- ini$A\n\n out <- if (identical(rankest, 0)) {\n list(\n call = Call,\n cr.path = cr_path,\n cr.error = crerr,\n norder = norder,\n coef = matrix(0, nrow = p, ncol = q),\n rank = 0,\n coef.ls = C_ls\n )\n }\n else {\n list(\n call = Call,\n cr.path = cr_path,\n cr.error = crerr,\n norder = norder,\n coef.ls = C_ls,\n coef = C_ls %*% tcrossprod(A[, seq_len(rankest)]),\n rank = rankest\n )\n }\n #class(out) <- \"cv.rrr\"\n out\n}\n\n\n\nrrr.fit <- function(Y,\n X,\n nrank = 1,\n weight = NULL,\n coefSVD = FALSE)\n{\n Call <- match.call()\n\n q <- ncol(Y)\n n <- nrow(Y)\n p <- ncol(X)\n stopifnot(n == nrow(X))\n\n S_yx <- crossprod(Y, X)\n S_xx <- crossprod(X)\n\n ## FIXME: 0.1 is too arbitrary\n S_xx_inv <- tryCatch(\n MASS::ginv(S_xx),\n error = function(e)\n solve(S_xx + 0.1 * diag(p))\n )\n\n ## FIXME: if weighted, this needs to be weighted too\n C_ls <- tcrossprod(S_xx_inv, S_yx)\n\n if (!is.null(weight)) {\n stopifnot(nrow(weight) == q && ncol(weight) == q)\n eigenGm <- eigen(weight)\n ## FIXME: ensure eigen success?\n ## sqrtGm <- tcrossprod(eigenGm$vectors * sqrt(eigenGm$values),\n ## eigenGm$vectors)\n ## sqrtinvGm <- tcrossprod(eigenGm$vectors / sqrt(eigenGm$values),\n ## eigenGm$vectors)\n sqrtGm <- eigenGm$vectors %*% (sqrt(eigenGm$values) *\n t(eigenGm$vectors))\n sqrtinvGm <- eigenGm$vectors %*% (1 / sqrt(eigenGm$values) *\n t(eigenGm$vectors))\n\n XC <- X %*% C_ls %*% sqrtGm\n ## FIXME: SVD may not converge\n ## svdXC <- tryCatch(svd(XC,nu=nrank,nv=nrank),error=function(e)2)\n svdXC <- svd(XC, nrank, nrank)\n A <- svdXC$v[, 1:nrank]\n Ad <- (svdXC$d[1:nrank]) ^ 2\n AA <- tcrossprod(A)\n C_rr <- C_ls %*% sqrtGm %*% AA %*% sqrtinvGm\n } else {\n ## unweighted\n XC <- X %*% C_ls\n svdXC <- svd(XC, nrank, nrank)\n A <- svdXC$v[, 1:nrank]\n Ad <- (svdXC$d[1:nrank]) ^ 2\n AA <- tcrossprod(A)\n C_rr <- C_ls %*% AA\n }\n\n ret <- list(\n call = Call,\n coef = C_rr,\n coef.ls = C_ls,\n fitted = X %*% C_rr,\n fitted.ls = XC,\n A = A,\n Ad = Ad,\n rank = nrank\n )\n\n if (coefSVD) {\n coefSVD <- svd(C_rr, nrank, nrank)\n coefSVD$d <- coefSVD$d[1:nrank]\n coefSVD$u <- coefSVD$u[, 1:nrank, drop = FALSE]\n coefSVD$v <- coefSVD$v[, 1:nrank, drop = FALSE]\n ret <- c(ret, list(coefSVD = coefSVD))\n }\n\n #class(ret) <- \"rrr.fit\"\n ret\n}\n\nrrs.fit <- function(Y,\n X,\n nrank = min(ncol(Y), ncol(X)),\n lambda = 1,\n coefSVD = FALSE)\n{\n Call <- match.call()\n\n q <- ncol(Y)\n n <- nrow(Y)\n p <- ncol(X)\n\n S_yx <- t(Y) %*% X\n ## This is a key difference\n S_xx <- t(X) %*% X + lambda * diag(p)\n\n ## S_xx_inv <- tryCatch(solve(S_xx+0.1*diag(p)),error=function(e)ginv(S_xx))\n ## S_xx_inv <- ginv(S_xx)\n ## Use the Woodbury matrix identity\n if (lambda != 0) {\n S_xx_inv <- 1 / lambda * diag(p) -\n lambda ^ (-2) * t(X) %*% MASS::ginv(diag(n) + lambda ^ (-1) * X %*%\n t(X)) %*% X\n } else{\n S_xx_inv <- MASS::ginv(S_xx)\n if (sum(is.na(S_xx_inv)) > 0) {\n S_xx_inv <- solve(S_xx + 0.1 * diag(p))\n }\n }\n\n C_ls <- S_xx_inv %*% t(S_yx)\n\n ypy.svd <- TRUE\n ##if(ypy.svd){\n ##This is another key difference\n XC <- rbind(X, sqrt(lambda) * diag(p)) %*% C_ls\n svdXC <- tryCatch(\n svd(XC, nu = nrank, nv = nrank),\n error = function(e)\n 2)\n if (tryCatch(\n svdXC == 2,\n error = function(e)\n 3) == 3) {\n A <- svdXC$v[, 1:nrank]\n Ad <- (svdXC$d[1:nrank]) ^ 2\n } else{\n ypy.svd <- FALSE\n }\n #}\n if (!ypy.svd) {\n SS <- S_yx %*% C_ls\n SS <- (SS + t(SS)) / 2\n eigenSS <- eigen(SS, symmetric = TRUE)\n A <- as.matrix(eigenSS$vectors[, 1:nrank])\n Ad <- eigenSS$values[1:nrank]\n }\n\n AA <- A %*% t(A)\n C_rr <- C_ls %*% AA\n\n ## if(c.svd){\n ## svd_C <- svd(C_rr,nv=nrank,nu=nrank)\n ## U <- as.matrix(svd_C$u[,1:nrank])\n ## V <- as.matrix(svd_C$v[,1:nrank])\n ## D <- diag(svd_C$d[1:nrank],nrow=nrank)\n ##\n ## ####return ls estimator C_ls, reduced-rank estimator C_rr\n ## ####return SVD of C_rr\n ## list(A=A,Ad=Ad,C_ls=C_ls,C_rr=C_rr,U=U,V=V,D=D,C=C_rr,rank=nrank)\n ## }else{\n ## list(A=A,Ad=Ad,C_ls=C_ls,C_rr=C_rr,C=C_rr,rank=nrank)\n ## }\n\n ret <- list(\n call = Call,\n coef = C_rr,\n coef.ls = C_ls,\n fitted = X %*% C_rr,\n fitted.ls = XC,\n A = A,\n Ad = Ad,\n nrank = nrank\n )\n\n if (coefSVD) {\n coefSVD <- svd(C_rr, nrank, nrank)\n coefSVD$d <- coefSVD$d[1:nrank]\n ret <- c(ret, list(coefSVD = coefSVD))\n }\n\n #class(ret) <- \"rrs.fit\"\n ret\n}\n\n\n\n\n\n", "meta": {"hexsha": "769d22fb6eab2792c867de67d10bb759e4b67452", "size": 8004, "ext": "r", "lang": "R", "max_stars_repo_path": "R/tools.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/tools.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/tools.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": 23.8925373134, "max_line_length": 79, "alphanum_fraction": 0.5266116942, "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.668208980241892}} {"text": "#' Lambda\n#' \n#' Seasonal model for the intensity function, \\eqn{\\lambda(t) = a + b + b \\sin(c\\,2 \\pi/365 + x 2 \\,\\pi / 365)}.\n#' \n#' @param x \\code{numeric} vector of time points.\n#' @param params \\code{numeric} vector of parameters of length = 4.\n#' @param names A vector. Can be used to label \n#' @return a \\code{numeric} vector of the same length as \\code{x}.\n#' @examples\n#' lambda(c(1,2,3,4,5,6), c(1,1,1,1) )\nlambda<-function(x, params, names=F){ \n p1<-params[1]\n p2<-params[2]\n p3<-params[3]\n p4<-params[4]\n # period = 365 # (days)\n period = 52 # (weeks)\n \n ret = p1 + p2 + (p2 + p4 * x)* sin(2 * pi / period * p3 + x * 2 * pi / period) + p4* x\n \n if(names){\n ret = c(0, ret)\n names(ret) = c('NA', 0:(length(ret)-2))\n return(ret)\n }else{\n return(ret) \n }\n}\n\n\n#' Negative log-likelihood\n#'\n#' \\eqn{l(\\lambda) = \\log L(\\lambda) = - \\int_0^T\\lambda(x) dx + \\sum_{i=1}^n\\log \\lambda(x_i)}\n#'\n#' @param params A \\code{numeric} vector of parameters of length = 4.\n#' @param data A \\code{numeric} vector of event times.\n#' @return \\code{numeric}.\n#' @examples\n#' neg.log.like(c(1,1,1,1),c(1,2,3,4,5,6))\nneg.log.like<-function(params, data){\n lower<-min(data)\n upper<-max(data)\n integrate(lambda,lower,upper,params,subdivisions = 5000)$value - sum(log(lambda(data,params)))\n}\n\n\n\n#' Optimize function \\code{neg.log.like} conditioned on having the last parameter fixed.\n#' \n#' @param data A \\code{numeric} vector of event times.\n#' @param cpar A \\code{numeric}.\n#' @param iteration This is the maximum number of interations allowed for the function \\code{optimx}.\n#' @return 2D 4x2 matrix.\n#' @importFrom optimx optimx\n#' @examples\n#' cmle1(data, 1, iterations=20)\ncmle1<-function(data, cpar, iterations=10000){\n fn<-function(par){\n if (all(par>c(0,2,0)) & all(par 0.1)){\n # res = 1000000 * par[4] ^ 2\n # }\n res = optimize(fn, interval = c(0,10), tol = 0.00001)\n return(res$minimum)\n}\n\n#' Estimate the parameters for the seasonal model given the aggregated vector of event times.\n#'\n#' Optimize the function \\code{neg.log.like} recursively calling \\code{clme1} and \\code{cmle2}.\n#' \n#' @param data A \\code{numeric} vector of event times.\n#' @param n.cycles \\code{integer}. Number of times the conditional optimizers are called.#\n#' @param start \\code{numeric}. Starting parameters (not yet implemented).\n#' @param save.on.dir \\code{logical}. If TRUE, will save the inferred parameter in `timefactor_parameters.RData`.\n#' @return \\code{numeric}. A 2D 2x4 matrix with the estimated parameters.\n#' @examples\n#' cmle(data)\ncmle<-function(data, n.cycles=10, start=NULL, save.on.dir=TRUE){\n par = cmle1(data, 0)\n trace = matrix(data=0, nrow = n.cycles, ncol = 4)\n for (i in 1:n.cycles){\n cat(\"Estimating parameters for temporal trend, step \", i, \" of \", n.cycles, \".\\r\")\n trace[i,1:3] = par\n par1 = cmle2(data, par)\n trace[i,4] = par1\n par = cmle1(data, par1)\n }\n par1 = cmle2(data, par)\n Parameters = c(par, par1)\n trace[i,] = Parameters\n attributes(Parameters) = list(trace=trace)\n if(save.on.dir){\n save.and.tell('Parameters', file=file.path(getwd(), paste0('timefactor_parameters.RData')))\n }\n return(Parameters)\n}\n\n\n#' Lambda\n#' \n#' Seasonal model for the intensity function, \\eqn{\\lambda(t) = a + b + b \\sin(c\\,2 \\pi/365 + x 2 \\,\\pi / 365)}.\n#'\n#' @inheritParams lambda\n#' @return a \\code{numeric} vector of the same length as \\code{x}.\n#' @examples\n#' predict.cmle(c(1,2,3,4,5,6), c(1,1,1,1) )\npredict.cmle<-lambda\n\npredict.cmle.ci<-function(x, parameters){\n data.frame(upper=qpois(0.975,lambda(x,parameters)),\n lower=qpois(0.025,lambda(x,parameters)))\n}\n\nexpand.histogram<-function(histo){\n Histo = data.frame(Names = as.integer(names(histo)), freq = unlist(histo))\n return(unlist(do.call(c, apply(Histo, 1, function(x){rep(x[1], x[2]) }) )))\n}\n\nLoess<-function(counts, span = 0.2){\n df = data.frame(time = 1:length(counts), counts = counts)\n loess(counts ~ time, df, span=span)\n}\n\npredict.Loess<-function(x, fit){\n df = data.frame(time = x)\n predict(fit, df)\n}\n\npredict.Loess.ci<-function(x, fit){\n df = data.frame(time = x)\n data.frame(upper= unlist(-predict(fit, df, se = T)[['se.fit']] + predict(fit, df, se = T)[['fit']]),\n lower= unlist(predict(fit, df, se = T)[['se.fit']] + predict(fit, df, se = T)[['fit']]))\n}\n", "meta": {"hexsha": "9f57e8bbb918604a8ae89efaae7adcc918e2c7cd", "size": 5387, "ext": "r", "lang": "R", "max_stars_repo_path": "R/time_utils.r", "max_stars_repo_name": "mcavallaro/rancovr", "max_stars_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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/time_utils.r", "max_issues_repo_name": "mcavallaro/rancovr", "max_issues_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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/time_utils.r", "max_forks_repo_name": "mcavallaro/rancovr", "max_forks_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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.875739645, "max_line_length": 113, "alphanum_fraction": 0.6265082606, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6681402364206657}} {"text": "library(MASS)\r\n\r\na_white <- 11\r\na_black <- 10\r\nb_white <- 9\r\nb_black <- 18\r\n\r\n# a_white <- 19\r\n# a_black <- 18\r\n# b_white <- 17\r\n# b_black <- 17\r\n\r\n# a_white <- 12\r\n# a_black <- 8\r\n# b_white <- 10\r\n# b_black <- 14\r\n\r\na <- a_white + a_black\r\nb <- b_white + b_black\r\n\r\nprimadomanda <- ((b_white+1)/(b+1) * a_white/a) + ((b_white/(b+1)) * (a_black/a))\r\nsecondadomanda <- ((b_white+1)/(b+1) * a_white/a) / primadomanda\r\n\r\n\r\nprint(fractions(primadomanda))\r\nprint(fractions(secondadomanda))", "meta": {"hexsha": "0b2b06ee68aa91a35283899f678f1fa221ea8e37", "size": 484, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 07.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 07.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 07.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": 18.6153846154, "max_line_length": 82, "alphanum_fraction": 0.6033057851, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6678578003279703}} {"text": "# Example : 1 Chapter : 10.1 Page No: 496\r\n# r of complex numbers\r\nrad2deg <- function(rad) {\r\n (rad * 180) / (pi)\r\n}\r\nz<-complex(real=1,imaginary=1)\r\nz1<-Conj(z)\r\nprint(\"r of z and its conjugate are\")\r\nprint(Mod(z))\r\nprint(Mod(z1))\r\nprint(\"The argument of z and its conjugate in degrees are\")\r\nprint(paste(rad2deg(Arg(z)),\"degrees\")) # in radians which is equal to 45 degree\r\nprint(paste(rad2deg(Arg(z1)),\"degrees\"))\r\n", "meta": {"hexsha": "f40f7507db1076eeb7d2c2633949764962709857", "size": 426, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.1.1/Ex10.1_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.1.1/Ex10.1_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH10/EX10.1.1/Ex10.1_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 30.4285714286, "max_line_length": 81, "alphanum_fraction": 0.6572769953, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6678175831347405}} {"text": "## Dexter Barrows\n## dbarrows.github.io\n## McMaster University\n## 2016\n\nStocSIRS <- function(y, pars, T, steps) {\n\n\tout <- matrix(NA, nrow = (T+1), ncol = 4)\n\n\tR0 <- pars[['R0']]\n\tr <- pars[['r']]\n\tN <- pars[['N']]\n\teta <- pars[['eta']]\n\tberr <- pars[['berr']]\n re <- pars[['re']]\n\n\tS <- y[['S']]\n\tI <- y[['I']]\n\tR <- y[['R']]\n\n\tB0 <- R0 * r / N\n\tB <- B0\n\n\tout[1,] <- c(S,I,R,B)\n\n\th <- 1 / steps\n\n\tfor ( i in 1:(T*steps) ) {\n\n #Bfac <- 1/2 - cos((2*pi/365)*i)/2\n Bfac <- exp(2*cos((2*pi/365)*i) - 2)\n\n\t\tB <- exp( log(B) + eta*(log(B0) - log(B)) + rnorm(1, 0, berr) )\n\n\t\tBSI <- Bfac*B*S*I\n\t\trI <- r*I\n reR <- re*R \n\n\t\tdS <- -BSI + reR\n\t\tdI <- BSI - rI\n\t\tdR <- rI - reR\n\n\t\tS <- S + h*dS #newInf\n\t\tI <- I + h*dI #newInf - h*dR\n\t\tR <- R + h*dR #h*dR\n\n\t\tif (i %% steps == 0)\n\t\t\tout[i/steps+1,] <- c(S,I,R,B)\n\n\t}\n\n\tcolnames(out) <- c(\"S\",\"I\",\"R\",\"B\")\n\treturn(out)\n\n}\n\n### suggested parameters\n#\n# T \t\t<- 200\n# i_infec \t<- 10\n# steps \t<- 7\n# N \t\t<- 500\n# sigma \t<- 5\n#\n# pars <- c(R0 = 3.0, \t# new infected people per infected person\n# r = 0.1, \t# recovery rate\n#\t\t N = 500, # population size\n#\t\t eta = 0.5, \t# geometric random walk\n#\t\t berr = 0.5, # Beta geometric walk noise\n# re = 1) \t# resuceptibility rate", "meta": {"hexsha": "048ef1e2a72925a2d772b38fd2a82c3aa6f7c8d5", "size": 1263, "ext": "r", "lang": "R", "max_stars_repo_path": "code/sir-functions/StocSIRS.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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/sir-functions/StocSIRS.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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/sir-functions/StocSIRS.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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": 18.0428571429, "max_line_length": 65, "alphanum_fraction": 0.4639746635, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6677738125792931}} {"text": "intToLogicalBits <- function(intx) as.logical(intToBits(intx))\nlogicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))\n\"%AND%\" <- function(x, y)\n{\n logicalBitsToInt(intToLogicalBits(x) & intToLogicalBits(y))\n}\n\"%OR%\" <- function(x, y)\n{\n logicalBitsToInt(intToLogicalBits(x) | intToLogicalBits(y))\n}\n\n35 %AND% 42 # 34\n35 %OR% 42 # 42\n", "meta": {"hexsha": "d12f4fa24e3dd72392c9e5443783a7ad4f6d4882", "size": 354, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Bitwise-operations/R/bitwise-operations-3.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/Bitwise-operations/R/bitwise-operations-3.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/Bitwise-operations/R/bitwise-operations-3.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": 25.2857142857, "max_line_length": 64, "alphanum_fraction": 0.6666666667, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.667637316263383}} {"text": "# vectorized approach based on scalar code from primeSieve and mersenne in CRAN package `numbers`\nrequire(gmp)\nn <- 4423 # note that the sieve below assumes n > 9\n\n# sieve the set of primes up to n\np <- seq(1, n, by = 2)\nq <- length(p)\np[1] <- 2\nfor (k in seq(3, sqrt(n), by = 2))\n if (p[(k + 1)/2] != 0)\n p[seq((k * k + 1)/2, q, by = k)] <- 0\np <- p[p > 0]\ncat(p[1],\" special case M2 == 3\\n\")\np <- p[-1]\n\nz2 <- gmp::as.bigz(2)\nz4 <- z2 * z2\nzp <- gmp::as.bigz(p)\nzmp <- z2^zp - 1\nS <- rep(z4, length(p))\n\nfor (i in 1:(p[length(p)] - 2)){\n S <- gmp::mod.bigz(S * S - z2, zmp)\n if( i+2 == p[1] ){\n if( S[1] == 0 ){\n cat( p[1], \"\\n\")\n flush.console()\n }\n p <- p[-1]\n zmp <- zmp[-1]\n S <- S[-1]\n }\n}\n", "meta": {"hexsha": "a95ce0cee377c8dd2430ed21abd939777ed204e5", "size": 732, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Lucas-Lehmer-test/R/lucas-lehmer-test.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Lucas-Lehmer-test/R/lucas-lehmer-test.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/Lucas-Lehmer-test/R/lucas-lehmer-test.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5294117647, "max_line_length": 97, "alphanum_fraction": 0.4931693989, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6675785775526952}} {"text": "#autor: Joao Sollari Lopes\n#local: INE, Lisboa\n#Rversion: 3.2.3\n#criado: 02.07.2017\n#modificado: 11.02.2019\n\nlibrary(\"GA\")\n\n#Define data \nn <- c(\"pocketknife\",\"beans\",\"potatoes\",\"unions\",\"sleepingbag\",\"rope\",\"compass\") # Items \np <- c(10,20,15,2,30,10,30) # Profits \nw <- c(1,5,10,1,7,5,1) # Weights\nW <- 20 # Knapsack ’s capacity \n\n#Define fitness function \nknapsack <- function(x){ \n if(sum(x*w) > W)\n\t return(0)\n else\n\t\treturn(sum(x*p))\n}\n\n# Run SGA\nSGA <- ga(type=\"binary\", \n fitness=knapsack, #fitness function\n nBits=length(n), #chromosome length\n popSize=100, #population size\n pcrossover=0.8, #crossover rate\n pmutation=0.1, #mutation rate\n elitism=5, #number of best individuals sure to be selected\n maxiter=100, #number of generations\n names=n, #name of \"genes\"\n seed=12345) #random seed\n\nres <- SGA@solution\nprint(res) #Best solution\nsum(res) #Total number of selected items\nsum(res*p) #Total profit of selected items\nsum(res*w) #Total weight of selected items\n\n#Plot model\nplot(SGA@summary[,\"mean\"],type=\"l\",ylab=\"mean fitness\",xlab=\"iteration\",\n col=\"blue\",lty=1,lwd=2)\nbarplot(SGA@fitness,ylab=\"fitness\",xlab=\"\",col=\"blue\")\n", "meta": {"hexsha": "9110a53448b996a721457a69212999c612ce5068", "size": 1393, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/knapsack.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/knapsack.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/knapsack.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": 30.9555555556, "max_line_length": 104, "alphanum_fraction": 0.5685570711, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6675785555060703}} {"text": "##### Chapter 8: Association Rules -------------------\n\n## Example: Identifying Frequently-Purchased Groceries ----\n## Step 2: Exploring and preparing the data ----\n\n# load the grocery data into a sparse matrix\nlibrary(arules)\ngroceries <- read.transactions(\"groceries.csv\", sep = \",\")\nsummary(groceries)\n\n# look at the first five transactions\ninspect(groceries[1:5])\n\n# examine the frequency of items\nitemFrequency(groceries[, 1:3])\n\n# plot the frequency of items\nitemFrequencyPlot(groceries, support = 0.1)\nitemFrequencyPlot(groceries, topN = 20)\n\n# a visualization of the sparse matrix for the first five transactions\nimage(groceries[1:5])\n\n# visualization of a random sample of 100 transactions\nimage(sample(groceries, 100))\n\n## Step 3: Training a model on the data ----\nlibrary(arules)\n\n# default settings result in zero rules learned\napriori(groceries)\n\n# set better support and confidence levels to learn more rules\ngroceryrules <- apriori(groceries, parameter = list(support =\n 0.006, confidence = 0.25, minlen = 2))\ngroceryrules\n\n## Step 4: Evaluating model performance ----\n# summary of grocery association rules\nsummary(groceryrules)\n\n# look at the first three rules\ninspect(groceryrules[1:3])\n\n## Step 5: Improving model performance ----\n\n# sorting grocery rules by lift\ninspect(sort(groceryrules, by = \"lift\")[1:5])\n\n# finding subsets of rules containing any berry items\nberryrules <- subset(groceryrules, items %in% \"berries\")\ninspect(berryrules)\n\n# writing the rules to a CSV file\nwrite(groceryrules, file = \"groceryrules.csv\",\n sep = \",\", quote = TRUE, row.names = FALSE)\n\n# converting the rule set to a data frame\ngroceryrules_df <- as(groceryrules, \"data.frame\")\nstr(groceryrules_df)\n", "meta": {"hexsha": "927fd69f4bec119d2a33bdc9980a5e80effe72c4", "size": 1732, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 08/MLwR_v2_08.r", "max_stars_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_stars_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-17T21:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T04:28:52.000Z", "max_issues_repo_path": "Chapter 08/MLwR_v2_08.r", "max_issues_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_issues_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "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": "Chapter 08/MLwR_v2_08.r", "max_forks_repo_name": "PacktPublishing/Machine-Learning-with-R---Second-Edition", "max_forks_repo_head_hexsha": "426864c2fc703962ae89ae6b437ac40d1b4104f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2019-10-06T00:57:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:18:58.000Z", "avg_line_length": 28.393442623, "max_line_length": 70, "alphanum_fraction": 0.7263279446, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.7853085733507947, "lm_q1q2_score": 0.6674896453759784}} {"text": "subroutine qtest1(h,i,j,k,x,y,ntot,eps,shdswp,nerror)\n\n# The Lee-Schacter test for the LOP (all points are real,\n# i.e. non-ideal). If the LOP is ***not*** satisfied (i.e. if\n# vertex j is inside the circumcircle of vertices h, i, and k) then the\n# diagonals should be swapped, i.e. shdswp (\"should-swap\") is true.\n# Called by qtest.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot)\ninteger h\nlogical shdswp\n\n# The vertices of the quadrilateral are labelled\n# h, i, j, k in the anticlockwise direction, h\n# being the point of central interest.\n\n# Make sure the quadrilateral is convex, so that\n# it makes sense to swap the diagonal.\n# call acchk(i,j,k,shdswp,x,y,ntot,eps)\n# if(!shdswp) return\n#\n# 23 July 2011:\n# The foregoing test is a load of dingos' kidneys. (1) It is\n# unnecessary, and (2) it is wrong! (1) If the LOP is not satisfied\n# (the only circumstance under which there should be a swap) then the\n# quadrilateral ***must*** be convex, and so swapping can sensibly\n# take place. (2) The vertices i, j, k in will ***always*** be in\n# anticlockwise order, since the vertices h, i, j, k of the quadrilateral\n# are in such order and i is connected to k, whence j can't be inside\n# the triangle ihk. So the test does nothing. But then it didn't need\n# to do anything.\n\n# Get the coordinates of vertices h and j.\nxh = x(h)\nyh = y(h)\nxj = x(j)\nyj = y(j)\n\n# Find the centre of the circumcircle of vertices h, i, k.\ncall circen(h,i,k,x0,y0,x,y,ntot,eps,shdswp,nerror)\nif(nerror>0) return\nif(shdswp) return # The points h, i, and k are colinear, so\n # the circumcircle has `infinite radius', so\n # (xj,yj) is definitely inside.\n\n# Check whether (xj,yj) is inside the circle of centre\n# (x0,y0) and radius r = dist[(x0,y0),(xh,yh)]\n\na = x0-xh\nb = y0-yh\nr2 = a*a+b*b\na = x0-xj\nb = y0-yj\nch = a*a + b*b\nif(ch N)\nx <- x[j]\nX <- f$x[j,]\nw <- simRegOrd(n, nsim=400, delta=delta, sigma=sd, x=x,\n X=X,\n Eyx=Function(f), pr=TRUE)\nw$power ## 0.70\n\n## Finally, add discrete ordinal category overrides and high end of y\n## Start with no effect of treatment on these ordinal event levels (OR=1.0)\n\nw <- simRegOrd(n, nsim=400, delta=delta, odds.ratio=1, sigma=sd,\n x=x, X=X, Eyx=Function(f),\n p=c(.98, .01, .01),\n pr=TRUE)\nw$power ## 0.61 (0.3 if p=.8 .1 .1, 0.37 for .9 .05 .05, 0.50 for .95 .025 .025)\n\n## Now assume that odds ratio for treatment is 2.5\n## First compute power for clinical endpoint portion of Y alone\nor <- 2.5\np <- c(.9, .05, .05)\npopower(p, odds.ratio=or, n=100) # 0.275\n## Compute power of t-test on continuous part of Y alone\npower.t.test(n = 100 / 2, delta=delta, sd=sd, type='two.sample') # 0.70\n## Note this is the same as the p.o. model power from simulation above\n## Solve for OR that gives the same power estimate from popower\npopower(rep(.01, 100), odds.ratio=2.4, n=100) # 0.706\n## Compute power for continuous Y with ordinal override\nw <- simRegOrd(n, nsim=400, delta=delta, odds.ratio=or, sigma=sd,\n x=x, X=X, Eyx=Function(f),\n p=c(.9, .05, .05),\n pr=TRUE)\nw$power ## 0.72\n", "meta": {"hexsha": "b9e1d9626b825f787801a8646f727b0a300ee40d", "size": 2176, "ext": "r", "lang": "R", "max_stars_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/simRegOrd.r", "max_stars_repo_name": "klodzikowski/phongames", "max_stars_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/simRegOrd.r", "max_issues_repo_name": "klodzikowski/phongames", "max_issues_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/simRegOrd.r", "max_forks_repo_name": "klodzikowski/phongames", "max_forks_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 33.4769230769, "max_line_length": 83, "alphanum_fraction": 0.6089154412, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6670341404650493}} {"text": "#R version 3.3.2 \n\n# Implementation provided by\n# Banks J., Garrabrant S.M., Huber M.L., Perizzolo A.\n# in their paper titled \"Using TPA to count linear extensi-ons\" \n# published in Journal of Discrete Algorithms, 2018.\n\n#necessary to install the library for the first time\n#install.packages('gtools', repos='http://cran.us.r-project.org')\n\nlibrary(gtools)\nlibrary(Matrix)\n \nchain.step <- function(state,beta,i,c1,c2,posetmatrix) {\n# Takes one step in the Karzanov-Khatchyan chain using randomness in i, c1, c2\n# Assumes that home state is the identity permutation\n# Line 2 of Algorithm 5.1\nd <- i + 1 - state[i]\n# Line 3 of Algorithm 5.1\nif ((state[i] <= length(state)) && (state[i+1] <= length(state)))\nposetflag <- posetmatrix[state[i],state[i+1]]\nelse\nposetflag <- 0\nif ( (c1 == 1) && (posetflag == 0) &&\n(d <= ceiling(beta)) && ((d < beta) || (c2 == 1))) {\n13\na <- state[i+1]; state[i+1] <- state[i]; state[i] <- a\n}\nreturn(state)\n}\n \nbounding.chain.step <- function(cstate,beta,i,c1,c2,posetmatrix) {\n# Based on Algorithm 5.2\n# Here cstate is a matrix with two rows, the first is the underlying state,\n# while the second is the bounding state\nn <- dim(cstate)[2]\n# Line 1\nif (cstate[2,i+1] == cstate[1,i]) c3 <- 1 - c1\nelse c3 <- c1\n# Line 2 & 3\ncstate[1,] <- chain.step(cstate[1,],beta,i,c3,c2,posetmatrix)\ncstate[2,] <- chain.step(cstate[2,],beta,i,c1,c2,posetmatrix)\n# Line 4 through 6\nif (cstate[2,n] == (n+1))\ncstate[2,n] <- 1 + sum(cstate[2,] <= n)\n#Line 7\nreturn(cstate)\n}\ngenerate <- function(t,beta,posetmatrix) {\nn <- dim(posetmatrix)[1]; beta <- min(beta,n-1)\n# Line 1\nsigma <- 1:n; B <- rep(n+1,n)\n# Line 2 thorugh 4\nfor (item in 1:(n - ceiling(beta)))\nB[item+ceiling(beta)] <- item\nB0 <- B\ncstate <- matrix(c(sigma,B),byrow=TRUE,nrow=2)\n# Line 5 through 8\ni <- floor(runif(t)*(n-1))+1;c1 <- rbinom(t,1,1/2)\nc2 <- rbinom(t,1,1+beta-ceiling(beta))\nfor (s in 1:t) {\ncstate <- bounding.chain.step(cstate,beta,i[s],c1[s],c2[s],posetmatrix)\n}\n# Line 9\nif (sum(cstate[2,] < (n+1)) == n) return(cstate[2,])\n# Line 11-15\nelse {\ncstate[1,] <- generate(2*t,beta,posetmatrix)\n14\ncstate[2,] <- B0\nfor (s in 1:t)\ncstate <- bounding.chain.step(cstate,beta,i[s],c1[s],c2[s],posetmatrix)\n}\nreturn(cstate[1,])\n}\n \napproximate.sample <- function(n,beta,posetmatrix,tvdist) {\n# Generates an approximate sample from the target distribution\nx <- 1:n\nn <- length(x)\nt <- 10*n^3*log(n)*log(1/tvdist)\nfor (i in 1:t) {\ni <- runif(1)*(n-1)+1\nc1 <- rbinom(1,1,1/2)\nc2 <- rbinom(1,1,1+beta-ceiling(beta))\nx <- chain.step(x,beta,i,c1,c2,posetmatrix)\n}\nreturn(x)\n}\nchecksum <- function(x) {\nchecksum <- 0\nn <- length(x)\nfor (i in n:1) {\nonespot <- which(x == 1)\nchecksum <- checksum + factorial(i-1)*(onespot-1)\nx <- x[-onespot] - 1\n}\nreturn(checksum+1)\n}\n \ncount.perfect.linear.extensions <- function(n = 4,beta = 4,posetmatrix,trials = 100) {\n# Generates a number of linear extensions, then counts the results\nresults <- rep(0,factorial(n))\n# Burnin to an approximate sample\nx <- 1:n\nn <- length(x)\n# Take data\nfor (i in 1:trials) {\n15\nx <- generate(1,beta,posetmatrix)\ncs <- checksum(x)\nresults[cs] <- results[cs] + 1\n}\nreturn(results/trials)\n}\n \ntpa.count.linear.extensions <- function(r,posetmatrix) {\n# Algorithm 6.1\n# Returns an estimate of the number of linear\n# extensions consistant with posetmatrix\nrequire(Matrix)\nn <- dim(posetmatrix)[1]\n# Line 1\nk <- 0\n# Line 2 through 12\nfor (i in 1:r) {\nbeta <- n - 1; k <- k - 1\nwhile (beta > 0) {\nk <- k + 1\nx <- generate(1,beta,posetmatrix)\nxinv <- invPerm(x)\nbetastep <- rep(0,n); y <- rep(0,n)\nfor (j in 1:n) {\ny[j] <- runif(1)*((1+beta-ceiling(beta))*(xinv[j]-j == ceiling(beta))+\n((xinv[j]-j) < ceiling(beta)))\nbetastep[j] <- (xinv[j]-j-1+y[j])*(xinv[j]-j > 0)\n}\nbeta <- max(betastep)\n# cat(\" X: \",x,\"\\n X^{-1}: \",xinv,\"\\n Y: \",y,\"\\n betastep: \",betastep,\"\\n beta: \",beta,\"\\n\")\n}\n}\ncat(\" Estimate: [\",exp((k-2*sqrt(k))/r),\",\",exp((k+2*sqrt(k))/r),\"]\\n\")\nreturn(exp(k/r))\n}\n \ntpa.approximation <- function(posetmatrix,epsilon,delta) {\n# Gives an $(\\epsilon,\\delta)$-ras for the number of posets\nr1 <- ceiling(2*log(2/delta))\na1 <- tpa.count.linear.extensions(r1,posetmatrix)\n16\na1 <- log(a1)\nr2 <- ceiling(2*(a1+sqrt(a1)+2)*\n(log(1+epsilon)^2-log(1+epsilon)^3)^(-1)*log(4/delta))\na2 <- tpa.count.linear.extensions(r2,posetmatrix)\nreturn(a2)\n}\n \nbrute.force.count.linear.extensions <- function(posets) {\n# Counts the number of linear extensions of a poset by direct\n# ennumeration of all n! permutations and checking each to see\n# if it is a linear extension\n#\n# The poset is given as an n by n matrix whose (i,j)th entry\n# is the indicator function of $i \\preceq j$\nrequire(gtools)\nn <- dim(posets)[1]\nA <- permutations(n,n)\nnfact <- nrow(A)\nle.flag <- rep(1,nfact)\ncount <- 0\nfor (i in 1:nfact) {\nfor (a in 1:(n-1))\nfor (b in (a+1):n) {\nle.flag[i] <- le.flag[i]*(1-posets[A[i,b],A[i,a]])\n}\ncount <- count + le.flag[i]\n}\nreturn(count)\n}\n\n", "meta": {"hexsha": "52450de1aef0fd0ed270a26ff8b551e7e8c764ac", "size": 4901, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/tpa.r", "max_stars_repo_name": "hasansozer/JBita", "max_stars_repo_head_hexsha": "b7c00c3bfccadb6061d5c85b3a183cdd9d97cb87", "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": "lib/tpa.r", "max_issues_repo_name": "hasansozer/JBita", "max_issues_repo_head_hexsha": "b7c00c3bfccadb6061d5c85b3a183cdd9d97cb87", "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": "lib/tpa.r", "max_forks_repo_name": "hasansozer/JBita", "max_forks_repo_head_hexsha": "b7c00c3bfccadb6061d5c85b3a183cdd9d97cb87", "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": 27.0773480663, "max_line_length": 92, "alphanum_fraction": 0.6463986941, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.6668719143405449}} {"text": "\n\n#' Find optimal radia\n#'\n#' This function compute the optimal cylinder radia, such that the corresponding\n#' cylinders contain one event in average \n#' for the chosen N heights (\\code{heights}) and a given \\code{baseline.matrix}.\n#' It returns an Nx2 \\code{Matrix} whose first column contains the heights and \n#' and the second column contains the corresponding radia.\n#' @param baseline.matrix A \\code{Matrix} enconding the baseline. \n#' @param heigths \\code{integer}. \n#' @return A \\code{Matrix}.\n#' @examples\n#' radia_and_heights = f_radia_and_heights(baseline.matrix, 1:10)\nf_radia_and_heights<-function(baseline.matrix, heigths=1:100){\n n.heigths = ncol(baseline.matrix)\n mean.baseline = mean(baseline.matrix[, 1:n.heigths])\n # R = 3959 # earth radius in miles\n # lat1 = min(postcode2coord$latitude)\n # lat2 = max(postcode2coord$latitude)\n # lon1 = min(postcode2coord$longitude)\n # lon2 = max(postcode2coord$longitude)\n # total.area = (pi / 180) * R * R * abs(sin(lat1)-sin(lat2)) * abs(lon1-lon2)\n total.area = 130279 # total area of England in km2s\n n.points = nrow(baseline.matrix)\n mean.spatial.baseline = mean.baseline * n.points / total.area\n # we want A such that A * mean.spatial.baseline=1, A * mean.spatial.baseline=1/2, A * mean.spatial.baseline=1/3, etc\n radia = sapply(heigths, function(x){sqrt(1 / mean.spatial.baseline / pi / x)} )\n ret = cbind(heigths, radia)\n colnames(ret) = c('heights','radia')\n return(ret)\n}\n\n\n#' Find optimal radia\n#'\n#' This function compute the optimal cylinder radia, such that the corresponding\n#' cylinders contain one event in average \n#' for the chosen N heights (\\code{heights}) and a given tabulated baseline.\n#' It returns an Nx2 \\code{Matrix} whose first column contains the heights and \n#' and the second column contains the corresponding radia.\n#' @param baseline.matrix An \\code{expand.grid} tab enconding the baseline. \n#' @param heigths \\code{integer}. \n#' @return A \\code{Matrix}.\n#' @examples\n#' radia_and_heights = f_radia_and_heights(baseline.matrix, 1:10)\nf_radia_and_heights_<-function(baseline.tab, heights=1:100){\n n.heights = length(unique(baseline.tab$t))\n mean.baseline = mean(baseline.tab$z[baseline.tab$z>0]) # z strictly > 0 to exclude the grid points on unpopulated area.\n\n total.area = 130279 # total area of England in km2\n idx = baseline.tab$z > 0\n n.points = sum(idx) / n.heights\n delta2 = prod(attributes(baseline.tab)$delta2)\n mean.spatial.baseline = mean.baseline / (n.points * delta2) * total.area\n # we want A such that A * mean.spatial.baseline=1, A * mean.spatial.baseline=1/2, A * mean.spatial.baseline=1/3, etc\n radia = sapply(heights, function(x){sqrt(1 / mean.spatial.baseline / pi / x )} )\n ret = cbind(heigths, radia)\n colnames(ret) = c('heights','radia')\n return(ret)\n}\n\n\n#' Draw random cylinder coordinates\n#' \n#' Find the coordinates (centers and height limits) of cylinders\n#' that contain events defined in \\code{observation.matrix}, with radia and heights\n#' given in \\code{radia_and_heights}.\n#' \n#' @param n.cylinders An \\code{integer}; the number of cylinders to draw.\n#' @param observation.matrix A \\code{sparseMatrix} object enconding the events.\n#' @param time.range An \\code{integer} vector.\n#' @param radia_and_heights A \\code{Matrix}.\n#' @param postcode2coord A \\code{data.frame} that maps the rows of \\code{observation.matrix} to geographical coordinates.\n#' @importFrom truncnorm rtruncnorm\n#' @import Matrix\n#' @return A \\code(data.frame).\n#' @examples\n#' cylinders=rcylinder(10, observation.matrix, time.range, radia_and_heights, postcode2coord)\nrcylinder<-function(n.cylinders, observation.matrix, time.range, radia_and_heights, postcode2coord, only.last=F){\n if (any(rownames(observation.matrix)=='NA')){\n cat(\"WARNING: any(rownames(observation.matrix)=='NA'\")\n }\n cols = as.character(time.range[1]:time.range[2])\n cases = which(observation.matrix[, cols] > 0, arr.ind = T)\n # cases is of the form:\n # row col\n # PL15 9NE 5851 231\n # SY11 3PN 6370 255\n if (sum(observation.matrix[, cols]) > 0){\n idx = sample(1:nrow(cases), n.cylinders, replace = T)\n y = postcode2coord[cases[idx, 1], 'y']\n x = postcode2coord[cases[idx, 1], 'x']\n \n # t = cases[idx,2] + time.range[1] - 1\n # print(head(t))\n t = as.integer(colnames(observation.matrix[,cols])[cases[idx,2]])\n # radia and heights are given as input in the matrix radia_and_heights\n\n radia_and_heights = radia_and_heights[sample(1:nrow(radia_and_heights), n.cylinders, replace=T),]\n # randomise wilst keeping same radius and height and avoiding negative t\n rho = radia_and_heights[, 2]\n random_radia = runif(n.cylinders, 0, rho)\n theta = runif(n.cylinders, 0, 2* pi)\n\n y = y + sin(theta) * random_radia\n x = x + cos(theta) * random_radia\n tt = t + runif(n.cylinders, -radia_and_heights[,1]/2, radia_and_heights[,1]/2)\n \n if (only.last){\n t.upp = as.integer(time.range[2])\n }else{\n t.upp = ceiling(tt + radia_and_heights[,1] / 2)\n }\n t.max = as.integer(time.range[2])\n \n if (only.last){\n t.low = floor(t.upp - radia_and_heights[,1])\n t.low = ifelse(t < t.low, t, t.low)\n }else{\n t.low = floor(tt - radia_and_heights[,1] / 2)\n }\n t.min = as.integer(time.range[1])\n \n t.low = ifelse(t.low >= t.min, t.low, t.min)\n t.upp = ifelse(t.upp <= t.max, t.upp, t.max)\n \n t.low = as.integer(ifelse(t.low == t.max, t.low - 1, t.low))\n # isx = (t.low == t.upp)\n # if (any(isx)){\n # print(c(t.low[isx], t.upp[isx]))\n # } \n \n return(data.frame(x=x, y=y, rho=rho, t.low=t.low, t.upp=t.upp))\n }else{\n return(data.frame(x=double(), y=double(), rho=double(), t.low=integer(), t.upp=integer())) \n }\n}\n\n\n\n#' Compute exceedance probabality in a cylinder.\n#' \n#' A cylinder is defined by the circle coordinated (say, x,y, and radius) and lower and upper height limits (aay, t.low and t.upp, respectively).\n#' For a given cylinder, this function computes the number of observed events (\\code{n_cases}) in the cylinder according to\n#' \\code{observation.matrix}, the expected number \\code{mu} of events according the Poisson point model (with intensity\n#' defined in \\code{baseline.matrix}), and the probability that .\n#' The function returns \\code{c(n_cases, mu, p.val)}.\n#' \n#' @param cylinder \n#' @param observation.matrix A \\code{sparseMatrix} object enconding the events.\n#' @param baseline.matrix A \\code{Matrix} object enconding the baseline.\n#' @param postcode.locations A \\code{data.frame} that maps the rows of \\code{observation.matrix} to geographical coordinates.\n#' @import Matrix\n#' @return A \\code{numeric} vector of dimension 3.\n#' @examples\n#' exceedance=compute(c(x,y,rho,t.low,t.upp), observation.matrix, baseline.matrix, postcode.locations)\ncompute<-function(cylinder, observation.matrix, baseline.matrix, postcode.locations){\n t.range = as.character(as.integer(cylinder['t.low']):as.integer(cylinder['t.upp']))\n observations = observation.matrix[,t.range]\n baselines = baseline.matrix[,t.range]\n\n d = sqrt(\n (as.numeric(postcode.locations$x) - as.numeric(cylinder['x']))^2 +\n (as.numeric(postcode.locations$y) - as.numeric(cylinder['y']))^2\n )\n in_circle = (d= t.low) & (tab.baseline$t <= t.upp)\n\n mu = sum(tab.baseline[in_circle & in_height,]$z) #* attributes(tab.baseline)$delta2 #multiply by delta2 as this is the bin size\n \n# in_of_square = sum(in_circle & in_height) * delta2\n# out_of_square = pi * rho* rho - in_of_square\n# correct by taking into account that outsise the square there is nothing. \n# mu = mu * pi * rho *rho / in_of_square\n \n d = sqrt(\n (as.numeric(postcode.locations$longitude) - x0)^2 +\n (as.numeric(postcode.locations$latitude) - y0)^2\n )\n in_circle = (d < rho) & (!is.na(d))\n\n n_cases_in_cylinder = sum(observations[in_circle, ], na.rm = T)\n \n# ci = qpois(c(0.25,0.95) , lambda=mu)\n p.val = ppois(n_cases_in_cylinder-1, lambda=mu, lower.tail=FALSE)\n return (c(n_cases_in_cylinder, mu, p.val))\n}\n\n\n\n\n\nwarning_ratio<-function(i, observation.matrix, cylinders, postcode.locations){\n # check if the location i\n x = as.numeric(postcode.locations[i, 'longitude'])\n y = as.numeric(postcode.locations[i, 'latitude'])\n \n ## da vettorizzare\n # in_circle = apply(cylinders, 1, function(X){\n # ifelse(sqrt((as.numeric(X['x']) - x)^2 + (as.numeric(X['y']) - y)^2) < as.numeric(X['rho']), TRUE, FALSE)\n # })\n \n # vettorizzato\n in_circle = sqrt((as.numeric(cylinders['x']) - x)^2 + (as.numeric(cylinders['y']) - y)^2) < as.numeric(cylinders['rho'])\n \n times = which(observation.matrix[i,] > 0)\n\n if (length(times) > 0){\n in_cylinder_height = matrix(FALSE, nrow = nrow(cylinders), ncol=length(times))\n\n for (i in 1:length(times)){\n \n #da vettorizzare:\n in_cylinder_height[,i] = apply(cylinders, 1, function(X){\n TT = as.numeric(names(times[i]))\n (as.numeric(X['t.low']) < TT) & (as.numeric(X['t.upp']) > TT)\n })\n \n \n # vettorizzato\n #TT = as.numeric(names(times[i]))\n #in_cylinder_height[,i] = (as.numeric(cylinders['t.low']) < TT) & (as.numeric(cylinders['t.upp']) > TT)\n\n }\n\n # number of cylinders that include locations `i`\n in_cylinder = sum(in_circle * in_cylinder_height)\n # number of cylinder with `warning` flag that include location `i`\n warning = sum(cylinders$warning * in_circle * in_cylinder_height)\n\n return(warning / in_cylinder)\n }else{\n return(NA)\n }\n}\n# \n# warning_ratio2<-function(i, observation.matrix, t, cylinders, postcode.locations){\n# times = which(observation.matrix > 0)\n# if (length(times) > 0){\n# # check if the location is in any circle\n# x = as.numeric(postcode.locations[i,'longitude'])\n# y = as.numeric(postcode.locations[i,'latitude'])\n# \n# \n# in_circle = apply(cylinders, 1, function(X){\n# ifelse(sqrt((as.numeric(X['x']) - x)^2 + (as.numeric(X['y']) - y)^2) < as.numeric(X['rho']), TRUE, FALSE)\n# })\n# in_cylinder_height = (cylinders['t.low'] < t) & (cylinders['t.upp'] > t)\n# # number of cylinders that include locations\n# in_cylinder = sum(in_circle * in_cylinder_height)\n# # number of cylinder with `warning` flag that include location `i`\n# warning = sum(cylinders$warning * in_circle * in_cylinder_height)\n# if (in_cylinder == 0){\n# return(0)\n# }else{\n# return(warning / in_cylinder)\n# }\n# }else{\n# return(0)\n# }\n# }\n\n\nwarning.score<-function(case, cylinders, date.time.field = 'week'){\n x = as.numeric(case['x'])\n y = as.numeric(case['y'])\n TT = as.numeric(case[date.time.field])\n \n d = sqrt((cylinders$x - x)^2 + (cylinders$y - y)^2)\n in_circle = as.integer(d <= cylinders$rho)\n in_cylinder_height = as.integer((cylinders$t.low <= TT) & (cylinders$t.upp >= TT))\n \n # number of cylinders that include geo-coordinate of `case`\n in_cylinder = sum(in_circle * in_cylinder_height, na.rm=T)\n if (in_cylinder>0){\n # number of cylinder with `warning` flag that include location `i`\n warning = sum(cylinders$warning * in_circle * in_cylinder_height, na.rm=T)\n re = warning / in_cylinder\n }else{\n re = 0\n } \n return(re)\n}\n\n\nwarning.score2 <-function(case, TT, cylinders) {\n \n x = as.numeric(case['x'])\n y = as.numeric(case['y'])\n\n d = sqrt((cylinders$x - x)^2 + (cylinders$y - y)^2)\n in_circle = as.integer(d <= cylinders$rho)\n in_cylinder_height = as.integer((cylinders$t.low <= TT) & (cylinders$t.upp >= TT))\n \n # number of cylinders that include geo-coordinate of `case`\n in_cylinder = sum(in_circle * in_cylinder_height, na.rm=T)\n if (in_cylinder>0){\n # number of cylinder with `warning` flag that include location `i`\n warning = sum(cylinders$warning * in_circle * in_cylinder_height, na.rm=T)\n re = warning / in_cylinder\n }else{\n re = 0\n } \n return(re)\n}\n\n\n\n\n", "meta": {"hexsha": "f4cf0dbc534a844b5ce6fb129ad94205bee3dde3", "size": 13908, "ext": "r", "lang": "R", "max_stars_repo_path": "R/surveillance_utils.r", "max_stars_repo_name": "mcavallaro/rancovr", "max_stars_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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/surveillance_utils.r", "max_issues_repo_name": "mcavallaro/rancovr", "max_issues_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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/surveillance_utils.r", "max_forks_repo_name": "mcavallaro/rancovr", "max_forks_repo_head_hexsha": "e5ea9e30381d43a3e572126613667b26722fc761", "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.9579831933, "max_line_length": 145, "alphanum_fraction": 0.6717716422, "num_tokens": 4119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6668705352898285}} {"text": " # for clinic 1\r\nr1=c(50,50)\r\nc1=c(55,45)\r\n\r\n# for clinic 2\r\nr2=c(50,50)\r\nc2=c(55,45)\r\n\r\n# for clinic 3\r\nr3=c(50,50)\r\nc3=c(74,26)\r\nnh=100\r\n# The numerator of the CMH statistic\r\nN=((40-((r1[1]*c1[1])/nh))+(35-((r2[1]*c2[1])/nh))+(43-((r3[1]*c3[1])/nh)))^2\r\nprint(N)\r\n\r\nD=((r1[1]*r1[2]*c1[1]*c1[2])/(nh^2*(nh-1)))+((r2[1]*r2[2]*c2[1]*c2[2])/(nh^2*(nh-1)))+((r3[1]*r3[2]*c3[1]*c3[2])/(nh^2*(nh-1)))\r\nprint(D)\r\n\r\nX2=N/D\r\nprint(X2)\r\n# For df = 1, this result is significant at the p < .001 level. the drug-treated groups have consistently higher improvement rates than the placebo groups.", "meta": {"hexsha": "66c68fd6dc46e0ea08bde3b524c6fcaf0bfa1277", "size": 583, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.17/Ex10_17.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.17/Ex10_17.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH10/EX10.17/Ex10_17.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 26.5, "max_line_length": 155, "alphanum_fraction": 0.5780445969, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6668705186960154}} {"text": "# https://github.com/ericgoolsby/Rphylopars/wiki\n\nlibrary(Rphylopars)\nlibrary(phytools) # for simulating pure-birth phylogenies\nset.seed(21) # Set the seed for reproducible results\ntrait_cov <- matrix(c(4,2,2.2,2,3,1.5,2.2,1.5,2.5),nrow = 3,ncol = 3)\ntrait_cov # Phylogenetic trait covariance\ntree <- pbtree(n = 20)\nsim_data <- simtraits(v = trait_cov,tree = tree,nmissing = 10)\n\np_BM <- phylopars(trait_data = sim_data$trait_data,tree = sim_data$tree)\n\nsim_data$trait_data[,2:4]\n\np_BM$anc_recon[1:20,] # Data with imputed species means\np_BM$anc_var[1:20,] # Variances for each estimate\np_BM$anc_recon[1:20,] - sqrt(p_BM$anc_var[1:20,])*1.96 # Lower 95% CI\np_BM$anc_recon[1:20,] + sqrt(p_BM$anc_var[1:20,])*1.96 # Upper 95% CI\n\nplot.phylo(reorder(tree,\"postorder\"))\nnodelabels()\n\np_BM$anc_recon[21:39,] # Reconstructed ancestral states for each trait\np_BM$anc_var[21:39,] # Variances for each estimate\np_BM$anc_recon[21:39,] - sqrt(p_BM$anc_var[21:39,])*1.96 # Lower 95% CI\np_BM$anc_recon[21:39,] + sqrt(p_BM$anc_var[21:39,])*1.96 # Upper 95% CI\n\np_lambda <- phylopars(trait_data = sim_data$trait_data,\n tree = sim_data$tree,model = \"lambda\")\np_lambda # Estimated trait covariance and Pagel's lambda\n\np_star <- phylopars(trait_data = sim_data$trait_data,tree = sim_data$tree,model = \"star\")\np_star # Estimated trait covariance, fixed Pagel's lambda = 0\n\nchi_square <- as.double(2*(logLik(p_lambda) - # 2*(logLik_alt - logLik_null)\n logLik(p_star))) \ndegrees_freedom <- p_lambda$npars - p_star$npars # df = difference in # model parameters\npchisq(q = chi_square,df = degrees_freedom,lower.tail = FALSE) # p-value\n\np_OU <- phylopars(trait_data = sim_data$trait_data,tree = sim_data$tree,model = \"OU\")\np_OU # Estimated trait covariance, OU alpha, and stationary covariance\n\np_EB <- phylopars(trait_data = sim_data$trait_data,tree = sim_data$tree,model = \"EB\")\np_EB # Estimated trait covariance and EB rate parameter\n\nAIC(p_BM)\nAIC(p_OU)\nAIC(p_EB)\n\nBIC(p_BM)\nBIC(p_OU)\nBIC(p_EB)\n", "meta": {"hexsha": "85332cccc51913268d2f84ece6161093732145d0", "size": 2024, "ext": "r", "lang": "R", "max_stars_repo_path": "dev/R/zOld/Rphyopars.r", "max_stars_repo_name": "marknovak/FracFeed", "max_stars_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "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": "dev/R/zOld/Rphyopars.r", "max_issues_repo_name": "marknovak/FracFeed", "max_issues_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "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": "dev/R/zOld/Rphyopars.r", "max_forks_repo_name": "marknovak/FracFeed", "max_forks_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "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.1886792453, "max_line_length": 89, "alphanum_fraction": 0.7203557312, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6667914876205019}} {"text": "##require(mgcv)\n\n##'convience function for the logistic transform\n##' @param x the number to be transformed\n##'\n##' @return the logistic transform\n\n\nlogistic <- function(x){\n return(log(x/(1-x)))\n}\n\n##'convience function for the inverse logistic transform\n##' @param x the number to be transformed\n##'\n##' @return the inverse logistic transform\n\ninv_logistic <- function(x) {\n return(exp(x)/(1+exp(x)))\n}\n\n\n##' Function to estimate the progress on an epidemic\n##' using the method of Viboud and Chowell.\n##'\n##' @param epi.curve an epidemic curve\n##' @param cum.sum the cumulative sums to use...allows us to pass\n##' in epi.curve with missing observations.\n##' @param r intrinsic growth parameter\n##' @param p \"deceleration of growth' parameter\n##' @param K final size of the outbreak\n##' @param ... additional options to optim\n##'\n##' @return expected final size of outbreak and params specifying outbreak\n\nfinal.size.ViboudChowell <- function(epi.curve,\n cum.curve = cumsum(epi.curve),\n r =1,\n p = 0.5,\n K = max(cum.curve),...){\n\n log.K <- log(K)\n log.r <- log(r)\n logistic.p <- logistic(p)\n\n ## NOTE: when using cum.curve=cumsum(epi.curve), cum.curve is using whatever epi.curve is when it is first used\n cum.curve <- cum.curve[-length(cum.curve)] ##this was here because we don't have a groundtruth data for the last element of the cumsum (see preds for why)\n ##line up epi curve data with cumulative data\n epi.curve <- epi.curve[-1]\n\n if(length(epi.curve) == 0){\n return(NA)\n }\n\n ##current fit will be by optim. Setting objective function\n ##takes parameter in order r,p,K...assuming alpha is 1 for now\n ob.func <- function(param) {\n loc.r <- exp(param[1]) #range 0 to inf\n loc.p <- inv_logistic(param[2]) #range 0 to inf\n loc.K <- exp(param[3]) #range 0 to inf\n\n preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/loc.K)\n rc <- sum(abs(epi.curve - preds))/sum(epi.curve)\n return(rc)\n }\n\n #call optim wiht som not insane starting values\n tmp <- optim(c(log.r,logistic.p,log.K), ob.func, ...)\n\n return(list(r = exp(tmp$par[1]), p = inv_logistic(tmp$par[2]), K = exp(tmp$par[3])))\n}\n\n\n\n##' Function to estimate the progress on an epidemic\n##' using the method of Viboud and Chowell, with shared\n##' parameters accross epidmeics\n##'\n##' @param ecs a list of epidemic curves\n##' @param cum.curves the cumulative sums to use...allows us to pass\n##' in ecs with missing observations.\n##' @param r intrinsic growth parameter\n##' @param p \"deceleration of growth' parameter\n##' @param K final size of the outbreak\n##' @param ... additional options to optim\n##'\n##' @return expected final size of outbreak and params specifying outbreak\nfinal.size.ViboudChowell.pooled <- function(ecs,\n cum.curves = sapply(ecs, cumsum),\n r =1, p = 0.5,\n K = sapply(cum.curves, max),...){\n\n log.K <- log(K)\n log.r <- log(r)\n logistic.p <- logistic(p)\n\n for (i in 1:length(ecs)) {\n ## NOTE: when using cum.curve=cumsum(epi.curve), cum.curve is using whatever epi.curve is when it is first used\n cum.curves[[i]] <- cum.curves[[i]][-length(cum.curves[[i]])] ##this was here because we don't have a groundtruth data for the last element of the cumsum (see preds for why)\n ##line up epi curve data with cumulative data\n ecs[[i]] <- ecs[[i]][-1]\n\n\n if(length(ecs[[i]]) == 0){\n stop(\"Empty epidemic curve\")\n }\n }\n\n ##current fit will be by optim. Setting objective function\n ##takes parameter in order r,p,K...assuming alpha is 1 for now\n ob.func <- function(param) {\n loc.r <- exp(param[1]) #range 0 to inf\n loc.p <- inv_logistic(param[2]) #range 0 to inf\n loc.K <- exp(param[3:length(param)]) #range 0 to inf\n\n rc <- 0\n\n for (i in 1:length(ecs)) {\n cum.curve <- cum.curves[[i]]\n epi.curve <- ecs[[i]]\n preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/loc.K[i])\n #print(i)\n #print(sum(abs(epi.curve - preds))/sum(epi.curve))\n denom <- sum(epi.curve)\n if(denom==0) {denom<-1}\n rc <- rc + sum(abs(epi.curve - preds))/denom\n }\n\n\n return(rc)\n }\n\n print(log.r)\n print(logistic.p)\n print(range(exp(log.K)))\n #call optim wiht som not insane starting values\n tmp <- optim(c(log.r,logistic.p,log.K), ob.func, ...)\n\n ##print(tmp)\n\n\n return(list(r = exp(tmp$par[1]), p = inv_logistic(tmp$par[2]), K = exp(tmp$par[3:(2+length(ecs))])))\n}\n\n\n\n\n##' Function to estimate parameters given K is fixed using K from the gam\n##' using the method of Viboud and Chowell.\n##'\n##' @param epi.curve an epidemic curve\n##' @param cum.sum the cumulative sums to use...allows us to pass\n##' in epi.curve with missing observations.\n##' @param r intrinsic growth parameter\n##' @param p \"deceleration of growth' parameter\n##' @param K epidemic curves generated from the gam model\n##' @param ... additional options to optim\n##'\n##' @return refitted r and p values\n\nfinal.size.ViboudChowell.fit.params <- function(epi.curve,\n cum.curve = cumsum(epi.curve),\n r=1,\n p = 0.5,\n K = max(cum.curve),...){\n\n log.K <- log(K)\n log.r <- log(r)\n logistic.p <- logistic(p)\n\n #print(log.K)\n #print(log.r)\n #print(logistic.p)\n\n ## NOTE: when using cum.curve=cumsum(epi.curve), cum.curve is using whatever epi.curve is when it is first used\n cum.curve <- cum.curve[-length(cum.curve)] ##this was here because we don't have a groundtruth data for the last element of the cumsum (see preds for why)\n ##line up epi curve data with cumulative data\n epi.curve <- epi.curve[-1]\n\n if(length(epi.curve) == 0){\n return(100000)\n }\n\n ##current fit will be by optim. Setting objective function\n ##takes parameter in order r,p,K...assuming alpha is 1 for now\n ob.func <- function(param) {\n loc.r <- exp(param[1])\n\n loc.p <- inv_logistic(param[2]) #range 0 to 1\n\n preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/K)\n rc <- sum(abs(epi.curve - preds))/sum(epi.curve)\n return(rc)\n }\n\n #call optim wiht som not insane starting values\n tmp <- optim(c(log.r,logistic.p), ob.func, ...)\n #cat(\"fit.parms.r\", log.r, \":\", logistic.p, \"\\n\")\n\n return(list(r = exp(tmp$par[1]), p = inv_logistic(tmp$par[2])))\n}\n\n##' Function to estimate parameters given K is fixed using K from the gam\n##' using the method of Viboud and Chowell using information from all\n##' epi curves to create a single set of r and p values.\n##'\n##' @param epi.curve an list of epidemic curves.\n##' @param cum.sum the cumulative sums to use...allows us to pass\n##' in epi.curve with missing observations.\n##' @param r intrinsic growth parameter\n##' @param p \"deceleration of growth' parameter\n##' @param K epidemic curves generated from the gam model\n##' @param ... additional options to optim\n##'\n##' @return refitted r and p values\nfinal.size.ViboudChowell.fit.params.pooled <- function(epi.curve,\n cum.curve = lapply(epi.curve,cumsum),\n r=1, p = 0.5,\n K = sapply(cum.curve,max),...){\n\n log.K <- log(K)\n log.r <- log(r)\n logistic.p <- logistic(p)\n\n #print(log.K)\n #print(log.r)\n #print(logistic.p)\n\n ## NOTE: when using cum.curve=cumsum(epi.curve), cum.curve is using whatever epi.curve is when it is first used\n # cum.curve <- cum.curve[-length(cum.curve)] ##this was here because we don't have a groundtruth data for the last element of the cumsum (see preds for why)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##this was here because we don't have a groundtruth\n ##line up epi curve data with cumulative data\n # epi.curve <- epi.curve[-1]\n epi.curve <- lapply(epi.curve,function(x){x[-1]})\n\n\n if(length(epi.curve) == 0){\n # return(100000)\n stop(\"Use at least one epi curve.\")\n }\n #Debug only\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n ##current fit will be by optim. Setting objective function\n ##takes parameter in order r,p,K...assuming alpha is 1 for now\n\n ob.func <- function(param) {\n rc <- 0\n for(i in 1:length(epi.curve)){\n loc.r <- exp(param[1])\n\n loc.p <- inv_logistic(param[2]) #range 0 to 1\n\n # preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/K)\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - cum.curve[[i]]/K[i])\n\n denom <- sum(epi.curve[[i]])\n if(denom==0) {denom<-1}\n\n\n rc <- rc + sum(abs(epi.curve[[i]] - preds))/denom\n\n }\n return(rc)\n }\n\n\n ##call optim wiht som not insane starting values\n print(r,p)\n print(c(log.r,logistic.p))\n print(K)\n tmp <- optim(c(log.r,logistic.p), ob.func, ...)\n print(tmp)\n cat(\"fit.parms.r\", exp(tmp$par[1]), \":\", exp(tmp$par[2]), \"\\n\")\n\n rc <- list(r = exp(tmp$par[1]), p = inv_logistic(tmp$par[2]))\n ##don't let these be 0, sub with 10^-12\n if (rc$r == 0) {rc$r<-10^-12}\n if (rc$p == 0) {rc$p<-10^-12}\n return(rc)\n\n}\n\n##' Function to estimate K using updated parameters\n##' using the method of Viboud and Chowell.\n##'\n##' @param epi.curve an epidemic curve\n##' @param cum.sum the cumulative sums to use...allows us to pass\n##' in epi.curve with missing obsrvations.\n##' @param r intrinsic growth parameter\n##' @param p \"deceleration of growth' parameter\n##' @param K final size\n##' @param ... additional options to optim\n##'\n##' @return expected final size of outbreak\n\nfinal.size.ViboudChowell.fit.K <- function(epi.curve,\n cum.curve = cumsum(epi.curve),\n r=1,\n p=0.5,\n K = max(cum.curve), ...){\n\n logistic.p <- logistic(p)\n log.r <- log(r)\n log.K <- log(K)\n\n #cat(\"passed.parms.r\", log.r, \":\", logistic.p, \"\\n\")\n\n ## NOTE: when using cum.curve=cumsum(epi.curve), cum.curve is using whatever epi.curve is when it is first used\n cum.curve <- cum.curve[-length(cum.curve)] ##this was here because we don't have a groundtruth data for the last element of the cumsum (see preds for why)\n ##line up epi curve data with cumulative data\n epi.curve <- epi.curve[-1]\n\n if(length(epi.curve) == 0){\n #return(100000)\n stop(\"Use at least one epi curve.\")\n }\n\n ##current fit will be by optim. Setting objective function\n ##takes parameter in order r,p,K...assuming alpha is 1 for now\n\n ob.func <- function(param) {\n loc.K <- exp(param[1]) #range 0 to inf\n\n preds <- r*cum.curve^p * (1 - cum.curve/loc.K)\n\n\n\n if(length(epi.curve) < 5){\n warning(\"This needs longer epi curves\")\n return(0)\n }\n\n #rc <- sum(((log(epi.curve+1) - log(preds+1))^2)) #+ loc.K^.1875\n rc <- sum(abs(epi.curve - preds))/sum(epi.curve) +\n (abs(max(cum.curve)-loc.K)^.01-1) #weak penalty for additional cases\n ##cat(\"**\", loc.K,\":\", K,\":\", rc,\"\\n\")#Debug\n\n return(rc)\n }\n\n\n\n #call optim wiht som not insane starting values\n tmp <- optim(c(log.K), ob.func, method = \"Brent\",\n lower = log(max(cum.curve, na.rm = T)) ,\n upper = log(7*10^9), ...)\n #tmp <- optimize(ob.func, method = \"L-BFGS-B\", lower = 0 , upper = log(7*10^9), ...)\n\n #print(tmp) ##DEBUG\n\n #if (exp(tmp$par[1])>10^7) stop(\"Exploding K\")\n return(list(K = exp(tmp$par[1])))\n}\n\n##' Function gets the error compared to the final estimate\n##' for final size estimates over the entire epidemic\n##' curve\n##'\n##' @param epi.curve the epidemic curve to be analyzed\n##' @param ... additional parameters to the fitting\n##'\n##' @return a \"time series\" of errors\n\nts.err.final.size.ViboudChowell <- function(epi.curve, ...) {\n\n\n}\n\n##'Function runs a jacknife calculation on the final size\n##'for the Viboud Chowell model\n##'\n##' @param epi.curve\n##' @param ... additional parameters to optim\n##'\n##' @return\n\njackknife.final.size.ViboudChowell <- function(epi.curve,...) {\n\n rc <- vector(length=length(epi.curve)-1)\n cum.curve<- cumsum(epi.curve)\n\n for (i in 2:length(epi.curve)) {\n tmp.cum <- cum.curve[-(i-1)]\n tmp.epi <- epi.curve[-i]\n rc[i-1] <- final.size.ViboudChowell(tmp.epi,tmp.cum, ...)\n }\n\n return(rc)\n}\n\n##' Function generates a bunch of epidemic curves of different\n##' percent done based on a ViboudChowell model given values of\n##' r and p and a series of final sizes.\n##'\n##' @param pct a vector of percent of epidemic done of the same length\n##' as the number we should generate.\n##' @param K a vector of final epidemic sizes\n##' @param r the growth rate\n##' @param p the extent the growthrate is super or sub exponential\n##'\n##' @return a list of epidemic curves\ngen.epicurves.ViboudChowell <- function (pct, K, r, p) {\n rc <- list()\n\n for (i in 1:length(pct)) {\n ## for each epidemic we want to generate, start with\n ## a single case and then loop until we generate\n ## the appropriate percentage of the final size.\n ec <- (1)\n while (sum(ec) 0) {\n infs <- rbinom(1,S, 1-exp(-I*beta[i]/N[i]))\n recovs <- rbinom(1,I, 1-exp(-gamma[i]))\n S <- S - infs\n I <- I + infs - recovs\n R <- R + recovs\n\n curve <- c(curve, infs)\n }\n\n if (sum(curve) > 10) { #eliinate stochastic fadeouts\n break\n }\n }\n\n ## truncate it by pct\n fs <- sum(curve)\n\n target_sz <-fs * pct[i]\n ind <- max(c(which(cumsum(curve)<=target_sz),2)) #ust have at least 2 obse\n\n\n rc_ecs[[i]] <- curve[1:ind]\n rc_fs <- c(rc_fs, fs)\n\n }\n\n return(list(ecs=rc_ecs, fs=rc_fs))\n}\n\n##' Perform an MCMC to estimate percent of epidemic complete from\n##' a combination of covariates and predictor variables. Uses GAMs\n##' to fit covariate relationship, and assumes ViboudChowell\n##' underlying model.\n##'\n##' @param epi.curves all the epi curves we are going\n##' @param x data frame of covariates\n##' @param f formula to add to use in the GAM. Assume outcome variable\n##' is called K\n##' @param mcmc.iter the number of interations to run\n##'\n##' @return the samples from the MCMC\n\nsimple.EPInf.mcmc <- function (epi.curves, x, f, mcmc.iter = 1000) {\n require(mgcv)\n\n ##first determine priors for the percent done.\n expected.K <- rep(0, length(epi.curves))\n for (i in 1:length(epi.curves)) {\n expected.K[i] <-\n final.size.ViboudChowell(epi.curves[[i]])\n }\n\n pcts <- sapply(epi.curves, sum)/expected.K\n ##convert pcts above 1 to fractionally less than 1.\n pcts[pcts>1] <- 0.999999999\n\n cur.pcts <- log(pcts/(1-pcts))\n\n totals <- sapply(epi.curves, sum)\n\n\n ##set up the matrix for MCMC return\n rc <- matrix(nrow=mcmc.iter, ncol=length(pcts))\n\n ##fit model at starting parameters. Note that here we can just\n ##use K\n x$K <- sqrt(expected.K)\n mdl <- gam(formula(f),data=x)\n\n ##calculate the likelihood of the observed\n ##given pcts and expected K.\n cur.ll <- sum(dpois(totals,logistic(cur.pcts)*\n predict(mdl)^2, log=T)) +\n sum(dpois(round(expected.K), expected.K, log=TRUE)) #clearly part of the problem\n\n rc[1,] <- cur.pcts\n\n ##Do the MCMC loops\n for (i in 2:mcmc.iter) {\n ##propose new pcts for a random place\n prop.pcts <- cur.pcts\n ind <- sample(length(prop.pcts),1)\n prop.pcts[ind] <- cur.pcts[ind] + rnorm(1, 0,1)\n prop.K <- totals/logistic(prop.pcts)\n\n ##refit model\n x$K <- sqrt(prop.K)\n mdl <- gam(formula(f),data=x)\n\n\n ##calculate proposal likelihood\n prop.ll <- sum(dpois(totals,logistic(prop.pcts)*\n predict(mdl)^2, log=T)) +\n sum(dpois(round(prop.K), expected.K, log=TRUE))\n\n if ((prop.ll - cur.ll) > log(runif(1))) {\n ##accept\n cur.ll <- prop.ll\n cur.pcts <- prop.pcts\n }\n\n rc[i,] <- cur.pcts\n\n }\n\n return(rc)\n\n}\n\n##' Simple compare function that will be used in simple.epiInf.EM to generate\n##' the absolute error of the observed and predicted percent complete of the\n##' epidemic curve\n##' @param this_iter the current iteration of the loop\n##' @param last_iter the previous iteration of the loop\n##'\n##' @return the absolute error of percent complete between the iterations\n\ncompare <- function(this_iter, last_iter){\n # if(!(('pcts' %in% names(this_iter)) & ('pcts' %in% names(last_iter)))){\n # stop(\"pcts not found\")\n # }\n #\n # if(length(this_iter$pcts) != length(last_iter$pcts)){\n # stop(\"arguments have different lengths\")\n # }\n\n K.diff <- abs(this_iter$K - last_iter$K)\n K.stat.diff <- abs(this_iter$K.stat - last_iter$K.stat)\n\n return(max(sum(K.diff), sum(K.stat.diff)))\n}\n\n##' Initialization function. Estimates final size and\n##' parameters based on epidemic curve that will be used to start\n##' EM approach.\n##' @param epi.curve the epidemic curve to be analyzed\n##'\n##' @return list of final sizes and percent done of epidemic\n\ninitialize.em <- function(epi.curves){\n\n res <- final.size.ViboudChowell.pooled(epi.curves, method=\"BFGS\")\n\n return(list(K=res$K, r=res$r,p=res$p))\n}\n\n\n##' Simple EM approach to estimating epidemic progress.\n##' Basic algorithm is to initialize using epi-curve data\n##' and then interate between fitting model and fitting\n##' epi curve data using pooled estimates until convergance.\n##' Using a GAM model to start.\n##'\n##' @param epi.curves the individual epi curves\n##' @param x data frame of covariates\n##' @param f formula to use in GAM\n##' @param max.iter the maxiumum number of iterations performed\n##' @param threshold the desired precision of output\n##'\n##' @return a vector of estimated final sizes\n##'\nsimple.epiInf.EM <- function(epi.curves, x, f, max.iter = 100, threshold = 10^-5){\n require(mgcv)\n #browser()\n ## initialize using information from epidemic curves\n this_iter <- initialize.em(epi.curves)\n #print(this_iter)\n\n ## We want to use the total observed cases as a lower bound for final size\n #lower_K <- sapply(epi.curves,sum)\n\n ##Loop until ending critera is met\n iter <- 0\n #print(iter)\n ## make sure values are above the threshold\n last_iter <- list(K = this_iter$K+2*threshold,\n #pcts=this_iter$pcts+2*threshold,\n r = this_iter$r+2*threshold,\n p = this_iter$p+2*threshold)\n\n Khist <- NULL\n Khist.stat <- NULL\n par.hist <- NULL\n\n while(\n (compare(last_iter, this_iter) >= threshold) &\n (iter < max.iter)){\n # browser()\n ## Re-starting loop\n last_iter <- this_iter\n\n\n ##Get the length of the epi curves.\n epi.curve.length <- c()\n for(i in 1:length(epi.curves)){\n curve.length <- length(epi.curves[[i]])\n epi.curve.length[i] <- curve.length\n }\n\n\n ## fit statistical model (use final size for covariates)\n ## where currently model is 'K~x'\n x$K <- round(this_iter$K) #Rounding becuase we are uding poisson\n # x$K = this_iter$K\n #mdl <- gam(formula(f), data = x)\n #mdl <- gam(formula(f), data = x, weights = epi.curve.length)\n mdl <- gam(formula(f), data = x, family = poisson(), weights = epi.curve.length)\n\n ## predict model\n K.stat <- predict(mdl,type='response')\n #cat(\"statistical prediction\", K.stat, \"\\n\")\n #print(cbind(x$K,K.stat))\n\n\n ## re-estimate parameters\n ## only want final percentage complete\n #expected.r <- rep(0, length(epi.curves))\n\n\n tmp <- final.size.ViboudChowell.fit.params.pooled(epi.curves,\n K = K.stat,\n r = this_iter$r,\n p = this_iter$p,\n method=\"BFGS\")\n\n #cat(this_iter$r,\"->\",tmp$r,\" : \", this_iter$p, \"->\", tmp$p, \"\\n\")\n expected.p <- tmp$p\n expected.r <- tmp$r\n\n\n ## estimate final size based on epidemic curve\n expected.K <- c()\n\n for(i in 1:length(epi.curves)) {\n tmp <- final.size.ViboudChowell.fit.K(epi.curves[[i]], r = expected.r, p = expected.p, K = K.stat[[i]])\n\n expected.K[i] <- tmp$K\n }\n\n this_iter$K <- expected.K\n this_iter$r <- expected.r\n this_iter$p <- expected.p\n this_iter$K.stat <- K.stat\n\n Khist <-rbind(Khist, expected.K)\n Khist.stat <- rbind(Khist.stat, K.stat)\n par.hist <- rbind(par.hist, c(this_iter$r, this_iter$p))\n\n # if(iter %% 10 == 0){\n # cat(\"model prediction \",iter,\":\", expected.K, \"\\n\")\n # print(summary(mdl))\n # print(paste(\"iter =\" ,iter, sep=\"\"))\n # print(\"K\")\n # print(this_iter$K)\n # print(\"r\")\n # print(this_iter$r)\n # print(\"p\")\n # print(this_iter$p)\n # print(K.stat)\n # }\n\n #print(compare(last_iter, this_iter))\n #print(last_iter)\n #print(this_iter)\n #this_iter$pcts <- mapply(x=epi.curves,y=this_iter$K,function(x,y){x[length(x)]/y})\n\n #this_iter$pcts[this_iter$pcts > 1] <- 0.999999999\n iter = iter + 1\n\n cat(\"Err : \",compare(last_iter, this_iter),\"\\n\")\n }\n print(iter)\n #return(this_iter$pcts)\n rc <- this_iter\n rc$Khist <- Khist\n rc$Khist.stat <- Khist.stat\n rc$par.hist <- par.hist\n return(rc)\n\n\n}\n\n\n##' Algorithm does the EM fit of viboud chowell and a gam, but without pooling parameters.\n##'\n##'\n\n##' Initialization function. Estimates final size\n##' based on cumulative epidemic curve that will be\n##' used to start the statistical model approach\n##'\n##' @param epi.curve the epidemic curve to be analyzed\n##'\n##' @return list of final sizes of the epidemic\n\ninitialize_stat <- function(epi.curves){\n K <- sapply(epi.curves, sum)\n return(list(K=K))\n}\n\n##' Naive statistical approach to estimating epidemic progress.\n##' Basic algorithm is to initialize using epi-curve data\n##' and then generate final size from statistical model\n##'\n##' @param epi.curves the individual epi curves\n##' @param x data frame of covariates\n\nstat_inference <- function(epi.curves, x){\n\n fit <- initialize_stat(epi.curves)\n\n x$K <- round(fit$K)\n\n mdl <- glm(log(K) ~ x , data = x)\n\n stat_pred <- predict(mdl,type='response')\n\n fit$stat_pred <- exp(stat_pred)\n\n rc <- fit\n return(rc)\n\n}\n\n\n\n\n################### MORE GENERAL FRAMEWORK#################\n\n##' Functoin that fits a general epidemic and statistical model using an EM\n##' algorithm.\n##'\n##' @param epi.curves the individual epidemic curves to fit\n##' @param x data frame of covariates. First columns assumed to contain K initialized for the odel fits\n##' @param stat.mdl.fit a function that fits the statistical model with the following parameters and returns a fir model:\n##' - x: a data frame of covariates that must include the final size column K a\n##' @param epi.mdl.fit a function that calls the epi model with the following parameter and returns a fit model:\n##' - epi.curves: the epidemic curves.\n##' - K: the projected fornal sizes\n##' - prev.mdl : the previous model. should behave when this is null\n##' @param stat.mdl.pred: a function that takes in a statisitcal model and returns a vector of predicted final sizes\n##' @param epi.mdl.pred: a fuctnion that takes in the epdiemic model and and returns a vector of predicted final sizes\n##' @param max.iter the maximum number of iterations to run\n##' @param threshold the desired precision of the putput\n##'\n##'\n##' @return a vector of estimated final sizes\n##'\nepiInf.EM <- function (epi.curves, x,\n stat.mdl.fit, epi.mdl.fit,\n stat.mdl.pred, epi.mdl.pred,\n max.iter=100, threshold = 10^-5) {\n\n\n iter <- 0 #keep track of iterations\n\n ##for the first loop through, make sure that we are abover threshold\n iter.diff <- 2*threshold *2\n\n ##matrices for holding results.\n K <- matrix(nrow=max.iter, ncol= length(epi.curves))\n K.stat <- matrix(nrow=max.iter, ncol= length(epi.curves))\n\n ##previous epi model\n prev.epi.mdl <- NULL\n\n ## Loop until endinc criteria is met\n while ((iter.diff >= threshold) &\n (iter1) {\n ##iter.diff <- max(sum(abs(K[iter-1,]-K[iter,])),\n ## sum(abs(K.stat[iter-1,]-K.stat[iter,])))\n iter.diff <- sum(abs(K[iter-1,]-K[iter,]))/length(K[iter,])\n #print(cbind(K[iter-1,],K[iter,]))\n\n }\n\n ##print(cbind(x$K, K[iter,]))\n ##hist(K.stat[iter,]- K[iter,])\n ##print(which(abs(K.stat[iter,]- K[iter,])>10000))\n #cat(iter, \":\",iter.diff ,\":\", range(K[iter,]),\":\",\n # range(K.stat[iter,]),\"\\n\")\n }\n\n\n ##return a list with the two Ks and the final Ks\n return(list(K=K[iter,],\n K.stat=K.stat[iter,],\n Khist = K[1:iter,],\n Khist.stat = K.stat[1:iter,]))\n}\n\n\n##' Function for doing random forrest fit of the K data appropriate for\n##' passing in to epiInf.EM\n##'\n##' @param x the data frame to fit basedd on\n##'\n##' @return a fit random forrest model\n##'\nstat.mdl.rf.fit <- function(x) {\n require(randomForest)\n\n y <- x$K\n x <- as.matrix(subset(x, select=-K))\n\n rc <- randomForest(x=x, y=y)\n\n return(rc)\n}\n\n\n\n##'Function for doing the predict for duing the predict for the\n##' results from a stat.mdl.rf.fit\n##'\n##' @param mdl the fit model\n##'\n##' @return a vector of predicted final sizes\n##'\nstat.mdl.rf.pred <- function(mdl) {\n return(predict(mdl))\n}\n\n\n\n##' Function for doing random forrest fit of the K data appropriate for\n##' passing in to epiInf.EM\n##'\n##' @param x the data frame to fit basedd on\n##'\n##' @return a fit random forrest model\n##'\nstat.mdl.rpart.fit <- function(x) {\n require(rpart)\n\n f <- formula(paste0(\"K~\",paste(names(subset(x,select=-K)),collapse=\"+\")))\n rc <- rpart(f, data=x)\n\n return(rc)\n}\n\n\n\n##'Function for doing the predict for duing the predict for the\n##' results from a stat.mdl.rf.fit\n##'\n##' @param mdl the fit model\n##'\n##' @return a vector of predicted final sizes\n##'\nstat.mdl.rpart.pred <- function(mdl) {\n return(predict(mdl))\n}\n\n\n\n##' Function for doing the fit for a viboud chowell model of the epidemic curves.\n##' Parameters are considered to be drawn from a shared distribution. Fit is done via optim\n##'\n##' @param ecs the epidemic curves\n##' @param K the Ks\n##'\n##' @return a vector of parameters for the fit model\n##'\nepi.mdl.ViboudChowell.fit <- function (ecs, K) {\n\n ##make some starting values for p and r with a touch of noise\n logistic.p.intercept <- 0\n logistic.p <- rnorm(length(ecs),0,1)\n\n log.r.intercept <- 0\n log.r <- rnorm(length(ecs),0,1)\n\n\n\n ## Calculate the cumulative incidence curves\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n ## will fit by optim using poisson error function at each step with shared priors.\n ## param vector is structured as follows....first parameter is shared r\n ## parameters 2...(length(ec)+1) are individual rs\n ## parameters (length(ec)+2 is shard p\n ## parameters length(ec)+3...2*length(ec)+2 are inividual ps\n ob.func <- function(param) {\n rc <- 0\n for(i in 1:length(epi.curve)){\n loc.r <- exp(param[1+i])\n loc.p <- inv_logistic(param[length(ecs)+2+i]) #range 0 to 1\n\n ## preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/K)\n\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - cum.curve[[i]]/K[i])\n preds[preds<.1] <- .1\n #print(length(param))\n #cat(\"locp :\", loc.p, \"locr :\", loc.r,\"\\n\")\n #print(cbind(preds,epi.curve[[i]], dpois(epi.curve[[i]],preds)))\n log.prob <- sum(dpois(epi.curve[[i]], preds, log=TRUE)) +\n dnorm(param[1+i],param[1], 3) + ##magic number of variance\n dnorm(param[length(ecs)+2+i], param[length(ecs)+2], 3) ##magic number\n #cat(i,\":\",log.prob,\"\\n\")\n\n rc <- rc - log.prob\n\n\n }\n return(rc)\n }\n\n tmp <- optim(c(log.r.intercept, log.r, logistic.p.intercept, logistic.p), ob.func,\n method=\"CG\")\n return(list(r=exp(tmp$par[(1+(1:length(ecs)))]), p=inv_logistic(tmp$par[(2+length(ecs)+(1:length(ecs)))]), ecs=ecs,\n fit.Ks=K))\n\n}\n\n\n\n##' Funciton for doing the \"predict\" step for the viboud cholel model\n##' Essentially takes the p and r parameters and fits K given those parameters\n##'\n##' Has some weak schrinkage of K towards a single value\n##'\n##' @param pars the parameters from a model fit given K\n##'\n##' @return a vector of Ks\n##'\nepi.mdl.ViboudChowell.pred <- function(pars) {\n log.K <- log(pars$fit.Ks)\n ecs <- pars$ecs\n\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n ## Joint fitting of Ks\n ob.func <- function(param) {\n rc <- 0\n for(i in 1:length(epi.curve)){\n loc.r <- pars$r[i]\n loc.p <- pars$p[i]\n loc.a <- pars$a[i]\n K <- exp(param[i])\n\n ## preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/K)\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - (cum.curve[[i]]/K)^loc.a)\n preds[preds<.1] <- .1\n #print(length(param))\n #cat(\"locp :\", loc.p, \"locr :\", loc.r,\" loc.K:\", K, \"\\n\")\n #print(preds)\n log.prob <- sum(dpois(epi.curve[[i]], preds, log=TRUE))#+\n #dnorm(log(K), mean(param), 2, log=TRUE)\n\n rc <- rc - log.prob\n }\n\n return(rc)\n }\n\n ##tmp <- optim(log.K, ob.func,control=list(maxit=5000))\n tmp <- optim(log.K, ob.func, method=\"Nelder-Mead\", control=list(maxit=10000))\n\n print(tmp)\n\n return(exp(tmp$par))\n\n}\n\n\n\n\n##' Function for doing the first fit for a viboud chowell model of the epidemic curves.\n##' Parameters are considered to be drawn from a shared distribution.\n##'\n##' Fit is done via optim\n##'\n##' @param ecs the epidemic curves\n##'\n##' @return a vector of Ks\n##'\nepi.mdl.ViboudChowell.init <- function (ecs) {\n\n ##make some starting values for p and r with a touch of noise\n logistic.p.intercept <- 0\n logistic.p <- rnorm(length(ecs),0,1)\n\n log.r.intercept <- 0\n log.r <- rnorm(length(ecs),0,1)\n\n log.K <- log(2*sapply(ecs,sum))\n\n log.a.intercept <- 0\n log.a <- rnorm(length(ecs),0,1)\n\n\n ## Calculate the cumulative incidence curves\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n ## will fit by optim using poisson error function at each step with shared priors.\n ## param vector is structured as follows....first parameter is shared r\n ## parameters 2...(length(ec)+1) are individual rs\n ## parameters (length(ec)+2 is shard p\n ## parameters length(ec)+3...2*length(ec)+2 are inividual ps\n ## parameter 2*length(ec)+3...3*length(ec) are the Ks\n ob.func <- function(param) {\n rc <- 0\n for(i in 1:length(epi.curve)){\n loc.r <- exp(param[1+i])\n loc.p <- inv_logistic(param[length(ecs)+2+i]) #range 0 to 1\n loc.K <- exp(param[2*length(ecs)+2+i])\n loc.a <- exp(param[3*length(ecs)+3+i])\n\n ## preds <- loc.r*cum.curve^loc.p * (1 - cum.curve/K)\n\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - (cum.curve[[i]]/loc.K)^loc.a)\n\n\n preds[preds<.1] <- .1\n\n\n log.prob <- sum(dpois(epi.curve[[i]], preds, log=TRUE)) +\n dnorm(param[1+i],param[1], 3, log=T) + ##magic number of variance\n dnorm(param[length(ecs)+2+i], param[length(ecs)+2], 3, log=T) +\n dnorm(param[3*length(ecs)+3+i], param[3*length(ecs)+3], 3, log=T)# +\n ##dnorm(log10(loc.K),0,5, log=T)\n\n\n\n ## if(is.nan(log.prob)) {\n ## print(cbind(preds,epi.curve[[i]], dpois(epi.curve[[i]],preds, log=T)))\n ## cat(\"locp :\", loc.p, \"locr :\", loc.r,\"logprob:\", log.prob,\"\\n\")\n ## }\n\n rc <- rc - log.prob\n\n }\n #print(rc)\n\n return(rc)\n }\n\n tmp <- optim(c(log.r.intercept, log.r, logistic.p.intercept, logistic.p, log.K,\n log.a.intercept, log.a), ob.func,\n control=list(maxit=10000))\n print(tmp)\n return(list(r=exp(tmp$par[(1+(1:length(ecs)))]),\n p=inv_logistic(tmp$par[(2+length(ecs)+(1:length(ecs)))]),\n K=exp(tmp$par[2*length(ecs)+2+1:length(ecs)]),\n a=exp(tmp$par[3*length(ecs)+3+1:length(ecs)])))\n\n}\n\n\n\n##' Function for doing the first fit for a viboud chowell model of the epidemic curves.\n##' Parameters are fit independently for each epidemic\n##'\n##' Fit is done via optim\n##'\n##' @param ecs the epidemic curves\n##'\n##' @return a vector of Ks\n##'\nepi.mdl.ViboudChowell.init2 <- function (ecs) {\n\n ##make some starting values for p and r with a touch of noise\n logistic.p <- rnorm(length(ecs),0,1)\n\n log.r <- rnorm(length(ecs),0,1)\n\n log.K <- log(2*sapply(ecs,sum))\n\n log.a <- rnorm(length(ecs),0,1)\n\n ## Calculate the cumulative incidence curves\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n\n ob.func <- function(param) {\n rc <- 0\n loc.r <- exp(param[1])\n loc.p <- inv_logistic(param[2]) #range 0 to 1\n loc.K <- exp(param[3])\n loc.a <- exp(param[4])\n\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - (cum.curve[[i]]/loc.K)^loc.a)\n\n\n preds[preds<.1] <- .1\n\n\n log.prob <- sum(dpois(epi.curve[[i]], preds, log=TRUE)) +\n dnorm(log10(loc.K),0,5, log=T)\n\n rc <- - log.prob\n\n return(rc)\n }\n\n rc <- list()\n\n for (i in 1:length(ecs)) {\n tmp <- optim(c(log.r[i], logistic.p[i],\n log.K[i], log.a[i]), ob.func,\n control=list(maxit=10000))\n rc$converged <- c(rc$converged,tmp$convergence)\n rc$r <- c(rc$r, exp(tmp$par[1]))\n rc$p <- c(rc$p, inv_logistic(tmp$par[2]))\n rc$K <- c(rc$K, exp(tmp$par[3]))\n rc$a <- c(rc$a, exp(tmp$par[4]))\n\n }\n\n return(rc)\n\n\n}\n\n\n##' Funciton for doing the \"predict\" step for the viboud cholel model\n##' Essentially takes the p and r parameters and fits K given those parameters\n##'\n##' Has some weak schrinkage of K towards 0e\n##'\n##' @param pars the parameters from a model fit given K\n##'\n##' @return a vector of Ks\n##'\nepi.mdl.ViboudChowell.pred2 <- function(pars) {\n log.K <- log(pars$fit.Ks)\n ecs <- pars$ecs\n\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n\n\n ##Individual fitting of Ks\n ob.func <- function(param, loc.r, loc.p, loc.a, cum.curve, epi.curve) {\n K <- param\n preds <- loc.r*cum.curve^loc.p * (1 - (cum.curve/K)^loc.a)\n preds[preds<.1] <- .1\n\n log.prob <- sum(dpois(epi.curve, preds, log=TRUE)) +\n dnorm(log10(K),0,9, log=T)\n\n return(-log.prob)\n }\n\n rc <- rep(NA, length(log.K))\n\n\n for (i in 1:length(rc)) {\n tmp <- optimize(ob.func, c(sum(ecs[[i]]), 10^7),\n loc.r=pars$r[i], loc.p=pars$p[i],\n loc.a=pars$a[i],\n cum.curve = cum.curve[[i]],\n epi.curve=epi.curve[[i]])\n rc[i] <- tmp$minimum\n }\n\n return(rc)\n}\n\n\n\n\n##' Function for doing the fit for a viboud chowell model of the epidemic curves.\n##' Parameters are considered to be independent for each epidem. Fit is done via optim\n##'\n##' @param ecs the epidemic curves\n##' @param K the Ks\n##' @param prev.mde an optional argument with the previous model\n##'\n##' @return a vector of parameters for the fit model\n##'\nepi.mdl.ViboudChowell.fit2 <- function (ecs, K, prev.mdl=NULL) {\n\n ##make some starting values for p and r with a touch of noise\n if (is.null(prev.mdl)) {\n logistic.p <- rnorm(length(ecs),0,1)\n log.r <- rnorm(length(ecs),0,1)\n log.a <- rnorm(length(ecs),0,1)\n } else {\n logistic.p <- prev.mdl$logistic.p\n log.r <- prev.mdl$log.r\n log.a <- prev.mdl$log.a\n }\n\n\n\n ## Calculate the cumulative incidence curves\n cum.curve = lapply(ecs,cumsum)\n cum.curve <- lapply(cum.curve,function(x){x[-length(x)]}) ##drop the last cumsum observation as it does not contibute\n epi.curve <- lapply(ecs,function(x){x[-1]}) ##first observed epi curve also does not contribute\n\n\n lapply(epi.curve,function(x){if(length(x) == 0){stop(\"Do not use empty epi curves.\")}})\n\n\n\n ob.func <- function(param, loc.K) {\n rc <- 0\n loc.r <- exp(param[1])\n loc.p <- inv_logistic(param[2]) #range 0 to 1\n loc.a <- exp(param[3])\n\n preds <- loc.r*cum.curve[[i]]^loc.p * (1 - (cum.curve[[i]]/loc.K)^loc.a)\n\n\n preds[preds<.1] <- .1\n\n\n log.prob <- sum(dpois(epi.curve[[i]], preds, log=TRUE)) +\n dnorm(log10(loc.K),0,9, log=T)\n\n rc <- - log.prob\n\n return(rc)\n }\n\n rc <- list()\n\n for (i in 1:length(ecs)) {\n tmp <- optim(c(log.r[i], logistic.p[i],\n log.a[i]), ob.func,\n loc.K = K[i],\n control=list(maxit=10000))\n rc$converged <- c(rc$converged,tmp$convergence)\n rc$log.r <- c(rc$log.r, tmp$par[1])\n rc$logistic.p <- c(rc$logistic.p, tmp$par[2])\n rc$log.a <- c(rc$log.a, tmp$par[3])\n\n }\n\n rc$r <- exp(rc$log.r)\n rc$p <- inv_logistic(rc$logistic.p)\n rc$a <- exp(rc$log.a)\n\n rc$fit.Ks <- K\n rc$ecs <- ecs\n\n return(rc)\n\n\n}\n\n\n\n##' Version of the epidemiologic model that fits a normal distribution to an epidemic curve.\n##' INitialization fits all parameters, including final size, peak time (i.e., mean) and\n##' spread (i.e., standard deviation)\n##'\n##' @param ecs the epidemic curves\n##'\n##' @return a list with final size, peak time and spread\n##'\nepi.mdl.normcurve.init <- function(ecs) {\n\n fs <- 2*sapply(ecs, sum) #start at twice the observed cases\n peak.time <- sapply(ecs, length) #the consistent choice for peak time is the length of the EC\n spread <- peak.time/3 #the consistent choice for peak time and size\n converged <- rep(0, length(ecs))\n\n ##objective function. POisson error on pedicted incdience.\n ob.func <- function(par, ec) {\n loc.fs <- exp(par[1])\n loc.sd <- exp(par[3])\n pred <- loc.fs * (pnorm(1:length(ec), par[2], loc.sd) - pnorm((1:length(ec))-1, par[2], loc.sd))\n\n\n log.prob <- sum(dpois(ec, pred, log=TRUE)) +\n dnorm(log10(loc.fs), 0,1, log=TRUE)\n\n if(is.nan(log.prob)) {\n print(par)\n print(ec)\n }\n\n return(-log.prob)\n }\n\n\n for (i in 1:length(ecs)) {\n ec <- ecs[[i]]\n\n\n #print(c(fs[i], peak.time[i], spread[i]))\n tmp <- optim(c(log(fs[i]), peak.time[i], log(spread[i])), ob.func, ec=ecs[[i]])\n\n converged[i] <- tmp$convergence\n fs[i] <- exp(tmp$par[1])\n peak.time[i] <- tmp$par[2]\n spread[i] <- exp(tmp$par[3])\n }\n\n return(list(K=fs, peak.time = peak.time, spread=spread, converged=converged))\n\n}\n\n\n\n##' Version of the epidemiologic model that fits a normal distribution to an epidemic curve.\n##' fit fits the\n##'\n##' @param ecs the epidemic curves\n##' @param K the values of K\n##' @param prev.mdl the previous model, can be null\n##'\n##' @return a list with final size, peak time and spread\n##'\nepi.mdl.normcurve.fit <- function(ecs, K, prev.mdl=NULL) {\n\n fs <- K #start at twice the observed cases\n peak.time <- sapply(ecs, length) #the consistent choice for peak time is the length of the EC\n\n if (is.null(prev.mdl)) {\n peak.time <- sapply(ecs, length) #the consistent choice for peak time is the length of the EC\n spread <- peak.time/3 #the consistent choice for peak time and size\n } else {\n peak.time <- prev.mdl$peak.time\n spread <- prev.mdl$spread\n }\n\n converged <- rep(0, length(ecs))\n\n ##objective function. POisson error on pedicted incdience.\n ob.func <- function(par, ec, fs) {\n loc.sd <- exp(par[2])\n pred <- fs * (pnorm(1:length(ec), par[1], loc.sd) - pnorm((1:length(ec))-1, par[1], loc.sd))\n\n log.prob <- sum(dpois(ec, pred, log=TRUE))\n\n if (is.nan(log.prob)) {\n print(par)\n print(ec)\n }\n\n return(-log.prob)\n }\n\n\n for (i in 1:length(ecs)) {\n ec <- ecs[[i]]\n\n\n #print(c(fs[i], peak.time[i], spread[i]))\n tmp <- optim(c(peak.time[i], log(spread[i])), ob.func, ec=ecs[[i]], fs=fs[i])\n\n converged[i] <- tmp$convergence\n peak.time[i] <- tmp$par[1]\n spread[i] <- exp(tmp$par[2])\n }\n\n return(list(K=fs, peak.time = peak.time, spread=spread, converged=converged, ecs=ecs))\n\n}\n\n\n\n##' Version of the epidemiologic model that fits a normal distribution to an epidemic curve.\n##' INitialization fits all parameters, including final size, peak time (i.e., mean) and\n##' spread (i.e., standard deviation)\n##'\n##' @param ecs the parameters of the fit model\n##'\n##' @return a list with final size, peak time and spread\n##'\nepi.mdl.normcurve.pred <- function(pars) {\n\n #everything starts at the previous estimates for everything\n fs <- pars$K\n peak.time <- pars$peak.time\n spread <- pars$spread\n converged <- rep(0, length(pars$ecs))\n\n\n ##objective function. POisson error on pedicted incdience.\n ob.func <- function(par, ec, peak.time, spread) {\n\n pred <- par * (pnorm(1:length(ec), peak.time, spread) - pnorm((1:length(ec))-1, peak.time, spread))\n\n log.prob <- sum(dpois(ec, pred, log=TRUE)) +\n dnorm(log10(par),0, 1, log=TRUE)\n\n if(is.nan(log.prob)) {\n print(par)\n print(peak.time)\n print(spread)\n print(ec)\n }\n\n return(-log.prob)\n }\n\n\n for (i in 1:length(ecs)) {\n ec <- pars$ecs[[i]]\n #print(ec)\n #print(c(fs[i], peak.time[i], spread[i]))\n\n tmp <- optimize(ob.func, interval=c(sum(ec),10^7), ec=ec, peak.time=peak.time[i], spread=spread[i])\n\n fs[i] <- tmp$minimum\n }\n\n return(fs)\n\n}\n\n\n##' Function for doing random forrest fit of the K data appropriate for\n##' passing in to epiInf.EM\n##'\n##' @param x the data frame to fit basedd on\n##'\n##' @return a fit random forrest model\n##'\nstat.mdl.linear.fit <- function(x) {\n require(rpart)\n\n f <- formula(paste0(\"K~\",paste(names(subset(x,select=-K)),collapse=\"+\")))\n rc <- lm(f, data=x)\n\n return(rc)\n}\n\n\n\n##'Function for doing the predict for duing the predict for the\n##' results from a stat.mdl.rf.fit\n##'\n##' @param mdl the fit model\n##'\n##' @return a vector of predicted final sizes\n##'\nstat.mdl.linear.pred <- function(mdl) {\n rc <-predict(mdl)\n rc[rc<1] <- 1\n return(rc)\n}\n\n\n\n##' Function for doing superlearner fit of the K data appropriate for\n##' passing in to iInf.EM\n##'\n##' @param x the data frame to fit basedd on\n##'\n##' @return a fit superlearner model\n##'\nstat.mdl.sl.fit <- function(x) {\n require(SuperLearner)\n require(gam)\n require(rpart)\n require(randomForest)\n y <- x$K\n x <- as.data.frame(subset(x, select=-K))\n rc <- SuperLearner(X = x, Y = y, newX = x, family = \"gaussian\", SL.library = c(\"SL.rpart\", \"SL.randomForest\", \"SL.glm\", 'SL.gam')) #'SL.gam',\n ##rc <- SuperLearner(X = x, Y = y, newX = x, family = \"gaussian\", SL.library = c(\"SL.rpart\", \"SL.glm\", 'SL.gam')) #'SL.gam',\n\n return(rc)\n}\n##'Function for doing the predict for duing the predict for the\n##' results from a stat.mdl.sl.fit\n##'\n##' @param mdl the fit model\n##'\n##' @return a vector of predicted final sizes\n##'\nstat.mdl.sl.pred <- function(mdl) {\n return(pmax(1,predict(mdl, onlySL = T)$pred))\n}\n", "meta": {"hexsha": "54fc997f117eabfe9e3a7b41e188a332a63cb872", "size": 47220, "ext": "r", "lang": "R", "max_stars_repo_path": "R/EpiProgInf.r", "max_stars_repo_name": "HopkinsIDD/EpiForecastStatMech", "max_stars_repo_head_hexsha": "4ba57edff1ece0c56ec6dfa41eac4cfe4a1c66cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-11T17:24:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T09:28:03.000Z", "max_issues_repo_path": "R/EpiProgInf.r", "max_issues_repo_name": "HopkinsIDD/EpiForecastStatMech", "max_issues_repo_head_hexsha": "4ba57edff1ece0c56ec6dfa41eac4cfe4a1c66cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-03T23:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T12:15:58.000Z", "max_forks_repo_path": "R/EpiProgInf.r", "max_forks_repo_name": "HopkinsIDD/EpiForecastStatMech", "max_forks_repo_head_hexsha": "4ba57edff1ece0c56ec6dfa41eac4cfe4a1c66cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-13T18:39:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T02:02:54.000Z", "avg_line_length": 30.0190718373, "max_line_length": 176, "alphanum_fraction": 0.5912113511, "num_tokens": 13308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6661580163504348}} {"text": "# get_scale_breaks_untransformed.r\n#\n# Copyright (c) 2020 VIB (Belgium) & Babraham Institute (United Kingdom)\n#\n# Software written by Carlos P. Roca, as research funded by the European Union.\n#\n# This software may be modified and distributed under the terms of the MIT\n# license. See the LICENSE file for details.\n\n\n# Returns a vector of scale breaks well distributed as powers of 10, inside\n# the given range limit.plot.untr and avoiding exponents smaller than mix.exp.\n\nget.scale.breaks.untransformed <- function( limit.plot.untr, min.exp )\n{\n if ( limit.plot.untr[ 1 ] > 10^min.exp )\n breaks.exp.min <- ceiling( log10( limit.plot.untr[ 1 ] ) )\n else if ( limit.plot.untr[ 1 ] > 0 )\n breaks.exp.min <- min.exp\n else if ( limit.plot.untr[ 1 ] > -10^min.exp )\n breaks.exp.min <- 0\n else\n breaks.exp.min <- - floor( log10( - limit.plot.untr[ 1 ] ) )\n\n if ( limit.plot.untr[ 2 ] < -10^min.exp )\n breaks.exp.max <- - ceiling( log10( - limit.plot.untr[ 2 ] ) )\n else if ( limit.plot.untr[ 2 ] < 0 )\n breaks.exp.max <- - min.exp\n else if ( limit.plot.untr[ 2 ] < 10^min.exp )\n breaks.exp.max <- 0\n else\n breaks.exp.max <- floor( log10( limit.plot.untr[ 2 ] ) )\n\n breaks.exp <- breaks.exp.min : breaks.exp.max\n\n breaks.exp <- breaks.exp[\n abs( breaks.exp ) == 0 | abs( breaks.exp ) >= min.exp ]\n\n sapply( breaks.exp, function ( be )\n if ( be > 0 )\n 10^be\n else if ( be < 0 )\n -10^-be\n else\n be\n )\n}\n\n", "meta": {"hexsha": "46b0e4c0f7d5b7cfa71fc0a310813b53e41f64cc", "size": 1547, "ext": "r", "lang": "R", "max_stars_repo_path": "R/get_scale_breaks_untransformed.r", "max_stars_repo_name": "DillonHammill/autospill", "max_stars_repo_head_hexsha": "2cd601ea9481688497f0800e7c873bbf71ba5f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-08-07T21:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T03:00:59.000Z", "max_issues_repo_path": "R/get_scale_breaks_untransformed.r", "max_issues_repo_name": "DillonHammill/autospill", "max_issues_repo_head_hexsha": "2cd601ea9481688497f0800e7c873bbf71ba5f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-10T08:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T23:41:00.000Z", "max_forks_repo_path": "R/get_scale_breaks_untransformed.r", "max_forks_repo_name": "DillonHammill/autospill", "max_forks_repo_head_hexsha": "2cd601ea9481688497f0800e7c873bbf71ba5f1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-09-05T14:15:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T14:36:42.000Z", "avg_line_length": 31.5714285714, "max_line_length": 79, "alphanum_fraction": 0.592760181, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6660756186960155}} {"text": "pcor_test <- function(x, y, z, use = \"mat\", method = \"p\", na.rm = TRUE) {\n # The partial correlation coefficient between x and y given z\n #\n # pcor.test is free and comes with ABSOLUTELY NO WARRANTY.\n #\n # x and y should be vectors\n #\n # z can be either a vector or a matrix\n #\n # use: There are two methods to calculate the partial correlation coefficient.\n # \t One is by using variance-covariance matrix (\"mat\") and the other is by using recursive formula (\"rec\").\n # \t Default is \"mat\".\n #\n # method: There are three ways to calculate the correlation coefficient,\n # \t which are Pearson's (\"p\"), Spearman's (\"s\"), and Kendall's (\"k\") methods.\n # \t The last two methods which are Spearman's and Kendall's coefficient are based on the non-parametric analysis.\n # \t Default is \"p\".\n #\n # na.rm: If na.rm is T, then all the missing samples are deleted from the whole dataset, which is (x,y,z).\n # If not, the missing samples will be removed just when the correlation coefficient is calculated.\n # \t However, the number of samples for the p-value is the number of samples after removing\n # \t all the missing samples from the whole dataset.\n # \t Default is \"T\".\n\n x <- c(x)\n y <- c(y)\n z <- as.data.frame(z)\n\n if (use == \"mat\") {\n p.use <- \"Var-Cov matrix\"\n pcor <- pcor.mat(x, y, z, method = method, na.rm = na.rm)\n } else if (use == \"rec\") {\n p.use <- \"Recursive formula\"\n pcor <- pcor.rec(x, y, z, method = method, na.rm = na.rm)\n } else {\n stop(\"\\'use\\' should be either \\\"rec\\\" or \\\"mat\\\"!\\n\")\n }\n\n # print the method\n if (gregexpr(\"p\", method)[[1]][1] == 1) {\n p.method <- \"Pearson\"\n } else if (gregexpr(\"s\", method)[[1]][1] == 1) {\n p.method <- \"Spearman\"\n } else if (gregexpr(\"k\", method)[[1]][1] == 1) {\n p.method <- \"Kendall\"\n } else {\n stop(\"\\'method\\' should be \\\"pearson\\\" or \\\"spearman\\\" or \\\"kendall\\\"!\\n\")\n }\n\n # sample number\n n <- dim(na.omit(data.frame(x, y, z)))[1]\n\n # given variables' number\n gn <- dim(z)[2]\n\n # p-value\n if (p.method == \"Kendall\") {\n statistic <- pcor / sqrt(2 * (2 * (n - gn) + 5) / (9 * (n - gn) * (n - 1 - gn)))\n p.value <- 2 * pnorm(-abs(statistic))\n } else {\n statistic <- pcor * sqrt((n - 2 - gn) / (1 - pcor^2))\n p.value <- 2 * pnorm(-abs(statistic))\n }\n\n data.frame(estimate = pcor, p.value = p.value, statistic = statistic, n = n, gn = gn, Method = p.method, Use = p.use)\n}\n\n# By using var-cov matrix\npcor.mat <- function(x, y, z, method = \"p\", na.rm = T) {\n x <- c(x)\n y <- c(y)\n z <- as.data.frame(z)\n\n if (dim(z)[2] == 0) {\n stop(\"There should be given data\\n\")\n }\n\n data <- data.frame(x, y, z)\n\n if (na.rm == T) {\n data <- na.omit(data)\n }\n\n xdata <- na.omit(data.frame(data[, c(1, 2)]))\n Sxx <- cov(xdata, xdata, m = method)\n\n xzdata <- na.omit(data)\n xdata <- data.frame(xzdata[, c(1, 2)])\n zdata <- data.frame(xzdata[, -c(1, 2)])\n Sxz <- cov(xdata, zdata, m = method)\n\n zdata <- na.omit(data.frame(data[, -c(1, 2)]))\n Szz <- cov(zdata, zdata, m = method)\n\n # is Szz positive definite?\n zz.ev <- eigen(Szz)$values\n if (min(zz.ev)[1] < 0) {\n stop(\"\\'Szz\\' is not positive definite!\\n\")\n }\n\n # partial correlation\n Sxx.z <- Sxx - Sxz %*% solve(Szz) %*% t(Sxz)\n\n rxx.z <- cov2cor(Sxx.z)[1, 2]\n\n rxx.z\n}\n\n# By using recursive formula\npcor.rec <- function(x, y, z, method = \"p\", na.rm = T) {\n #\n\n x <- c(x)\n y <- c(y)\n z <- as.data.frame(z)\n\n if (dim(z)[2] == 0) {\n stop(\"There should be given data\\n\")\n }\n\n data <- data.frame(x, y, z)\n\n if (na.rm == T) {\n data <- na.omit(data)\n }\n\n # recursive formula\n if (dim(z)[2] == 1) {\n tdata <- na.omit(data.frame(data[, 1], data[, 2]))\n rxy <- cor(tdata[, 1], tdata[, 2], m = method)\n\n tdata <- na.omit(data.frame(data[, 1], data[, -c(1, 2)]))\n rxz <- cor(tdata[, 1], tdata[, 2], m = method)\n\n tdata <- na.omit(data.frame(data[, 2], data[, -c(1, 2)]))\n ryz <- cor(tdata[, 1], tdata[, 2], m = method)\n\n rxy.z <- (rxy - rxz * ryz) / (sqrt(1 - rxz^2) * sqrt(1 - ryz^2))\n\n return(rxy.z)\n } else {\n x <- c(data[, 1])\n y <- c(data[, 2])\n z0 <- c(data[, 3])\n zc <- as.data.frame(data[, -c(1, 2, 3)])\n\n rxy.zc <- pcor.rec(x, y, zc, method = method, na.rm = na.rm)\n rxz0.zc <- pcor.rec(x, z0, zc, method = method, na.rm = na.rm)\n ryz0.zc <- pcor.rec(y, z0, zc, method = method, na.rm = na.rm)\n\n rxy.z <- (rxy.zc - rxz0.zc * ryz0.zc) / (sqrt(1 - rxz0.zc^2) * sqrt(1 - ryz0.zc^2))\n return(rxy.z)\n }\n}\n", "meta": {"hexsha": "9f41d5940449653c2d81f9766878e66a354a458c", "size": 4488, "ext": "r", "lang": "R", "max_stars_repo_path": "data-raw/function/pcor.r", "max_stars_repo_name": "qins/UCSCXenaShiny", "max_stars_repo_head_hexsha": "e622c2830ebce05ef715b1d792c7ad3e0616fa62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-07T11:40:34.000Z", "max_issues_repo_path": "data-raw/function/pcor.r", "max_issues_repo_name": "fei0810/UCSCXenaShiny", "max_issues_repo_head_hexsha": "398605a5da859886313649036da739feee0edec3", "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-raw/function/pcor.r", "max_forks_repo_name": "fei0810/UCSCXenaShiny", "max_forks_repo_head_hexsha": "398605a5da859886313649036da739feee0edec3", "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.9548387097, "max_line_length": 119, "alphanum_fraction": 0.5565953654, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6659980196940507}} {"text": "\nac_powerflow = function(\n file_name, \n v_fr = 1.0, v_to = 1.0,\n vd_ub = 0.2, vd_lb = -0.2,\n ad_ub = pi/6, ad_lb = -pi/6,\n y_m = 1.0, y_a = -1.45,\n t_m = 1.0, t_a = 0.0\n ) {\n\n g = y_m*cos(y_a)\n b = y_m*sin(y_a)\n\n steps = 100\n\n v_to_delta_lb = vd_lb + v_fr - v_to\n v_to_delta_ub = vd_ub + v_fr - v_to\n\n v_to_delta = seq(v_to_delta_lb, v_to_delta_ub, (v_to_delta_ub-v_to_delta_lb)/(steps-1))\n vd_vals = (rep(v_to, steps) + v_to_delta) - rep(v_fr, steps)\n ad_vals = seq(ad_lb, ad_ub, (ad_ub-ad_lb)/(steps-1))\n\n stopifnot(vd_lb <= min(vd_vals)+0.000001)\n stopifnot(vd_ub >= max(vd_vals)-0.000001)\n\n pv = matrix(nrow = steps, ncol = steps)\n qv = matrix(nrow = steps, ncol = steps)\n\n for (i in 1:steps) {\n v1 = v_fr;\n v2 = v_to + v_to_delta[i];\n for (j in 1:steps) {\n ad = ad_vals[j];\n pv[i,j] = g*v1^2/t_m^2 - g*v1/t_m*v2*cos(ad - t_a) - b*v1/t_m*v2*sin(ad - t_a)\n qv[i,j] = -b*v1^2/t_m^2 + b*v1/t_m*v2*cos(ad - t_a) - g*v1/t_m*v2*sin(ad - t_a)\n }\n }\n\n ps = 14\n pdf(file_name, pointsize=ps, width=14, height=7, bg=\"white\")\n\n par(mfrow=c(1,2), oma=c(0,0,2.5,0)) \n\n contour(\n x = vd_vals,\n y = ad_vals,\n pv,\n #color = terrain.colors,\n #levels = colorsteps,\n nlevels = 8,\n labcex=1.0,\n plot.title = title(main = \"Active Power (p)\",\n xlab = \"Voltage Difference\", ylab = \"Angle Difference (rad)\")\n )\n\n contour(\n x = vd_vals,\n y = ad_vals,\n qv,\n #color = terrain.colors,\n #levels = colorsteps,\n nlevels = 8,\n labcex=1.0,\n plot.title = title(main = \"Reactive Power (q)\",\n xlab = \"Voltage Difference\", ylab = \"Angle Difference (rad)\")\n )\n\n title(\"AC Power Flow Fields (from side, p.u.)\", outer=TRUE)\n mtext(\n sprintf(\"v1 = %.3f, g = %.3f, b = %.3f, tr = %.3f, as = %.3f\", v_fr, g, b, t_m, t_a), \n line=-1, outer=TRUE)\n\n dev.off()\n}\n\n\n\nac_powerloss = function(\n file_name, \n v_fr = 1.0, v_to = 1.0,\n vd_ub = 0.2, vd_lb = -0.2,\n ad_ub = pi/6, ad_lb = -pi/6,\n y_m = 1.0, y_a = -1.45,\n t_m = 1.0, t_a = 0.0\n ) {\n\n g = y_m*cos(y_a)\n b = y_m*sin(y_a)\n\n steps = 100\n\n v_to_delta_lb = vd_lb + v_fr - v_to\n v_to_delta_ub = vd_ub + v_fr - v_to\n\n v_to_delta = seq(v_to_delta_lb, v_to_delta_ub, (v_to_delta_ub-v_to_delta_lb)/(steps-1))\n vd_vals = (rep(v_to, steps) + v_to_delta) - rep(v_fr, steps)\n ad_vals = seq(ad_lb, ad_ub, (ad_ub-ad_lb)/(steps-1))\n\n stopifnot(vd_lb <= min(vd_vals)+0.000001)\n stopifnot(vd_ub >= max(vd_vals)-0.000001)\n\n pv_fr = matrix(nrow = steps, ncol = steps)\n qv_fr = matrix(nrow = steps, ncol = steps)\n\n pv_to = matrix(nrow = steps, ncol = steps)\n qv_to = matrix(nrow = steps, ncol = steps)\n\n for (i in 1:steps) {\n v1 = v_fr;\n v2 = v_to + v_to_delta[i];\n for (j in 1:steps) {\n ad = ad_vals[j];\n pv_fr[i,j] = g*v1^2/t_m^2 - g*v1/t_m*v2*cos(ad - t_a) - b*v1/t_m*v2*sin(ad - t_a)\n qv_fr[i,j] = -b*v1^2/t_m^2 + b*v1/t_m*v2*cos(ad - t_a) - g*v1/t_m*v2*sin(ad - t_a)\n\n pv_to[i,j] = g*v2^2 - g*v1/t_m*v2*cos(ad + t_a) - b*v1/t_m*v2*sin(ad + t_a)\n qv_to[i,j] = -b*v2^2 + b*v1/t_m*v2*cos(ad + t_a) - g*v1/t_m*v2*sin(ad + t_a)\n }\n }\n\n ps = 14\n pdf(file_name, pointsize=ps, width=14, height=7, bg=\"white\")\n\n par(mfrow=c(1,2), oma=c(0,0,2.5,0)) \n\n contour(\n x = vd_vals,\n y = ad_vals,\n pv_fr + pv_to,\n #color = terrain.colors,\n #levels = colorsteps,\n nlevels = 8,\n labcex=1.0,\n plot.title = title(main = \"Active Power (p)\",\n xlab = \"Voltage Difference\", ylab = \"Angle Difference (rad)\")\n )\n\n contour(\n x = vd_vals,\n y = ad_vals,\n qv_fr + qv_to,\n #color = terrain.colors,\n #levels = colorsteps,\n nlevels = 8,\n labcex=1.0,\n plot.title = title(main = \"Reactive Power (q)\",\n xlab = \"Voltage Difference\", ylab = \"Angle Difference (rad)\")\n )\n\n title(\"AC Power Loss Fields (p.u.)\", outer=TRUE)\n mtext(\n sprintf(\"v1 = %.3f, g = %.3f, b = %.3f, tr = %.3f, as = %.3f\", v_fr, g, b, t_m, t_a), \n line=-1, outer=TRUE)\n\n dev.off()\n}\n\n\n\nac_dc_comparison = function(\n file_name, \n v_fr = 1.0, v_to = 1.0,\n ad_ub = 1.5*pi/2, ad_lb = -1.5*pi/2,\n y_m = 1.0, y_a = -1.45,\n t_m = 1.0, t_a = 0.0\n ) {\n\n g = y_m*cos(y_a)\n b = y_m*sin(y_a)\n\n steps = 100\n\n ad_vals = seq(ad_lb, ad_ub, (ad_ub-ad_lb)/(steps-1))\n\n ac_p = rep(0.0, steps)\n dc_p = rep(0.0, steps)\n\n v1 = v_fr\n v2 = v_to\n for (i in 1:steps) {\n ad = ad_vals[i];\n ac_p[i] = g*v1^2/t_m^2 - g*v1/t_m*v2*cos(ad - t_a) - b*v1/t_m*v2*sin(ad - t_a)\n dc_p[i] = -b*v1/t_m*v2*(ad - t_a)\n }\n\n ps = 16\n pdf(file_name, pointsize=ps, width=7, height=7, bg=\"white\")\n x_range = c(min(ad_vals), max(ad_vals))\n y_range = c(min(ac_p, dc_p), max(ac_p, dc_p))\n plot(x_range, y_range, type=\"n\", xlab = \"Voltage Angle Difference (rad)\", ylab = \"Active Power (p.u.)\", main=\"AC vs DC Active Power Comparison\")\n abline(h=0.0, col=rgb(0,0,0,0.5))\n abline(v=0.0, col=rgb(0,0,0,0.5))\n points(ad_vals, dc_p, type=\"l\", lw=3, col=\"dodgerblue\")\n points(ad_vals, ac_p, type=\"l\", lw=3, col=\"darkorange\")\n legend(\"topleft\", legend=c(\"AC Power Flow\", \"DC Power Flow\"), lty=1, lw=3, col=c(\"darkorange\", \"dodgerblue\"), bg=\"white\")\n dev.off()\n}\n\n", "meta": {"hexsha": "01bc565c1ff50ab3ef2fde6597d6ea9a81bacdf1", "size": 5810, "ext": "r", "lang": "R", "max_stars_repo_path": "ac_powerflow_lib.r", "max_stars_repo_name": "ccoffrin/ac-powerflow-vis", "max_stars_repo_head_hexsha": "e875d2997673b9798cd1189093cedd8c5d44c94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-05-08T14:41:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T01:38:45.000Z", "max_issues_repo_path": "ac_powerflow_lib.r", "max_issues_repo_name": "ccoffrin/ac-powerflow-vis", "max_issues_repo_head_hexsha": "e875d2997673b9798cd1189093cedd8c5d44c94b", "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": "ac_powerflow_lib.r", "max_forks_repo_name": "ccoffrin/ac-powerflow-vis", "max_forks_repo_head_hexsha": "e875d2997673b9798cd1189093cedd8c5d44c94b", "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.1959798995, "max_line_length": 153, "alphanum_fraction": 0.5063683305, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6652071196531943}} {"text": "# Single Gerstner wave for plotting purposes only.\ngerstner_wave <- function(p, t, d, A, Q, w, phi) {\n H <- A*sin((p%*%d)*w + t*phi)\n Gx <- d[1]*Q*A*cos((p%*%d)*w + t*phi)\n Gz <- d[2]*Q*A*cos((p%*%d)*w + t*phi)\n return(c(p[1] + Gx, H, p[2] + Gz))\n}\n", "meta": {"hexsha": "5a2c4dae62ddbba67b8f974c72f4a60717ec3a28", "size": 261, "ext": "r", "lang": "R", "max_stars_repo_path": "utils/gerstner.r", "max_stars_repo_name": "CaffeineViking/lwss", "max_stars_repo_head_hexsha": "bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2018-09-28T06:58:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T14:08:23.000Z", "max_issues_repo_path": "utils/gerstner.r", "max_issues_repo_name": "CaffeineViking/lwss", "max_issues_repo_head_hexsha": "bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-02-11T18:49:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-16T12:29:21.000Z", "max_forks_repo_path": "utils/gerstner.r", "max_forks_repo_name": "CaffeineViking/lwss", "max_forks_repo_head_hexsha": "bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-06-05T02:36:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T09:04:54.000Z", "avg_line_length": 32.625, "max_line_length": 50, "alphanum_fraction": 0.5019157088, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6651953207601385}} {"text": "## LOOP WHILE:\n\n# Habiendo visto en la lección anterior el uso y ejemplos del loop for, haremos\n# lo propio con el loop 'while', que requiere del cumplimiento de una o más\n# condiciones para su ejecución.\n# Como su nombre lo indica, 'while' (mientras) es un loop que se ejecutará\n# solamente mientras la o las condiciones especificadas se cumplan, interrum-\n# piéndose inmediatamente cuando dejen de hacerlo.\n# Para ver la ayuda de R al respecto se pueden usar los comandos:\n?Control\n?\"while\"\n\n\n## SINTÁXIS\n# \"while\" es usado cuando el número de iteraciones deseado no es sabido de \n# antemano por el programador, si no que depende de una condición que va a \n# ir cambiando a medida que dichas iteraciones sean ejecutadas. Aquí veremos\n# algunos ejemplos sencillos, sin ver necesariamente el caso más general.\n\n# Usualmente un loop while se ve como esto (no ejecutar)\nwhile () {\n # Aquí\n # instrucciones\n}\n\n# Normalmente la condición (la expresión que está entre paréntesis) \n# involucra a algún objeto que es sujeto a cambios en las instrucciones. Veamos \n# un ejemplo sencillo:\nx <- 1\nwhile (x < 10) {\n print(x)\n x <- x + 2\n}\n\n# Podemos ver que aquí la expresión involucra a x (\"x < 10\") y que x es \n# modificado en las instrucciones, sumando un +2 en cada iteración. Conviene \n# observar también que aquí en la Preparación se definió x y que esto es \n# fundamental, ya que si no es imposible evaluar la expresión entre paréntesis. \n# Otra observación interesante es que en la consola se imprimieron todos los \n# valores menos el último (11), ¿puede deducir por qué ocurre esto?\n\n# Es importante entonces destacar que la expresión de la condición del loop \n# debe involucrar a una variable que cambie con las iteraciones, y dicha \n# variable debe eventualmente cambiar la condición a FALSE, porque de otra \n# forma es posible generar un loop while que corra indefinidamente. Los \n# siguientes son dos ejemplos (¡no ejecutar!):\n# Ej. 1: x no cambia dentro de las instrucciones:\nx <- 1\ny <- 1\nwhile (x < 10) {\n print(y)\n y <- y + 2\n}\n# Ej. 2: x cambia pero la condición nunca es FALSE:\nx <- 1\nwhile (x > 0) {\n print(x)\n x <- x + 2\n}\n\n# Veremos ahora un ejemplo más elaborado: la caminata del borracho.\n\n# La caminata aleatoria o del borracho es un ejemplo típico en cursos de física \n# o de matemática. Sirve para representar procesos aleatorios tales como la \n# deriva génica o el movimiento browniano. En su versión más sencilla, la \n# caminata ocurre sobre una recta (i.e.: tiene sólo 1 dimensión). El hombre \n# alcoholizado se encuentra en una posición inicial (0 para nosotros) y se va \n# a mover de forma aleatoria hacia izquierda o derecha en cada turno. Además la \n# longitud de cada paso es también aleatoria. Entonces para determinar tanto \n# dirección como longitud podemos tomar valores de una distribución normal o \n# gaussiana centrada en cero. La función rnorm nos sirve para este propósito, \n# por ejemplo:\nrnorm(100)\n# ... los valores pueden ser negativos o positivos y su valor absoluto tiene un \n# desvío estándar de 1. Cada paso del borracho será un número obtenido con esta \n# función.\n\n# Pero la caminata sería infinita a menos que se imponga un límite arbitrario. \n# En nuestra simulación determinaremos que el borracho dejará de caminar una \n# vez que se haya movido una distancia mayor a 10 para cualquiera de las dos \n# direcciones.\n\n# Vamos a tener un valor llamado pos que será la posición instantánea del \n# borracho, y un vector x en el cual vamos a almacenar toda la secuencia de \n# posiciones en un vector llamado x. Sabemos que pos es 0 inicialmente, así \n# que podemos empezar nuestro código con:\npos <- 0\n\n# Para definir x tenemos que saber cuántos elementos debe tener ... ¡pero en \n# verdad no lo sabemos! La caminata es aleatoria, por lo que es imposible saber \n# exactamente cuándo se detendrá. Hay varias formas de solucionar el problema, \n# pero la más sencilla (aunque ineficiente) es:\nx <- 0 # ó\nx <- pos\n\n# Entonces sólo nos queda hacer el loop:\nwhile (abs(pos) <= 10) {\n pos <- pos + rnorm(1)\n x <- c(x, pos)\n}\n\n# Veamos los distintos pasos ...\n\n# 1. La condición:\n# Como los límites de la caminata son 10 y -10, nos interesa evaluar si el \n# valor absoluto de pos es el que está por debajo de la distancia elegida (abs \n# es la función valor absoluto, por supuesto).\n# 2. El paso del borracho: \n# pos <- pos + rnorm(1), modifica la posición en base a la anterior. Nótese \n# que pos se sobreescribe en este comando.\n# 3. Almacenamiento de la nueva posición dentro de x: \n# x <- c(x, pos), aquí estamos \"agrandando x\", de a un valor cada turno. Sin \n# embargo en verdad estamos cambiando x por un x nuevo, pero eso es un detalle \n# sin importancia.\n\n# Podemos visualizar la caminata con el siguiente comando:\nplot(x, xlab = \"Nro. de iteración\", ylab = \"Posición del borracho\", \n type = \"o\", pch = 20)\n\n# Veamos varios ejemplos ...\n\n# ========= caminata.R: inicio ========\n# Preparación:\npos <- 0\nx <- pos\n# Loop:\nwhile (abs(pos) <= 10) {\n pos <- pos + rnorm(1)\n x <- c(x, pos)\n}\nplot(x, xlab = \"Nro. de iteración\", \n ylab = \"Posición del borracho\", \n type = \"o\", pch = 20)\n# ========= caminata.R: fin ===========\n\n# Si guardamos estos comandos en un script llamado \"caminata.R\", podemos hacer \n# varios intentos y ver como varían las caminatas, tanto en recorrido como en \n# duración:\n\nx11() # En una ventana nueva: conviene maximizarla\nop <- par(mfcol = c(3, 2), oma = c(0, 0, 3, 0))\nfor (i in 1:6)\n source(\"caminata.R\", encoding = \"UTF-8\") # Sólo funciona si \nmtext(\"Seis ejemplos en uno\", outer = TRUE, cex = 2)\npar(op)\n\n# Nota: el código que usamos aquí para la caminata no es la opción más \n# eficiente. Al final de esta lección se muestran otras opciones más adecuadas \n# para modelar este sistema.\n\n## RESUMEN\n# - La diferencia fundamental entre while y for es que en el primero no es \n# necesario definir de antemano el número de iteracciones, dependiendo de una \n# condición (una operación lógica) para ejecutar los comandos internos del \n# loop (hasta que de FALSE).\n# - Al igual que con for, es muy importante la preparación.\n# - También es *fundamental* tener cuidado de no crear un loop infinito, usando \n# una condición coerente con las variables que están en juego.\n \n\n## Caminata del borracho: opciones más eficientes (de menos a más)\n\n# 1. Definir x de antemano:\npos <- 0\nx <- numeric(1e4)\ni <- 1\nwhile (abs(pos) <= 10) {\n pos <- pos + rnorm(1)\n x[i] <- pos\n i <- i + 1\n}\nx <- x[1:(i - 1)]\n# Debido a que el estar cambiando de tamaño del x es un proceso muy ineficiente \n# del punto de vista computacional, es mejor crear un x al que le sobren \n# elementos (aquí se estima que diez mil es más que suficiente) para luego \n# eliminar las posiciones que sobren. Nótese que esto requiere definir la \n# variable i en la preparación, la cual debe ser actualizada en cada turno.\n\n# 2. Definir los valores aleatorios de antemano:\npos <- 0\nx <- numeric(1e4)\nr <- rnorm(1e4)\ni <- 1\nwhile (abs(pos) <= 10) {\n pos <- pos + r[i]\n x[i] <- pos\n i <- i + 1\n}\nx <- x[1:(i - 1)]\n# La creación de números aleatorios es un proceso que puede ser lento si se \n# hace de a uno por iteración. Es mejor siempre crear los valores aleatorios \n# (el vector r) en la preparación. De esta forma alcanza con sumar el iésimo \n# valor a pos en cada turno.\n# Nuevamente, esta estrategia requiere que se hagan una cantidad sobrada de \n# números aleatorios antes de empezar el loop.\n\n# 3. Eliminar el loop\nr <- rnorm(1e4)\nx <- cumsum(r)\na <- which(abs(x) > 10)\nx <- x[1:a[1]]\n# Aquí recurrimos a la función cumsum, que sirve para vectorizar el cálculo \n# (cumsum hace la suma acumulativa de r: x[1] == r[1], x[2] == r[1] + r[2], \n# ... , x[n] == sum(r[1:n]). Luego con which identificamos todas las posiciones \n# de x en las que el borracho se pasó de los límites y luego recortamos x, \n# seleccionando la secuencia desde el x[1] hasta el primer x quese va de los \n# límites.\n\n", "meta": {"hexsha": "1b38781faa72e3a3d06608089a09c817d79227e1", "size": 7947, "ext": "r", "lang": "R", "max_stars_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/6.3-loop-while.r", "max_stars_repo_name": "jcombari/Data-products-Course-Project", "max_stars_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/6.3-loop-while.r", "max_issues_repo_name": "jcombari/Data-products-Course-Project", "max_issues_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/6.3-loop-while.r", "max_forks_repo_name": "jcombari/Data-products-Course-Project", "max_forks_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.023923445, "max_line_length": 80, "alphanum_fraction": 0.7149867875, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.6651486709358111}} {"text": "\\name{generate_ER}\n\\alias{generate_ER}\n%- Also NEED an '\\alias' for EACH other topic documented here.\n\\title{\n Simulating networks from the Erdos-Renyi model}\n\\description{\n This function generates networks from the \\enc{Erdős–Rényi}{Erdos-Renyi} model. In this model, the preferential attachment function is a constant function, i.e. \\eqn{A_k = 1}, and node fitnesses are all equal to \\eqn{1}. It is a wrapper of the more powerful function \\code{\\link{generate_net}}.\n}\n\\usage{\n generate_ER(N = 1000, \n num_seed = 2 , \n multiple_node = 1 , \n m = 1)\n}\n\n%- maybe also 'usage' for other objects documented here.\n\\arguments{\n\\item{N}{\n Integer. Total number of nodes in the network (including the nodes in the seed graph). Default value is \\code{1000}.\n }\n\\item{num_seed}{\n Integer. The number of nodes of the seed graph (the initial state of the network). The seed graph is a cycle. Default value is \\code{2}.\n}\n\\item{multiple_node}{\n Positive integer. The number of new nodes at each time-step. Default value is \\code{1}.\n}\n\\item{m}{\n Positive integer. The number of edges of each new node. Default value is \\code{1}.\n}\n}\n\n\\value{\n The output is a \\code{PAFit_net} object, which is a List contains the following four fields:\n \\item{graph}{a three-column matrix, where each row contains information of one edge, in the form of \\code{(from_id, to_id, time_stamp)}. \\code{from_id} is the id of the source, \\code{to_id} is the id of the destination.}\n \\item{type}{a string indicates whether the network is \\code{\"directed\"} or \\code{\"undirected\"}.}\n \\item{PA}{a numeric vector contains the true PA function.}\n \\item{fitness}{fitness values of nodes in the network. The fitnesses are all equal to \\eqn{1}.}\n}\n\\author{\n Thong Pham \\email{thongpham@thongpham.net}\n}\n\\references{\n 1. \\enc{Erdös}{Erdos} P. & \\enc{Rényi}{Renyi} A.. On random graphs. Publicationes Mathematicae Debrecen. 1959;6:290–297 (\\url{http://snap.stanford.edu/class/cs224w-readings/erdos59random.pdf}).\n}\n\\seealso{\nFor subsequent estimation procedures, see \\code{\\link{get_statistics}}.\n\nFor other functions to generate networks, see \\code{\\link{generate_net}}, \\code{\\link{generate_BA}}, \\code{\\link{generate_BB}} and \\code{\\link{generate_fit_only}}. }\n\n\\examples{\n library(\"PAFit\")\n # generate a network from the ER model with N = 1000 nodes\n net <- generate_ER(N = 1000)\n str(net)\n plot(net)\n}\n\n% Add one or more standard keywords, see file 'KEYWORDS' in the\n% R documentation directory.\n\\concept{ER model}\n", "meta": {"hexsha": "e46dbc9188f8c5f90e823095d52c90b67aede58c", "size": 2573, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/generate_ER.rd", "max_stars_repo_name": "eddelbuettel/PAFit", "max_stars_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "man/generate_ER.rd", "max_issues_repo_name": "eddelbuettel/PAFit", "max_issues_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "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": "man/generate_ER.rd", "max_forks_repo_name": "eddelbuettel/PAFit", "max_forks_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1803278689, "max_line_length": 296, "alphanum_fraction": 0.7054022542, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6645795698360398}} {"text": "\nlm_curve = function(lr,Ms,p,ly,prod,rmin){\n r = 1/lr*(Ms/p - ly*prod)\n r[r < rmin] = rmin\n return(r)\n}\n\nRMPlot <- function(input,output,values){\n masse = seq(0,input$Mmax,length.out = 100)\n prod = seq(0,input$ymax,length.out = 100)\n to_plot = data.frame(money = masse, revenu = prod)\n fig = plot_ly(to_plot, x = ~money)\n \n fig = fig %>% add_segments(x = input$Ms, y = 0, xend = input$Ms, yend = 15, type = \"scatter\", mode = \"lines\", name = \"$$M = M^s$$\", color = I(\"blue\"),\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"\"))\n fig = fig %>% add_trace(y = lm_curve(input$lr, masse,values$p,input$ly,values$eq$y, input$rmin), type = \"scatter\", mode = \"lines\", name = \"$$M^d$$\", color = I(\"red\"),\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_segments(x = 0, y = values$eq$r, xend = input$Mmax, yend = values$eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n \n if(values$shock & !is.na(input$new_value_LM)){\n if(input$shocked_var_LM == \"Ms\"){\n fig = fig %>% add_segments(x = values$shocked_params_LM[\"Ms\"], y = 0, xend = values$shocked_params_LM[\"Ms\"], yend = 15, type = \"scatter\", mode = \"lines\", name = \"$$M = M^s$$\", color = \"rgb(0,20,200)\",\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"\"))\n fig = fig %>% add_segments(x = 0, y = values$new_eq$r, xend = input$Mmax, yend = values$new_eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n } else if(input$shocked_var_LM != \"Ms\"){\n fig = fig %>% add_trace(y = lm_curve(values$shocked_params_LM[\"lr\"],masse,values$shocked_params_LM[\"p\"]/100,values$shocked_params_LM[\"ly\"],values$shocked_params_LM[\"ystar\"],input$rmin), type = \"scatter\", mode = \"lines\", name = \"$$M^d$$\", color = \"rgb(0,200,20)\",\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_segments(x = 0, y = values$new_eq$r, xend = input$Mmax, yend = values$new_eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"Ms=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n }\n new_eq = list(\n x = unname(values$shocked_params_LM[\"Ms\"]),\n y = values$new_eq$r,\n text = paste0(\"r*=\",round(values$new_eq$r,1))\n )\n fig = fig %>% layout(annotations = new_eq)\n } else{\n eq = list(\n x = input$Ms,\n y = values$eq$r,\n text = paste0(\"r*=\",round(values$eq$r,1))\n )\n fig = fig %>% layout(annotations = eq)\n }\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n money <- list(\n title = \"Masse monétaire réelle, M/p\",\n titlefont = f\n )\n interest <- list(\n title = \"Taux d'intérêt, r\",\n titlefont = f\n )\n fig = fig %>% layout(xaxis = money, yaxis = interest)\n}\n\nLMPlot <- function(input,output,values){\n masse = seq(0,input$Mmax,length.out = 100)\n prod = seq(0,input$ymax,length.out = 100)\n to_plot = data.frame(money = masse, revenu = prod)\n \n fig = plot_ly(to_plot, x = ~revenu)\n fig = fig %>% add_trace(y = lm_curve(input$lr, input$Ms, values$p, input$ly, prod, input$rmin), type = \"scatter\", mode = \"lines\", name = \"$$LM_1$$\", color = I(\"red\"),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_segments(0,values$eq$r,values$eq$y,values$eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_segments(values$eq$y,0,values$eq$y,values$eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n \n if(values$shock & !is.na(input$new_value_LM)){ \n if(input$shocked_var_LM != \"ystar\"){\n fig = fig %>% add_trace(y = lm_curve(values$shocked_params_LM[\"lr\"],values$shocked_params_LM[\"Ms\"],values$shocked_params_LM[\"p\"],values$shocked_params_LM[\"ly\"],prod,input$rmin), type = \"scatter\", mode = \"lines\", name = \"$$LM_2$$\", color = \"rgb(0,200,20)\",\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n }\n fig = fig %>% add_segments(0,values$new_eq$r,values$shocked_params_LM[\"ystar\"],values$new_eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_segments(values$shocked_params_LM[\"ystar\"],0,values$shocked_params_LM[\"ystar\"],values$new_eq$r, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n lm_eq = list(\n x = unname(values$shocked_params_LM[\"ystar\"]),\n y = values$new_eq$r,\n text = paste0(\"r*=\",round(values$new_eq$r,1))\n )\n fig = fig %>% layout(annotations = lm_eq)\n } else{\n is_eq = list(\n x = values$eq$y,\n y = values$eq$r,\n text = paste0(\"r*=\",round(values$eq$r,1))\n )\n fig = fig %>% layout(annotations = is_eq)\n }\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n revenu <- list(\n title = \"Revenu, y\",\n titlefont = f\n )\n interest <- list(\n title = \"Taux d'intérêt, r\",\n titlefont = f\n )\n fig = fig %>% layout(xaxis = revenu, yaxis = interest)\n}", "meta": {"hexsha": "8bc9a5e12086a3d84534a08bf40b9955908d7da1", "size": 6065, "ext": "r", "lang": "R", "max_stars_repo_path": "src/LM_functions.r", "max_stars_repo_name": "placardo/macro_monetaire", "max_stars_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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/LM_functions.r", "max_issues_repo_name": "placardo/macro_monetaire", "max_issues_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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/LM_functions.r", "max_forks_repo_name": "placardo/macro_monetaire", "max_forks_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "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.7391304348, "max_line_length": 270, "alphanum_fraction": 0.5391591096, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6644039765438793}} {"text": "#' Title Partial Least Square Regression\r\n#'\r\n#' @param x matrix\r\n#' @param y vector\r\n#'\r\n#' @return just loadings\r\n#' @import stats\r\n#' @export\r\n#'\r\n\r\nPLSR1 <- function(x,y){\r\n # 用5折交叉验证的方法确定偏最小二乘回归主成分的个数\r\n # 然后用全体x、y求解对应的w*\r\n # PLSR1\r\n x <- scale(x)\r\n y <- scale(y)\r\n pis <- round(length(y)/5)\r\n a <- vector(length = 6)\r\n a[1] <- 1\r\n for (i in 1:5){\r\n a[i+1] <- i*pis\r\n }\r\n a[6] <- length(y)\r\n k <- length(x[1,])\r\n rmse <- vector(length = k)\r\n rmse[is.na(rmse)] <- 0\r\n for (i in 1:5){\r\n xx <- x[-c((a[i]):(a[i+1]-1)),]\r\n xtest <- x[c((a[i]):(a[i+1]-1)),]\r\n yy <- y[-c((a[i]):(a[i+1]-1))]\r\n ytest <- y[c((a[i]):(a[i+1]-1))]\r\n ypre <- vector(length = length(ytest))\r\n ypre[is.na(ypre)] <- 0\r\n w <- matrix(nrow = k,ncol = k)\r\n r <- vector(length = k)\r\n p <- matrix(nrow = k,ncol = k)\r\n for (j in 1:k){\r\n xp <- xx\r\n yp <- yy\r\n mat <- t(xp)%*%yp%*%t(yp)%*%xp\r\n en <- eigen(mat)\r\n w[,j] <- as.numeric(en$vec[,1])\r\n t <- xp%*%w[,j]\r\n p[,j] <- (t(xp)%*%t)/sum(t^2)\r\n r[j] <- t(yp)%*%t/sum(t^2)\r\n xx <- xp-t%*%t(p[,j])\r\n yy <- yp-t*(r[j])\r\n }\r\n for (e in 1:k){\r\n if (e==1){\r\n y_hat <- xtest%*%(w[,c(1:1)]*r[1])\r\n rmse[e] <- rmse[e] + mean(abs((ytest-y_hat)/ytest))\r\n }\r\n if (e>1){\r\n y_hat <- xtest%*%(w[,c(1:e)]%*%(r[c(1:e)]))\r\n rmse[e] <- rmse[e] + mean(abs((ytest-y_hat)/ytest))\r\n }\r\n }\r\n }\r\n rmse <- rmse/5\r\n or <- which.min(rmse)\r\n ww <- matrix(nrow = k,ncol = or)\r\n pp <- matrix(nrow = k,ncol = or)\r\n rr <- vector(length = or)\r\n for (d in 1:or){\r\n mat <- t(x)%*%y%*%t(y)%*%x\r\n en <- eigen(mat)\r\n ww[,d] <- as.numeric(en$vec[,1])\r\n t <- x%*%ww[,d]\r\n pp[,d] <- (t(x)%*%t)/sum(t^2)\r\n rr[d] <- t(y)%*%t/sum(t^2)\r\n x <- x-t%*%t(pp[,d])\r\n y <- y-t*(rr[d])\r\n }\r\n loadings <- ww%*%solve(t(pp)%*%ww)\r\n return(list(rmse,loadings))\r\n}\r\n", "meta": {"hexsha": "d06c63e0cf37f5b852f80497e802cd3f9e8ffab7", "size": 1912, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PLSR1.r", "max_stars_repo_name": "kkkkkkkh/khlearn", "max_stars_repo_head_hexsha": "b33c47c0de4d0da072dfb50862df441312e2e9a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-02T01:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T09:05:03.000Z", "max_issues_repo_path": "R/PLSR1.r", "max_issues_repo_name": "kkkkkkkh/khlearn", "max_issues_repo_head_hexsha": "b33c47c0de4d0da072dfb50862df441312e2e9a9", "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/PLSR1.r", "max_forks_repo_name": "kkkkkkkh/khlearn", "max_forks_repo_head_hexsha": "b33c47c0de4d0da072dfb50862df441312e2e9a9", "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": 24.5128205128, "max_line_length": 60, "alphanum_fraction": 0.4283472803, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6638789715125286}} {"text": "# Function to detect uncertainty in local peaks in a GAM and return the number and location of them after sampling from parameter uncertainty\n# Arguments:\n#\tmod: the GAM model (produced by mgcv)\n#\tnewdat: a data.frame of the new data on which to predict\n#\txvar: the name of the variable over which peaks should be detected\n#\txtol: the sliding window within which peaks are detected. Only one peak found per window. Width measured in # data points.\n#\tfindmaxima: TRUE if goal is to find peaks. FALSE if goal is to find valleys.\n# Returns a data.frame with \n\nfindPeaksGAM_CI <- function(mod, newdat, n, xvar, xtol, findmaxima=TRUE){\n\tlibrary(mgcv)\n\tXp <- predict(mod,newdat,type=\"lpmatrix\") # prediction decomposed into the linear predictors\n\tbr <- rmvn(n,coef(mod),mod$Vp) ## n replicate parameter vectors sampled with uncertainty\n\tres <- matrix(NA, ncol=n, nrow=nrow(newdat)) # to hold the predictions\n\tfor(i in 1:n) res[,i] <- Xp %*% br[i,] ## replicate predictions\n\n#\tord <- order(newdat[[xvar]]) # find order by xvar\n#\tyord <- newdat[[xvar]][ord] # order explanatory variable (xvar)\n#\tresord <- res[ord,] # order rows or res by xvar\n\tpeaks <- data.frame(npeaks=rep(NA, n), peaklocs=I(vector('list', n)), y=I(vector('list', n))) # hold the number and location of peaks\n\tfor(i in 1:n){\n\t\ttemp <- find_peaks(res[,i], m=xtol, findmaxima)\n\t\tpeaks$npeaks[i] <- length(temp)\n\t\tpeaks$peaklocs[[i]] <- newdat[[xvar]][temp]\n\t\tpeaks$y[[i]] <- res[,i]\n\t}\n\treturn(peaks)\n}\n\n# Same function, but from the mean prediction (no uncertainty)\nfindPeaksGAM <- function(mod, newdat, xvar, xtol, findmaxima=TRUE){\n\tlibrary(mgcv)\n\tres <- predict(mod,newdat) # prediction\n\n\tpeaks <- data.frame(npeaks=rep(NA, 1), peaklocs=I(vector('list', 1)), y=I(vector('list', 1))) # hold the number and location of peaks\n\ttemp <- find_peaks(res, m=xtol, findmaxima)\n\tpeaks$npeaks <- length(temp)\n\tpeaks$peaklocs[[1]] <- newdat[[xvar]][temp]\n\tpeaks$y[[1]] <- res\n\t\n\treturn(peaks)\n}\n\n## produce multivariate normal random deviates needed by findPeaksGAM\nrmvn <- function(n,mu,sig) { \n\tL <- mroot(sig)\n\tm <- ncol(L)\n\tt(mu + L%*%matrix(rnorm(m*n),m,n)) \n}\n\n# find peaks in a vector\n# from https://stats.stackexchange.com/questions/22974/how-to-find-local-peaks-valleys-in-a-series-of-data\nfind_peaks <- function (x, m = 3, findmaxima=TRUE){\n\tshape <- diff(sign(diff(x, na.pad = FALSE)))\n\tif(findmaxima){\n\t\tpks <- sapply(which(shape < 0), FUN = function(i){\n\t\t\tz <- i - m + 1\n\t\t\tz <- ifelse(z > 0, z, 1)\n\t\t\tw <- i + m + 1\n\t\t\tw <- ifelse(w < length(x), w, length(x))\n\t\t\tif(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0))\n\t\t})\n\t}\n\tif(!findmaxima){\n\t\tpks <- sapply(which(shape > 0), FUN = function(i){\n\t\t\tz <- i - m + 1\n\t\t\tz <- ifelse(z > 0, z, 1)\n\t\t\tw <- i + m + 1\n\t\t\tw <- ifelse(w < length(x), w, length(x))\n\t\t\tif(all(x[c(z : i, (i + 2) : w)] >= x[i + 1])) return(i + 1) else return(numeric(0))\n\t\t})\n\t}\n\tpks <- unlist(pks)\n\treturn(pks)\n}\n\n\n# Example using findPeaksGAM\n#library(mgcv)\n#n <- 200\n#sig <- 2\n#dat <- gamSim(1,n=n,scale=sig) # an example dataset\n#mod<-gam(y~s(x0)+s(I(x1^2))+s(x2)+offset(x3),data=dat) # fit a gam\n#newdat <- data.frame(x0=(0:60)/60,x1=(0:60)/60,x2=(0:60)/60,x3=(0:60)/60) # new data for projection\n#\n#peaks <- findPeaksGAM(mod, newdat, 500, 'x0', 5)\n#\n#hist(peaks$npeaks) # almost all find 2 peaks\n#\n#\n#plot(newdat$x0, predict(mod, newdat), type='l', ylim=range(res)) # plot the basic prediction\n#for(i in 1:nrow(peaks)) lines(newdat$x0, peaks$y[[i]], col=rgb(0,0,0,0.05), lty=1) # plot the uncertainty\n#\n#\n#plot(newdat$x0, predict(mod, newdat), type='l', ylim=range(res)) # plot the basic prediction\n#inds <- which(peaks$npeaks == 1)\n#for(i in 1:length(inds)) lines(newdat$x0, peaks$y[[inds[i]]], col=rgb(1,0,0,0.5), lty=1) # plot the lines with 1 peak\n#inds <- which(peaks$npeaks == 3)\n#for(i in 1:length(inds)) lines(newdat$x0, peaks$y[[inds[i]]], col=rgb(0,1,0,0.5), lty=1) # plot the lines with 3 peaks\n\n", "meta": {"hexsha": "1629543fd776af8ca92d8d42abdab26d0f2cad6e", "size": 3930, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/findPeaksGAM.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/findPeaksGAM.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/findPeaksGAM.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "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.9108910891, "max_line_length": 141, "alphanum_fraction": 0.6534351145, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6637462468447801}} {"text": "#!/usr/bin/env Rscript\n\n## Item Response Theory (IRT) - Partial Credit Model (PCM)\n# Copyright 2021 Enrico Glerean\n#\n# 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 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# In this script we fit the PCM for polytomous data as implemented\n# by the R packages eRm\n# We report\n# 1. summary statistics for the fitted model\n# 2. Item Characteristic Curves (ICC) for each item\n# 3. Wright map\n# 4. Item fit summary statistics and item map\n# 5. Person fit summary statistics and person fit map\n# 6. test for the unidimensionality of the data\n# 7. test for local dependence of items\n\n\n# We use the eRm package\nlibrary(\"eRm\")\n\n\ndfA <- read.table(\"../results/scores/scores_sorted.csv\",header=TRUE, sep=',', colClasses = \"integer\")\ndfA <- dfA + 1 # We have values from 0 to 2 as required by eRM packages with polytomous data\n\n\n# 1. model fitting and summary statistics for the fitted model\nPC_model <- PCM(df)\nsummary(PC_model)\nth <- thresholds(PC_model)\nth\n\n\n# 2. Item Characteristic Curves (ICC) for each item\n# TODO: legends and title could be improved\nlab <- labels(df)[[2]]\nfor(n in lab){\n print(paste(\"Plotting item \",n))\n # figures are stored in ../results/figures/\n pdf(paste('../results/figures/',n,'-ICC.pdf',sep=\"\"))\n plotICC(PC_model,item.subset=n)\n dev.off()\n}\n\n# 3. Person-Item map (Wright map)\npdf('../results/figures/PImap.pdf')\nplotPImap(PC_model)\ndev.off()\npdf('../results/figures/PImap_C1.pdf')\nplotPImap(PC_model,item.subset = c(1,2,3,4,5,6,7,8,9,10,11,12))\ndev.off()\npdf('../results/figures/PImap_C2.pdf')\nplotPImap(PC_model,item.subset = c(13,14,15,16,17,18,19,20,21,22))\ndev.off()\npdf('../results/figures/PImap_C3.pdf')\nplotPImap(PC_model,item.subset = c(23,24,25,26,27,28,29,30,31,32,33,34))\ndev.off()\npdf('../results/figures/PImap_C4.pdf')\nplotPImap(PC_model,item.subset = c(35,36,37,38,39,40))\ndev.off()\n\n# 4. Item fit summary statistics and item fit map\npres <- person.parameter(PC_model)\nitfi <- itemfit(pres)\nitfi\npdf('../results/figures/PW_itemMap.pdf')\nplotPWmap(PC_model)\ndev.off()\n\n# 5. Person fit summary statistics and person fit map\npefi <- personfit(pres)\npdf('../results/figures/PW_personsMap.pdf')\nplotPWmap(PC_model,pmap=TRUE, imap=FALSE)\ndev.off()\n\n\n# 6. test for the unidimensionality of the data\nutest <- MLoef(PC_model)\nutest\n\n# 7. test for local dependence of items\nres <- residuals(pres)\nQ3 <- cor(res,method=\"pearson\")\ndiag(Q3)<-NA\nQ3star=Q3 - mean(Q3, na.rm = TRUE)\nii = which(abs(Q3star) > 0.2)\nm = 40\nfor(ind in ii){\n rid = ((ind-1) %% m) + 1\n cid = floor((ind-1) / m) + 1\n print(paste(labels(df)[[2]][rid],labels(df)[[2]][cid],Q3star[rid,cid],sep=\" \"))\n}\n\n", "meta": {"hexsha": "2aebacceedbe11bfffcf71fca1af1e8784976ea6", "size": 3093, "ext": "r", "lang": "R", "max_stars_repo_path": "r02_IRT_PCM.r", "max_stars_repo_name": "eglerean/sulo", "max_stars_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "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": "r02_IRT_PCM.r", "max_issues_repo_name": "eglerean/sulo", "max_issues_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "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": "r02_IRT_PCM.r", "max_forks_repo_name": "eglerean/sulo", "max_forks_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "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": 29.7403846154, "max_line_length": 101, "alphanum_fraction": 0.712900097, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6635968556601924}} {"text": "require(Hmisc)\nif(FALSE) .Fortran('jrank', as.double(1:5), as.double(1:5), 5L,\n double(5), double(5), double(5))\nhoeffd(1:6, c(1,3,2,4,5,6))\ny <- 1:20; y[3] <- 17; y[17] <- 3\nhoeffd(1:20, y)$D\nset.seed(5)\nx <- runif(800); y <- runif(800)\nhoeffd(x,y)$D\n\nfor(n in c(50,100,200,400,1000)) {\n set.seed(1)\n x <- seq(-10,10,length=n)\n y <- x*sign(runif(n,-1,1))\n h <- hoeffd(x,y)\n print(c(h$D[1,2], h$aad[1,2], h$maxad[1,2]))\n}\n#[1] 0.06812286 in old version (real*4 in places)\n#[1] 0.04667929\n#[1] 0.05657654\n#[1] 0.07048487\n#[1] 0.06323746\n\n\n# From http://www.sciencemag.org/content/suppl/2011/12/14/334.6062.1518.DC1/Reshef.SOM.pdf\n# Table S2: Definitions of functions used for Figure 2A in the Science article\n\nw <- function(y) {\n ylab <- deparse(substitute(y))\n plot(x, y, ylab=substitute(y), type='l')\n h <- hoeffd(x, y)\n cat(ylab, '\\n')\n print(c(D=h$D[1,2],P=h$P[1,2],aDif=h$aad[1,2],mDif=h$maxad[1,2]))\n}\n\nx <- seq(0, 1, length=320)\npar(mfrow=c(3,3))\nw(x)\nw(4*(x-.5)^2)\nw(128*(x-1/3)^3 -48*(x-1/3)^2 - 12*(x-1/3) + 2)\nw(10^(10*x) - 1)\nw(sin(10*pi*x) + x)\nw(sin(16*pi*x))\nw(sin(13*pi*x))\nw(sin(7*pi*x*(1+x)))\nw(runif(320))\n", "meta": {"hexsha": "41db86d5494424a7d42c4c5f8f7301c66dc26c5d", "size": 1154, "ext": "r", "lang": "R", "max_stars_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/hoeff.r", "max_stars_repo_name": "klodzikowski/phongames", "max_stars_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/hoeff.r", "max_issues_repo_name": "klodzikowski/phongames", "max_issues_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/hoeff.r", "max_forks_repo_name": "klodzikowski/phongames", "max_forks_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 24.5531914894, "max_line_length": 90, "alphanum_fraction": 0.5779896014, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6635258844843163}} {"text": "Mean=c(2.2, 4.6 ,21.2 ,31.4)\r\nStandard_deviation=c(1.476,2.119,4.733,5.52)\r\ns_min=min(Standard_deviation)\r\ns_max=max(Standard_deviation)\r\n# test statistic\r\nF=s_max^2/s_min^2\r\nprint(F)\r\n# The critical value of F > F.alpha\r\n# we reject the hypothesis of homogeneity\r\n#of the population variances. \r\n\r\ndistance_1km=c(1,5,2,1,2,2,4,3,0,2)\r\ndistance_5km=c(4,8,2,3,8,5,6,4,3,3)\r\ndistance_10km=c(20,26,24,11,28,20,19,19,21,24)\r\ndistance_20km=c(37,30,26,24,41,25,36,31,31,33)\r\nprint(Standard_deviation[1]^2/Mean[1])\r\nprint(Standard_deviation[2]^2/Mean[2])\r\nprint(Standard_deviation[3]^2/Mean[3])\r\nprint(Standard_deviation[4]^2/Mean[4])\r\ni=1\r\nwhile(i<11){\r\n distance_1km[i]=sqrt(distance_1km[i]+0.375)\r\n i=i+1\r\n}\r\ni=1\r\nwhile(i<11){\r\n distance_5km[i]=sqrt(distance_5km[i]+0.375)\r\n i=i+1\r\n}\r\ni=1\r\nwhile(i<11){\r\n distance_10km[i]=sqrt(distance_10km[i]+0.375)\r\n i=i+1\r\n}\r\ni=1\r\nwhile(i<11){\r\n distance_20km[i]=sqrt(distance_20km[i]+0.375)\r\n i=i+1\r\n}\r\ncombined_group=data.frame(cbind(distance_1km,distance_5km,distance_10km,distance_20km))\r\ncombined_group\r\n \r\n ", "meta": {"hexsha": "472b751f4693e9e4f9017e07fc301849ccbb24e9", "size": 1055, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.4/Ex8_4.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.4/Ex8_4.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH8/EX8.4/Ex8_4.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.5348837209, "max_line_length": 88, "alphanum_fraction": 0.6957345972, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6635258761590318}} {"text": "library(\"MASS\")\ndata(\"OME\")\n\ndat = subset(OME, OME != \"N/A\")\ndat$OME = factor(dat$OME) # relabel OME\ndat$ID = as.numeric(factor(dat$ID)) # relabel ID so there are no gaps in numbers (they now go from 1 to 63)\n\n## Original reference model and covariate matrix\nmod_glm = glm(Correct/Trials ~ Age + OME + Loud + Noise, data=dat, weights=Trials, family=\"binomial\")\nX = model.matrix(mod_glm)[,-1]\n\n## Original model (that needs to be extended)\nmod_string = \" model {\n\tfor (i in 1:length(y)) {\n\t\ty[i] ~ dbin(phi[i], n[i])\n\t\tlogit(phi[i]) = a[ID[i]] + b[1]*Age[i] + b[2]*OMElow[i] + b[3]*Loud[i] + b[4]*Noiseincoherent[i]\n\t}\n\t\n for (k in 1:max(ID)){\n a[k] ~ dnorm(a0, tau_prec)\n }\n\n\ta0 ~ dnorm(0.0, 1.0/10.0^2)\n tau_prec ~ dgamma(1.0/2.0, 1.0/2.0)\n tau = 1.0/tau_prec\n\n\tfor (j in 1:4) {\n\t\tb[j] ~ dnorm(0.0, 1.0/4.0^2)\n\t}\n \n} \"\n\ndata_jags = as.list(as.data.frame(X))\ndata_jags$y = dat$Correct\ndata_jags$n = dat$Trials\ndata_jags$ID = dat$ID\n\nlibrary(\"rjags\")\n\nset.seed(113)\n\n\nparams = c(\"a0\", \"tau\", \"a\", \"b\")\n\nmod = jags.model(textConnection(mod_string), data=data_jags, n.chains=3)\nupdate(mod, 1e3)\n\nmod_sim = coda.samples(model=mod,\n variable.names=params,\n n.iter=5e3)\nmod_csim = as.mcmc(do.call(rbind, mod_sim))\n\n## convergence diagnostics\nplot(mod_sim)\n\ngelman.diag(mod_sim)\nautocorr.diag(mod_sim)\nautocorr.plot(mod_sim)\neffectiveSize(mod_sim)\n\n## compute DIC\ndic = dic.samples(mod, n.iter=1e3)\n", "meta": {"hexsha": "fc1657ebf67fee967a4f8144331be692dd16a9bd", "size": 1457, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/hieratchicalLinearRegression.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/hieratchicalLinearRegression.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/hieratchicalLinearRegression.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": 23.126984127, "max_line_length": 107, "alphanum_fraction": 0.6280027454, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6631845129660063}} {"text": "## The function to calculate the likelihood values.\n\nCalculation<-function(Simulation,Measurement,Variance)\n{\nConstant=10000;\n#A constant to amplify the likelihood values in case of beyond computer precision becasue the vasues may be very small.\n\nLikelihood<-Constant*(1/sqrt(2*pi*Variance))*exp(-(Measurement-Simulation)^2/(2*Variance));\n# The likelihood function derived from the normal distribution.\n\nreturn(Likelihood);\n\n}", "meta": {"hexsha": "8eee0ed1ff5e6d5c80a38f78a051a958b6ef18e7", "size": 426, "ext": "r", "lang": "R", "max_stars_repo_path": "DSSAT46/Tools/GLUE/Calculation.r", "max_stars_repo_name": "nocdoggo/Nitrogen-Tracking-and-Harvest-Simulation", "max_stars_repo_head_hexsha": "4d154790d14ba5d1f14dff0923275f663f3ee5a2", "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": "DSSAT46/Tools/GLUE/Calculation.r", "max_issues_repo_name": "nocdoggo/Nitrogen-Tracking-and-Harvest-Simulation", "max_issues_repo_head_hexsha": "4d154790d14ba5d1f14dff0923275f663f3ee5a2", "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": "DSSAT46/Tools/GLUE/Calculation.r", "max_forks_repo_name": "nocdoggo/Nitrogen-Tracking-and-Harvest-Simulation", "max_forks_repo_head_hexsha": "4d154790d14ba5d1f14dff0923275f663f3ee5a2", "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.7692307692, "max_line_length": 119, "alphanum_fraction": 0.7910798122, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.948154530420204, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6630012531856436}} {"text": "\n\n#' @title f-test\n#' @description f-test\n#' @param sd1 First standard deviation\n#' @param sd2 Second standard deviation\n#' @param df1 First degrees of freedom\n#' @param df2 Second degrees of freedom\n#' @param prob Probability\n#' @return Test decision\n#' @rdname f_test\nf_test <- function(sd1, sd2, df1, df2, prob){\n if(sd1 > sd2){\n F.estimated <- sd1^2/sd2^2\n F.quantile <- qf(p = prob, df1 = df1, df2 = df2)\n }else{\n F.estimated <- sd2^2/sd1^2\n F.quantile <- qf(p = prob, df1 = df1, df2 = df2)\n }\n if(F.estimated < F.quantile){\n note <- TRUE\n }else{\n note <- FALSE\n }\n return(list(f_estimated = F.estimated, f_quantile = F.quantile, decision = note))\n}\n\n#' @title deform.snet\n#' @description Two-epochs deformation analysis based on congruency testing\n#' @param snet_1_path Path to the data of the first epoch of the measurements\n#' @param snet_2_path Path to the data of the second epoch of the measurements\n#' @param sd.apriori Apriori standard deviation\n#' @param units Units of the results, Default: 'mm'\n#' @param dim_type Dimension type of the network, Default: '1D'\n#' @param prob Probability for statistical testing, Default: 0.95\n#' @param wdh_model Weightening model for leveling measurements, Default: list(\"n_dh\", \"sd_dh\", \"d_dh\", \"E\")\n#' @return dataframe with two columns: \"Name\" indicating the name of the point and \"stable\" indicating the stability status of the point (TRUE or FALSE)\n#' @details DETAILS\n#' @examples \n#' \\dontrun{\n#' if(interactive()){\n#' #EXAMPLE1\n#' }\n#' }\n#' @seealso \n#' @rdname snet.stable\n#' @export \n#' @importFrom dplyr arrange select case_when\n#' @importFrom MASS ginv\ndeform.snet <- function(snet_1_path, snet_2_path, sd.apriori, units = \"mm\", dim_type = \"1D\", prob = 0.95, wdh_model = list(\"n_dh\", \"sd_dh\", \"d_dh\", \"E\")){\n \"%!in%\" <- Negate(\"%in%\")\n wdh_model <- wdh_model[[1]]\n units.lookup.table <- c(mm = 1000, cm = 100, m = 1)\n if(length(sd.apriori) == 1){\n sd0_i <- sd.apriori[1]\n sd0_j <- sd.apriori[1]\n }else{\n sd0_i <- sd.apriori[1]\n sd0_j <- sd.apriori[2]\n }\n #=================== Reading snets ===============================\n snet_i <- suppressWarnings(read_surveynet(file = snet_1_path))\n snet_j <- suppressWarnings(read_surveynet(file = snet_2_path))\n\n #=================== Checking snets ==============================\n if(!identical(snet_i$observations[, c(\"from\", \"to\")], snet_j$observations[, c(\"from\", \"to\")])){\n print(\"Observation plans are not identical in two epochs.\")\n }\n\n used_points_i <- unique(c(snet_i$observations$from, snet_i$observations$to))\n used_points_j <- unique(c(snet_j$observations$from, snet_j$observations$to))\n\n if(!!any(used_points_i %!in% snet_i[[1]]$Name)){\n stop(paste(\"There is no coordinates for point\", paste(used_points_i[which(used_points_i %!in% snet_i[[1]]$Name)], \"in reference epoch\"), sep = \" \"))\n }else{used_points_i <- snet_i[[1]]$Name\n }\n\n if(!!any(used_points_i %!in% snet_i[[1]]$Name)){\n stop(paste(\"There is no coordinates for point\", paste(used_points_j[which(used_points_j %!in% snet_j[[1]]$Name)]), \"in target epoch\", sep = \" \"))\n }else{used_points_j <- snet_j[[1]]$Name\n }\n\n\n if(!identical(used_points_i, used_points_i)){\n print(\"Two epochs contains different points.\")\n if(length(used_points_i) > length(used_points_j)){\n print(paste(\"Points\", used_points_i[which(used_points_i %!in% used_points_j)], \"do not exist in the target epoch\", sep = \" \"))\n used_points <- used_points_j\n }else{\n if(length(used_points_i) < length(used_points_j)){\n print(paste(\"Points\", used_points_j$Points$Name[which(used_points_j %!in% used_points_i)], \"do not exist in the reference epoch\", sep = \" \"))\n used_points <- used_points_i\n }\n print(\"Only the results for common points will be processed.\")\n }\n }else{\n used_points <- used_points_i\n }\n\n\n if(!identical(snet_i$Points$h, snet_j$Points$h)){\n stop(print(\"Approximate coordinates in two epoches must be the same\"))\n }\n\n if(!identical(snet_i$points$Name[snet_i$points$Point_object], snet_j$points$Name[snet_j$points$Point_object])){\n stop(print(\"Reference points must be the same\"))\n }\n snet_i[[1]] <- snet_i[[1]][match(snet_i[[1]]$Name, used_points), ] %>% dplyr::arrange(Point_object, desc = TRUE)\n snet_j[[1]] <- snet_j[[1]][match(snet_j[[1]]$Name, used_points), ] %>% dplyr::arrange(Point_object, desc = TRUE)\n #===========================================================================\n\n #=================== Adjustment ============================================\n snet_i_adj <- suppressMessages(adjust.snet(adjust = TRUE, survey.net = snet_i, dim_type = \"1D\", sd.apriori = sd0_i, all = TRUE, prob = prob, wdh_model = wdh_model))\n snet_j_adj <- suppressMessages(adjust.snet(adjust = TRUE, survey.net = snet_j, dim_type = \"1D\", sd.apriori = sd0_j, all = TRUE, prob = prob, wdh_model = wdh_model))\n if(any(c(snet_i_adj$Summary$`Test decision`, snet_j_adj$Summary$`Test decision`) != \"Model is correct\")) {\n return(list(snet_1_adj = snet_i_adj[1:3], snet_2_adj = snet_i_adj[1:3]))\n stop(\"One epoch adjustment failed\")\n }\n #============================================================================\n points_i <- snet_i_adj$Points\n points_j <- snet_j_adj$Points\n\n points_i$Stable <- NA\n points_j$Stable <- NA\n\n Qx_i <- snet_i_adj$Matrices$Qx\n Qx_j <- snet_j_adj$Matrices$Qx\n\n #=================== Calculating reference accuracy factor ==================\n s0_i <- snet_i_adj$Summary$`sigma aposteriori`\n s0_j <- snet_j_adj$Summary$`sigma aposteriori`\n f_i <- snet_i_adj$Summary$`Degrees of freedom`\n f_j <- snet_j_adj$Summary$`Degrees of freedom`\n\n if(f_test(sd1 = s0_i, sd2 = s0_j, df1 = f_i, df2 = f_j, prob = prob)[[3]]){\n s0 <- sqrt((f_i*s0_i^2+f_j*s0_j^2)/(f_i + f_j))\n f0 <- f_i + f_j\n }else{\n if(s0_i > s0_j){\n s0 <- s0_i\n f0 <- f_i\n print(\"Two epoches are not equally precised! Computation will be continued with the worse reference standard deviation.\")\n }else{\n s0 <- s0_j\n f0 <- f_j\n print(\"Two epoches are not equally precised! Computation will be continued with the worse reference standard deviation.\")\n }\n }\n #============================================================================\n\n #=================== Testing whole network ==================================\n\n d_all <- (points_j$h - points_i$h)*units.lookup.table[units]\n\n Qd_all <- Qx_i + Qx_j\n\n Qd_all_ginv <- MASS::ginv(Qd_all)\n\n dd_all <- (crossprod(d_all, Qd_all) %*% d_all)\n\n teta_all_squared <- ((crossprod(d_all, Qd_all_ginv) %*% d_all)/qr(Qd_all)$rank)\n\n snet_test <- f_test(sd1 = sqrt(teta_all_squared), sd2 = s0, df1 = qr(Qd_all)$rank, df2 = f0, prob = prob)\n\n if(sum(points_i$Point_object) == 0){\n fix <- \"all\"\n if(!snet_test[[3]]){\n r_points_ind <- !points_i$Point_object\n names(r_points_ind) <- points_i$Name\n iter <- 0\n m <- sum(r_points_ind)\n while(!snet_test[[3]] & m > 1) {\n iter = iter + 1\n r_ind_matrix <- diag(sum(r_points_ind)) == 1\n teta_r <- rep(NA, sum(r_points_ind))\n for(i in 1:sum(r_points_ind)){\n drb <- d_all[r_points_ind][r_ind_matrix[i, ]]\n drf <- d_all[r_points_ind][!r_ind_matrix[i, ]]\n\n Qdbb <- Qd_all_ginv[r_points_ind, r_points_ind][r_ind_matrix[i, ], r_ind_matrix[i, ]]\n Qdbf <- Qd_all_ginv[r_points_ind, r_points_ind][r_ind_matrix[i, ], !r_ind_matrix[i, ]]\n Qdfb <- Qd_all_ginv[r_points_ind, r_points_ind][!r_ind_matrix[i, ], r_ind_matrix[i, ]]\n Qdff <- Qd_all_ginv[r_points_ind, r_points_ind][!r_ind_matrix[i, ], !r_ind_matrix[i, ]]\n\n dsb <- drb + solve(Qdbb) %*% Qdbf %*% drf\n Qsff <- Qdff - Qdfb %*% solve(Qdbb) %*% Qdbf\n\n dd_b <- (crossprod(dsb, Qdbb) %*% dsb)\n teta_r[i] <- dd_b\n }\n names(teta_r) <- points_i$Name[r_points_ind]\n max_teta_name <- names(teta_r[which(teta_r==max(teta_r))])\n points_i[points_i$Name == max_teta_name, \"Stable\"] <- FALSE\n points_j[points_j$Name == max_teta_name, \"Stable\"] <- FALSE\n\n r_points_ind[which(points_i$Stable == FALSE)] <- FALSE\n names(r_points_ind) <- points_i$Name\n\n d_rest <- d_all[r_points_ind]\n\n Qd_rest_ginv <- Qd_all_ginv[r_points_ind, r_points_ind]\n\n dd_rest <- (crossprod(d_rest, Qd_rest_ginv) %*% d_rest)\n\n teta_rest_squared <- ((crossprod(d_rest, Qd_rest_ginv) %*% d_rest)/qr(Qd_rest_ginv)$rank)\n\n snet_test <- f_test(sd1 = sqrt(teta_rest_squared), sd2 = s0, df1 = qr(Qd_rest_ginv)$rank, df2 = f0, prob = prob)\n m <- sum(r_points_ind)\n }\n }\n }else{\n # ================== Testing for reference points ============================\n\n r_points_names <- snet_i_adj$Points$Name[!snet_i_adj$Points$Point_object]\n o_points_names <- snet_i_adj$Points$Name[snet_i_adj$Points$Point_object]\n\n r_points_ind <- !points_i$Point_object\n names(r_points_ind) <- points_i$Name\n\n dr <- d_all[r_points_ind]\n names(dr) <- points_i$Name[r_points_ind]\n do <- d_all[!r_points_ind]\n names(do) <- points_i$Name[!r_points_ind]\n\n Qdrr <- Qd_all_ginv[r_points_ind, r_points_ind]\n Qdro <- Qd_all_ginv[r_points_ind, !r_points_ind]\n Qdor <- Qd_all_ginv[!r_points_ind, r_points_ind]\n Qdoo <- Qd_all_ginv[!r_points_ind, !r_points_ind]\n\n dso <- do + solve(Qdoo) %*% Qdor %*% dr\n Qsrr <- Qdrr - Qdro %*% solve(Qdoo) %*% Qdor\n\n dd_r <- (crossprod(dr, Qsrr) %*% dr) # kvadratna forma\n\n teta_r_squared <- ((crossprod(dr, Qsrr) %*% dr)/qr(Qsrr)$rank)\n\n r_test <- f_test(sd1 = sqrt(teta_r_squared), sd2 = s0, df1 = qr(Qsrr)$rank, df2 = f0, prob = prob)\n\n if(!r_test[[3]]){\n iter <- 0\n m <- sum(r_points_ind)\n while(!r_test[[3]] & m > 1) {\n iter = iter + 1\n r_ind_matrix <- diag(sum(r_points_ind)) == 1\n teta_r <- rep(NA, sum(r_points_ind))\n for(i in 1:sum(r_points_ind)){\n drb <- d_all[r_points_ind][r_ind_matrix[i, ]]\n drf <- d_all[r_points_ind][!r_ind_matrix[i, ]]\n\n Qdbb <- Qdrr[r_ind_matrix[i, ], r_ind_matrix[i, ]]\n Qdbf <- Qdrr[r_ind_matrix[i, ], !r_ind_matrix[i, ]]\n Qdfb <- Qdrr[!r_ind_matrix[i, ], r_ind_matrix[i, ]]\n Qdff <- Qdrr[!r_ind_matrix[i, ], !r_ind_matrix[i, ]]\n\n dsb <- drb + solve(Qdbb) %*% Qdbf %*% drf\n Qsff <- Qdff - Qdfb %*% solve(Qdbb) %*% Qdbf\n\n dd_b <- (crossprod(dsb, Qdbb) %*% dsb)\n teta_r[i] <- dd_b\n }\n names(teta_r) <- points_i$Name[r_points_ind]\n max_teta_name <- names(teta_r[which(teta_r==max(teta_r))])\n points_i[points_i$Name == max_teta_name, \"Stable\"] <- FALSE\n points_j[points_j$Name == max_teta_name, \"Stable\"] <- FALSE\n\n r_points_ind <- is.na(!points_i$Point_object & points_i$Stable)\n names(r_points_ind) <- points_i$Name\n\n dr <- d_all[r_points_ind]\n names(dr) <- points_i$Name[r_points_ind]\n do <- d_all[!r_points_ind]\n names(do) <- points_i$Name[!r_points_ind]\n\n Qdrr <- Qd_all_ginv[r_points_ind, r_points_ind]\n Qdro <- Qd_all_ginv[r_points_ind, !r_points_ind]\n Qdor <- Qd_all_ginv[!r_points_ind, r_points_ind]\n Qdoo <- Qd_all_ginv[!r_points_ind, !r_points_ind]\n\n Qsrr <- Qdrr - Qdro %*% solve(Qdoo) %*% Qdor\n\n teta_r_squared <- ((crossprod(dr, Qsrr) %*% dr)/qr(Qsrr)$rank)\n\n r_test <- f_test(sd1 = sqrt(teta_r_squared), sd2 = s0, df1 = qr(Qsrr)$rank, df2 = f0, prob = prob)\n m <- sum(r_points_ind)\n }\n }\n #================== Testing for object points ==============================\n\n points_i$Stable[r_points_ind] <- TRUE\n points_i$Stable[!points_i$Stable] <- NA\n\n points_j$Stable[r_points_ind] <- TRUE\n points_j$Stable[!points_j$Stable] <- NA\n\n o_points_ind <- !r_points_ind\n names(o_points_ind) <- points_i$Name\n\n dso <- do + solve(Qdoo) %*% Qdor %*% dr\n teta_o_squared <- ((crossprod(dso, Qdoo) %*% dso)/qr(Qdoo)$rank)\n o_test <- f_test(sd1 = sqrt(teta_o_squared), sd2 = s0, df1 = qr(Qdoo)$rank, df2 = f0, prob = prob)\n\n if(!o_test[[3]]){\n iter <- 0\n m <- sum(o_points_ind)\n while(!o_test[[3]] & m > 1) {\n iter = iter + 1\n o_ind_matrix <- diag(sum(is.na(points_i$Stable))) == 1\n teta_o <- rep(NA, sum(is.na(points_i$Stable)))\n dobs <- rep(NA, sum(is.na(points_i$Stable)))\n Qdoo_o <- Qd_all_ginv[o_points_ind, o_points_ind]\n for(i in 1:sum(o_points_ind)){\n drb <- (points_j$h[is.na(points_i$Stable)][o_ind_matrix[i, ]] - points_i$h[is.na(points_i$Stable)][o_ind_matrix[i, ]])*units.lookup.table[units]\n drf <- (points_j$h[is.na(points_i$Stable)][!o_ind_matrix[i, ]] - points_i$h[is.na(points_i$Stable)][!o_ind_matrix[i, ]])*units.lookup.table[units]\n\n Qdbb <- Qdoo_o[o_ind_matrix[i, ], o_ind_matrix[i, ]]\n Qdbf <- Qdoo_o[o_ind_matrix[i, ], !o_ind_matrix[i, ]]\n Qdfb <- Qdoo_o[!o_ind_matrix[i, ], o_ind_matrix[i, ]]\n Qdff <- Qdoo_o[!o_ind_matrix[i, ], !o_ind_matrix[i, ]]\n\n dsb <- drb + solve(Qdbb) %*% Qdbf %*% drf\n Qsff <- Qdff - Qdfb %*% solve(Qdbb) %*% Qdbf\n\n dd_b <- (crossprod(dsb, Qdbb) %*% dsb)\n teta_o[i] <- dd_b\n dobs[i] <- drb\n }\n names(teta_o) <- points_i$Name[o_points_ind]\n names(dobs) <- points_i$Name[o_points_ind]\n max_teta_name <- names(teta_o[which(teta_o==max(teta_o))])\n max_do <- dobs[which(teta_o == max(teta_o))]\n points_i[points_i$Name == max_teta_name, \"Stable\"] <- FALSE\n points_j[points_j$Name == max_teta_name, \"Stable\"] <- FALSE\n\n o_points_ind <- is.na(points_i$Stable)\n names(o_points_ind) <- points_i$Name\n\n # Qdrr <- Qd_all_ginv[o_points_ind, o_points_ind]\n # Qdro <- Qd_all_ginv[o_points_ind, !o_points_ind]\n # Qdor <- Qd_all_ginv[!o_points_ind, o_points_ind]\n # Qdoo <- Qd_all_ginv[!o_points_ind, !o_points_ind]\n\n Qdrr <- Qd_all_ginv[(!r_points_ind & o_points_ind), (!r_points_ind & o_points_ind)]\n Qdro <- Qd_all_ginv[(!r_points_ind & !o_points_ind), (!r_points_ind & o_points_ind)]\n Qdor <- Qd_all_ginv[(!r_points_ind & o_points_ind), (!r_points_ind & !o_points_ind)]\n Qdoo <- Qd_all_ginv[(!r_points_ind & !o_points_ind), (!r_points_ind & !o_points_ind)]\n\n do <- d_all[!r_points_ind & o_points_ind]\n\n Qsrr <- Qdrr - Qdro %*% solve(Qdoo) %*% Qdor\n\n teta_o_squared <- ((crossprod(do, Qsrr) %*% do)/qr(Qsrr)$rank)\n o_test <- f_test(sd1 = sqrt(teta_o_squared), sd2 = s0, df1 = qr(Qsrr)$rank, df2 = f0, prob = prob)\n\n m <- sum(o_points_ind)\n if(!o_test[[3]] & m == 1){\n points_i[o_points_ind, \"Stable\"] <- FALSE\n points_j[o_points_ind, \"Stable\"] <- FALSE\n }\n }\n }\n\n }\n points_i$Stable[is.na(points_i$Stable)] <- TRUE\n points_j$Stable[is.na(points_j$Stable)] <- TRUE\n\n return(points_i %>% dplyr::select(id, Name, Stable))\n}\n", "meta": {"hexsha": "93f00fa6aedadb5fed043e554e2ab9d3088a1231", "size": 14989, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Deformation_analysis_functions.r", "max_stars_repo_name": "pejovic/Surveyor", "max_stars_repo_head_hexsha": "40839e3cea8836b2b8e2681ffed591a6567ab173", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-14T22:40:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T22:40:36.000Z", "max_issues_repo_path": "R/Deformation_analysis_functions.r", "max_issues_repo_name": "pejovic/Surveyor", "max_issues_repo_head_hexsha": "40839e3cea8836b2b8e2681ffed591a6567ab173", "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/Deformation_analysis_functions.r", "max_forks_repo_name": "pejovic/Surveyor", "max_forks_repo_head_hexsha": "40839e3cea8836b2b8e2681ffed591a6567ab173", "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.7309782609, "max_line_length": 167, "alphanum_fraction": 0.6073787444, "num_tokens": 4823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6629280806072504}} {"text": "# establece ruta para leer/escribir\nsetwd(\"~/Desktop/sip/data\")\n\n# lee datos \nd <- read.csv(\"ptot-edo-2010-2020.csv\")\nstr(d)\n\n# quita total nacional\nd <- d[-which(d$edon==33),]\n\n# recalcula cambio %\nd$chg <- NULL\nd$chg <- d$ptot2020 / d$ptot2010\n\n# población total\nsum(d$ptot2020)\n# cambio\nsum(d$ptot2020) / sum(d$ptot2010)\n# subre/sub-crecimeiento\nd$sobsub <- round(d$chg - sum(d$ptot2020) / sum(d$ptot2010), 2)\nd[order(d$sobsub), c(\"estado\", \"sobsub\")]\n\nquantile(d$sobsub, probs = c(0,.33,.5,.67,1))\n\nquantile(d$ptot2020, probs = c(0,.33,.5,.67,1))\nd$size <- 0\nd$size[d$ptot2020 <= 2332000] <- 1\nd$size[d$ptot2020 > 2332000 & d$ptot2020 <= 3763000] <- 2\nd$size[d$ptot2020 > 3763000] <- 3\n# factor\nd$size <- factor(d$size, levels = 1:3, labels = c(\"ch\",\"med\",\"gde\"))\ntable(d$size)\n\n# ¿cuántas personas cree Ud. que debería representar un diputado federal? = DIVISOR\nr1787 <- 33000 # el techo de 1878 (constitución EUA dice r > 30000)\n# divisor ideal EEUU hoy (nacional)\nr.usa <- round(328200000 / 435)\nr.usa\n\n# relación ideal mx 2020\nr2020 <- round(sum(d$ptot2020) / 300)\n# relación ideal mx previas\nr1990 <- round(sum(d$ptot1990) / 300)\nr2000 <- round(sum(d$ptot2000) / 300)\nr2010 <- round(sum(d$ptot2010) / 300)\nr1990\nr2000\nr2010\nr2020\n\n# Si usaramos esto\nR <- 100000\n\n# Jeferson:\n# (1) Población del estado por divisor = COCIENTE\n# (2) Parte entera del conciente = APPORTIONMENT\napp <- data.frame(edo = d$edo,\n jef90 = as.integer(d$ptot1990 / R),\n jef00 = as.integer(d$ptot2000 / R),\n jef10 = as.integer(d$ptot2010 / R),\n jef20 = as.integer(d$ptot2020 / R))\n# (3) Mínimo dos por estado (regla Mx, no EEUU)\napp$jef90[app$jef90<2] <- 2\napp$jef00[app$jef00<2] <- 2\napp$jef10[app$jef10<2] <- 2\napp$jef20[app$jef20<2] <- 2\napp\n\n# tamaño del Congreso resultante, muy grande\ncolSums(app[,-1])\n\n# pongamos la tercera parte\nR <- 300000\napp <- data.frame(edo = d$edo,\n jef90 = as.integer(d$ptot1990 / R),\n jef00 = as.integer(d$ptot2000 / R),\n jef10 = as.integer(d$ptot2010 / R),\n jef20 = as.integer(d$ptot2020 / R))\n# (3) Mínimo dos por estado (regla Mx, no EEUU)\napp$jef90[app$jef90<2] <- 2\napp$jef00[app$jef00<2] <- 2\napp$jef10[app$jef10<2] <- 2\napp$jef20[app$jef20<2] <- 2\napp\n# tamaño del Congreso resultante, muy grande\ncolSums(app[,-1])\n\n\n# hamilton compromise\n# (1) Fija el tamaño del cuerpo dada la relación de representación\nN <- as.integer( sum(d$ptot2020) / R )\nN # 420, no 403, dice Hamilton. Algunas fracciones tendrán q asignarse para llegar al tamaño \n# (2) Regla de tres: N * Pob estatal / Pob total = cociente\nQ = N * (d$ptot2020 / sum(d$ptot2020))\nentero <- as.integer(Q)\nresto <- Q - as.integer(Q)\n# (3) Mínimo uno por estado\nentero[entero<2] <- 2\n# Cuántos hay?\nfaltan <- N - sum(entero) # falta asignar 17\napp$ham20 <- entero\nsel <- order(-resto)[1:faltan] # índices de los 17 restos mayores\n# verifica\nresto[sel]\nresto[-sel]\n# distribuye los diputados restantes\napp$ham20[sel] <- app$ham20[sel] + 1\n# verifica\nsum(app$ham20)\n\napp[,c(\"edo\",\"jef20\",\"ham20\")]\n# población creciente\napp$dif <- app$ham20 - app$jef20\napp$dif.r <- round(app$ham20 / app$jef20,2)\napp[order(d$ptot2020),c(\"edo\",\"jef20\",\"ham20\",\"dif\",\"dif.r\")]\n\n# descripción según tamaño del estado\napp$size <- d$size\nwith(app, table(size, dif))\nwith(app, table(size, dif.r))\nwith(app, aggregate(dif, list(size), mean))\nwith(app, aggregate(dif.r, list(size), mean))\n\n# mejor comparación con cuerpos del mismo tamaño\n# jeferson\nR <- sum(d$ptot2020) / 300 # con SMDs de diputados\nR <- sum(d$ptot2020) / 315 # prueba-y-error para que suma de enteros llegue a 300\napp <- data.frame(edo = d$edo,\n jef20 = as.integer(d$ptot2020 / R))\napp$jef20[app$jef20<2] <- 2\napp\n# tamaño del Congreso resultante, muy grande\nsum(app[,-1])\n\n# hamilton\nN <- 300\nQ = N * (d$ptot2020 / sum(d$ptot2020))\nentero <- as.integer(Q)\nresto <- Q - as.integer(Q)\n# (3) Mínimo uno por estado\nentero[entero<2] <- 2\n# Cuántos hay?\nfaltan <- N - sum(entero) # falta asignar 17\napp$ham20 <- entero\nsel <- order(-resto)[1:faltan] # índices de los 17 restos mayores\napp$ham20[sel] <- app$ham20[sel] + 1\n# verifica\nsum(app$ham20)\n\napp\n# población creciente\napp$dif <- app$ham20 - app$jef20\napp$dif.r <- round(app$ham20 / app$jef20,2)\napp[order(d$ptot2020),]\n\n# descripción según tamaño del estado\napp$size <- d$size\nwith(app, table(size, dif))\nwith(app, table(size, dif.r))\nwith(app, aggregate(dif, list(size), mean))\nwith(app, aggregate(dif.r, list(size), mean))\n\n# webster\nR <- sum(d$ptot2020) / 300.342 # prueba-y-error para que suma de enteros llegue a 300\napp$web20 <- round(d$ptot2020 / R)\napp$web20[app$web20<2] <- 2\n# tamaño del Congreso resultante, muy grande\nsum(app$web)\n\n## # Hill --- aún no jala, verlo en Balinski\n## N <- 300\n## Q = N * (d$ptot2020 / sum(d$ptot2020))\n## entero <- as.integer(Q)\n## geomedia <- sqrt( entero * (entero+1))\n## app$hill20 <- entero\n## app$hill[Q - geomedia > 0] <- entero[Q - geomedia > 0] + 1\n## # (3) Mínimo uno por estado\n## app$hill20[app$hill20<2] <- 2\n## # Cuántos hay?\n## sum(app$hill20)\n\n# diferencias con hamilton app <-\napp <- within(app, {\n djef20 <- jef20 - ham20 ;\n dweb20 <- web20 - ham20 ;\n drjef20 <- round(jef20 / ham20, 2);\n drweb20 <- round(web20 / ham20, 2)\n})\n\nplot(d$ptot2020, app$djef20, pch = 8)\nsel <- which(app$djef20!=0)\ntext(d$ptot2020[sel], (app$djef20[sel]+.07), labels = app$edo[sel], cex = .6)\n# points(d$ptot2020, app$dweb20, col = \"red\")\n\n# R de cada estado contra la ideal\nplot(d$ptot2020, (d$ptot2020 / app$ham20))\nabline(h = R)\nplot(d$ptot2020, (d$ptot2020 / app$jef20))\nabline(h = R)\n\n# Relative Representation Index (Ansolabehere Snyder)\n# RRI = (pob.nal / 300) / (pob.edo / ndip.edo)\napp$rri.jef <- round((sum(d$ptot2020) / 300) / (d$ptot2020 / app$jef20), 2);\napp$rri.ham <- round((sum(d$ptot2020) / 300) / (d$ptot2020 / app$ham20), 2);\napp$rri.web <- round((sum(d$ptot2020) / 300) / (d$ptot2020 / app$web20), 2);\n\nplot(c(.5,1.5), c(.5,1.5), type = \"n\")\npoints(app$rri.ham, app$rri.jef)\nabline(a = 0, b = 1, lty = 2)\n\nplot(d$ptot2020, app$rri.jef, type = \"n\", main = \"Jefferson\")\ntext(d$ptot2020, app$rri.jef, labels = app$edo, cex = .75)\nabline(h = 1)\n\nplot(d$ptot2020, app$rri.ham, type = \"n\", main = \"Hamilton\")\ntext(d$ptot2020, app$rri.ham, labels = app$edo, cex = .75)\nabline(h = 1)\n\n\napp[,c(\"edo\", \"rri.ham\", \"rri.jef\")]\n\n", "meta": {"hexsha": "12979cbd074fd21307c8296531167bdfcf4ba0f0", "size": 6534, "ext": "r", "lang": "R", "max_stars_repo_path": "code/reapportion.r", "max_stars_repo_name": "emagar/sip", "max_stars_repo_head_hexsha": "46b48aaa3b5f49acd8710a3db89a7c528b328fe4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-13T11:39:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T11:39:08.000Z", "max_issues_repo_path": "code/reapportion.r", "max_issues_repo_name": "emagar/sip", "max_issues_repo_head_hexsha": "46b48aaa3b5f49acd8710a3db89a7c528b328fe4", "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/reapportion.r", "max_forks_repo_name": "emagar/sip", "max_forks_repo_head_hexsha": "46b48aaa3b5f49acd8710a3db89a7c528b328fe4", "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.4324324324, "max_line_length": 94, "alphanum_fraction": 0.6345270891, "num_tokens": 2523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6629280781225921}} {"text": "\n\ncoul <- function(r, qi, qj){\n\treturn ((qi * qj)/(4.0*pi*0.0055264*r))\n}\n\nbuck <- function(r, A, rho, C){\n\treturn (A*exp(-r/rho) - C/r^6)\n}\n\nmorse <- function(r, D, gamma, r_star){\n\treturn (D*(exp(-2*gamma*(r-r_star)))-2*exp(-gamma*(r-r_star)))\n}\n\npot <- function(r, qi, qj, A, rho, C, D, gamma, r_star){\n\treturn (coul(r, qi,qj) + buck(r, A, rho, C) + morse(r, D, gamma, r_star))\n}\n\n\nA <- 693.650934\nrho <- 0.327022\nC <- 0.0\n\nD <- 0.577190\ngamma <- 1.650000\nr_star <- 2.369000\n\nq_O <- -1.2\nq_U <- 2.4\n\nUO_pot <- function(r){\n\treturn(pot(r, q_O, q_U, A, rho, C, D, gamma, r_star))\n}\n\n\n\nxlim <- c(0, 4)\nylim <- c(-25, 30)\n\npdf(\"analytical_plot.pdf\", fonts = \"Helvetica\")\nr <- seq(0.5, 4, length.out = 200)\nr_coarse <- seq(0.98, 4, length.out = 10)\n\nUO <- UO_pot(r)\nUO_coarse <- UO_pot(r_coarse)\n\nplot(r, UO, xlim = xlim, ylim = ylim, type = \"l\", xlab = NA, ylab = NA)\npoints(r_coarse, UO_coarse, col = 'red', pch=16)\nabline(h=0, lty=\"dashed\")\nabline(v=r_coarse, col = \"lightblue\")\ndev.off()\n\npdf(\"table_plot.pdf\")\nplot(r_coarse, UO_coarse, xlim = xlim, ylim = ylim, type = \"l\", xlab = NA, ylab = NA)\npoints(r_coarse, UO_coarse, col = 'red', pch=16)\nabline(h=0, lty=\"dashed\")\ndev.off()", "meta": {"hexsha": "10b8bc2bf5f304cc81b52d103ae736b603c6ee89", "size": 1183, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/quick_start/mk_pot_plot.r", "max_stars_repo_name": "mjdrushton/atsim-potentials", "max_stars_repo_head_hexsha": "566020dc0d2df4b701b9c8cd00319a1c9461f56e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T14:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T14:48:51.000Z", "max_issues_repo_path": "docs/quick_start/mk_pot_plot.r", "max_issues_repo_name": "mjdrushton/atsim-potentials", "max_issues_repo_head_hexsha": "566020dc0d2df4b701b9c8cd00319a1c9461f56e", "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": "docs/quick_start/mk_pot_plot.r", "max_forks_repo_name": "mjdrushton/atsim-potentials", "max_forks_repo_head_hexsha": "566020dc0d2df4b701b9c8cd00319a1c9461f56e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-30T09:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:12:14.000Z", "avg_line_length": 20.7543859649, "max_line_length": 85, "alphanum_fraction": 0.5993237532, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6623899665532131}} {"text": "#!/usr/bin/env R\n\n# http://stackoverflow.com/questions/3485456/useful-little-functions-in-r\n\nspike_file = 'spikes-103-0.gdf'\n\nvoltage_file = 'voltages-104-0.dat'\n\nt_sim = 10\n\n\n\n# Gets the frequencies returned by the FFT function\ngetFFTFreqs = function(Nyq.Freq, data) {\n # Odd number of sample\n if ((length(data) %% 2) == 1) {\n FFTFreqs = c(seq(0, Nyq.Freq, length.out=(length(data)+1)/2),\n seq(-Nyq.Freq, 0, length.out=(length(data)-1)/2))\n }\n else {\n FFTFreqs = c(seq(0, Nyq.Freq, length.out=length(data)/2),\n seq(-Nyq.Freq, 0, length.out=length(data)/2))\n }\n\n return (FFTFreqs)\n}\n\n# FFT plot\n# Params:\n# x,y -> the data for which we want to plot the FFT\n# samplingFreq -> the sampling frequency\n# shadeNyq -> if true the region in [0;Nyquist frequency] will be shaded\n# showPeriod -> if true the period will be shown on the top\n# Returns a list with:\n# freq -> the frequencies\n# FFT -> the FFT values\n# modFFT -> the modulus of the FFT\nplotFFT = function(x, y, samplingFreq, shadeNyq=TRUE, showPeriod = TRUE) {\n Nyq.Freq = samplingFreq/2\n FFTFreqs = getFFTFreqs(Nyq.Freq, y)\n\n FFT = fft(y)\n modFFT = Mod(FFT)\n FFTdata = cbind(FFTFreqs, modFFT)\n\n plot(FFTdata[1:nrow(FFTdata)/2,], t=\"l\", pch=20, lwd=2, cex=0.8, main=\"\",\n xlab=\"Frequency (Hz)\", ylab=\"Power\")\n\n if (showPeriod == TRUE) {\n # Period axis on top\n a = axis(3, lty=0, labels=FALSE)\n axis(3, cex.axis=0.6, labels=format(1/a, digits=2), at=a)\n }\n\n if (shadeNyq == TRUE) {\n # Gray out lower frequencies\n rect(0, 0, 2/max(x), max(FFTdata[,2])*2, col=\"gray\", density=30)\n }\n\n ret = list(\"freq\"=FFTFreqs, \"FFT\"=FFT, \"modFFT\"=modFFT)\n return (ret)\n}\n\n\nbin.ts = function(data, time, bins) {\n times = seq(min(time), max(time), (max(time) - min(time))/bins)\n freq = hist(time, times, plot=FALSE)$counts\n d = data.frame(time=times[-length(times)], freq=freq)\n}\n\n\nspikes = read.csv2(spike_file,\n sep='\\t',\n col.names=c('neuron', 'time', 'spike'),\n header=FALSE,\n stringsAsFactors=FALSE\n)\nspikes$spike = 1\nspikes$time = as.numeric(spikes$time)\n\nspikes.binned = bin.ts(spikes$spike, spikes$time, 1000)\n\npar(mfrow=c(2,1))\nplotFFT(spikes.binned$time, spikes.binned$freq, 1000/10)\n\n\nvoltages = read.csv2(voltage_file,\n sep='\\t',\n col.names=c('neuron', 'time', 'voltage', 'NA'),\n header=FALSE,\n stringsAsFactors=FALSE\n)\nvoltages$time = as.numeric(voltages$time)\nvoltages$voltage = as.numeric(voltages$voltage)\n\nvoltages.binned = bin.ts(voltages$voltage, voltages$time, 1000)\n\nplotFFT(voltages.binned$time, voltages.binned$freq, nrow(voltages.binned)/t_sim)\n\n\n", "meta": {"hexsha": "b5487d4a2c8aeaf9a97f8362145600683b826831", "size": 2577, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/analyze_fft.r", "max_stars_repo_name": "synergetics/nest_expermiments", "max_stars_repo_head_hexsha": "39c50fe7d4713b9d0a8e4618a829d94b4fe7456c", "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/analyze_fft.r", "max_issues_repo_name": "synergetics/nest_expermiments", "max_issues_repo_head_hexsha": "39c50fe7d4713b9d0a8e4618a829d94b4fe7456c", "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/analyze_fft.r", "max_forks_repo_name": "synergetics/nest_expermiments", "max_forks_repo_head_hexsha": "39c50fe7d4713b9d0a8e4618a829d94b4fe7456c", "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": 25.5148514851, "max_line_length": 80, "alphanum_fraction": 0.6627861855, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6623708113529762}} {"text": "isLeapYear <- function(year) {\n ifelse(year%%100==0, year%%400==0, year%%4==0)\n}\n\nfor (y in c(1900, 1994, 1996, 1997, 2000)) {\n print(paste(y, \" is \", ifelse(isLeapYear(y), \"\", \"not \"), \"a leap year.\", sep=\"\"))\n}\n", "meta": {"hexsha": "fea34876965b12c9aff1a048ca021f86ede88cf2", "size": 219, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Leap-year/R/leap-year.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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/Leap-year/R/leap-year.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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/Leap-year/R/leap-year.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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": 27.375, "max_line_length": 86, "alphanum_fraction": 0.5570776256, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6623708040860522}} {"text": "#!/usr/bin/Rscript\n\n# Bhishan Poudel\n# Jan 16, 2016\n\n# ref: http://www.ats.ucla.edu/stat/r/pages/greek_letters.htm\npar(mfrow = c(1, 2))\ncurve(dnorm, from = -3, to = 3, n = 1000, main = \"Normal Probability Density Function\")\ntext(-2, 0.3, expression(f(x) == paste(frac(1, sqrt(2 * pi * sigma^2)),\n \" \", e^{\n frac(-(x - mu)^2, 2 * sigma^2)\n })), cex = 1.2)\nx <- dnorm(seq(-3, 3, 0.001))\nplot(seq(-3, 3, 0.001), cumsum(x)/sum(x), type = \"l\", col = \"blue\",\n xlab = \"x\", main = \"Normal Cumulative Distribution Function\")\ntext(-1.5, 0.7, expression(phi(x) == paste(frac(1, sqrt(2 * pi)),\n \" \", integral(e^(-t^2/2) * dt, -infinity, x))), cex = 1.2)", "meta": {"hexsha": "0c76f0ae9d82c2800555e87aaf5a5b89a776f916", "size": 765, "ext": "r", "lang": "R", "max_stars_repo_path": "AstroSeminar2019Spring/ModernStatistics_R/chap0/plotting/multiplePlotting/ggplot4.r", "max_stars_repo_name": "bhishanpdl/AstroSeminar_OU", "max_stars_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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": "AstroSeminar2019Spring/ModernStatistics_R/chap0/plotting/multiplePlotting/ggplot4.r", "max_issues_repo_name": "bhishanpdl/AstroSeminar_OU", "max_issues_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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": "AstroSeminar2019Spring/ModernStatistics_R/chap0/plotting/multiplePlotting/ggplot4.r", "max_forks_repo_name": "bhishanpdl/AstroSeminar_OU", "max_forks_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "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.0, "max_line_length": 87, "alphanum_fraction": 0.4928104575, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6623704822764299}} {"text": "crp = function(n, a) {\n restaurant = data.frame(table = 1, customers = 1)\n for (j in seq(n - 1)) {\n restaurant = arrival(restaurant, a)\n }\n restaurant\n }\n\narrival = function(r, a) {\n p = 1 - a / (sum(r$customers) + a)\n if (rbinom(1, 1, p)) {\n join_table(r, a)\n } else {\n start_table(r)\n }\n }\n\njoin_table = function(r, a) {\n probs = r$customers / sum(r$customers)\n table = sample(1:nrow(r), size = 1, prob = probs)\n r[table, 'customers'] = r[table, 'customers'] + 1\n r\n }\n\nstart_table = function(r) {\n rbind(r, c(nrow(r) + 1, 1))\n }\n\n", "meta": {"hexsha": "796bc7a354e4f404826ca43f377d789ff191e655", "size": 565, "ext": "r", "lang": "R", "max_stars_repo_path": "chinese-restaurant-process/src/crp.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": "chinese-restaurant-process/src/crp.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": "chinese-restaurant-process/src/crp.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": 19.4827586207, "max_line_length": 51, "alphanum_fraction": 0.5575221239, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6622969535442392}} {"text": "#------------------------------------------------------------------------------\n#\t class calculating metrics for regression models.\n#\n#\tThis class has several functions calculating metrics of predictive ability\n#\tof regression models.\n#\tTo obtain the metrics, initialize the object and call\n#\t\\emph{calculate.metrics} method.\n#\n#\tFollowing metrics are calculated for regression models.\n#\n#\t\\describe{\n#\t\t\\item{Mean squared error (MSE)}{\n#\t\t\t\\eqn{mean((prediction - response) ^ 2)}\n#\t\t}\n#\t\t\\item{Root mean squared error (RMSE)}{\n#\t\t\t\\eqn{sqrt(mean((prediction - response) ^ 2))}\n#\t\t}\n#\t\t\\item{R squared, \\eqn{R ^ 2}}{\n#\t\t\t\\eqn{Pearson's product moment correlation coefficient ^ 2}\n#\n#\t\t\tNote that this definition of \\eqn{R^2} may produce high values\n#\t\t\tfor models without predictive ability so that I recommend to use\n#\t\t\t\\eqn{Q ^ 2} instead of \\eqn{R ^ 2}.\n#\t\t\tSee\n#\t\t\t\\href{http://www.russpoldrack.org/2012/12/the-perils-of-leave-one-out.html}{\n#\t\t\t\tthis\n#\t\t\t},\n#\t\t\t\\href{http://not2hastie.tumblr.com}{this} and\n#\t\t\t\\href{https://metarabbit.wordpress.com/2014/03/06/evaluating-regression-with-cross-validation/}{\n#\t\t\t\tthis\n#\t\t\t}.\n#\t\t}\n#\t\t\\item{Spearman's rho}{\n#\t\t\t\\code{cor(response, prediction, method = \"spearman\")}\n#\t\t}\n#\t\t\\item{Kendall's tau}{\n#\t\t\t\\code{cor(response, prediction, method = \"spearman\")}\n#\t\t}\n#\t\t\\item{Q squared, \\eqn{Q^2}}{\n#\t\t\t\\eqn{\n#\t\t\t\t1 - \\sum((prediction - response) ^ 2)\n#\t\t\t\t/ \\sum((response - mean(response)) ^ 2)\n#\t\t\t}\n#\t\t}\n#\t}\n#------------------------------------------------------------------------------\nregression.metrics.calculator <- R6::R6Class(\"regression.metrics.calculator\")\n\n\n#------------------------------------------------------------------------------\n#\tCalculate mean squared error (MSE).\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.mse\",\n\tfunction(fit) {\n\t\tif (is.factor(fit$response)) {\n\t\t\treturn(NA)\n\t\t}\n\t\treturn(mean((fit$prediction - fit$response) ^ 2))\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate root mean squared error (RMSE).\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.rmse\",\n\tfunction(fit) {\n\t\treturn(sqrt(private$calc.mse(fit)))\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate R squared.\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.r.squared\",\n\tfunction(fit) {\n\t\tif (is.factor(fit$response)) {\n\t\t\treturn(NA)\n\t\t}\n\t\treturn(stats::cor(fit$response, fit$prediction) ^ 2)\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate Spearman's rho.\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.spearman\",\n\tfunction(fit) {\n\t\tif (is.factor(fit$response)) {\n\t\t\treturn(NA)\n\t\t}\n\t\treturn(stats::cor(fit$response, fit$prediction, method = \"spearman\"))\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate Kendall's tau.\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.kendall\",\n\tfunction(fit) {\n\t\tif (is.factor(fit$response)) {\n\t\t\treturn(NA)\n\t\t}\n\t\treturn(stats::cor(fit$response, fit$prediction, method = \"kendall\"))\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate Q squared.\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"private\", \"calc.q.squared\",\n\tfunction(fit) {\n\t\tif (is.factor(fit$response)) {\n\t\t\treturn(NA)\n\t\t}\n\t\tpress <- sum((fit$prediction - fit$response) ^ 2)\n\t\ttss <- sum((fit$response - mean(fit$response)) ^ 2)\n\t\treturn(1 - press / tss)\n\t}\n)\n\n\n#------------------------------------------------------------------------------\n#\tCalculate all metrics.\n#\n#\tArgs:\n#\t\tfit:\n#\t\t\ta list having result of one fold of cross validation\n#\t\t\twith \"response\", \"prediction\" and \"index\" fields.\n#\n#\tReturns:\n#\t\tcalculated metrics in following format.\n#\n#\t\t\tlist(\n#\t\t\t\tmatrix(mse, rmse, r.squared, spearman, kendall, q.squared)\n#\t\t\t)\n#\n#\t\tBecause classification.metrics.calculator can returns metrics for\n#\t\tdifferent threshold determination method, the format of the result\n#\t\tshould be a list having matrix.\n#------------------------------------------------------------------------------\nregression.metrics.calculator$set(\n\t\"public\", \"calculate.metrics\",\n\tfunction(fit) {\n\t\tmetrics <- cbind(\n\t\t\tmse = private$calc.mse(fit),\n\t\t\trmse = private$calc.rmse(fit),\n\t\t\tr.squared = private$calc.r.squared(fit),\n\t\t\tspearman = private$calc.spearman(fit),\n\t\t\tkendall = private$calc.kendall(fit),\n\t\t\tq.squared = private$calc.q.squared(fit)\n\t\t)\n\t\t# To have same result format with classification.metrics.calculator,\n\t\t# return the matrix of metrics in a list.\n\t\treturn(list(metrics))\n\t}\n)\n", "meta": {"hexsha": "2377fade9b405c2751df70357b4bd190234f2850", "size": 5846, "ext": "r", "lang": "R", "max_stars_repo_path": "R/regression.metrics.r", "max_stars_repo_name": "Marchen/cv.models", "max_stars_repo_head_hexsha": "70af64f72933a4172d229413ff43034a53c93163", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T15:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T15:45:35.000Z", "max_issues_repo_path": "R/regression.metrics.r", "max_issues_repo_name": "Marchen/cv.models", "max_issues_repo_head_hexsha": "70af64f72933a4172d229413ff43034a53c93163", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-03-11T04:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:18:14.000Z", "max_forks_repo_path": "R/regression.metrics.r", "max_forks_repo_name": "Marchen/cv.models", "max_forks_repo_head_hexsha": "70af64f72933a4172d229413ff43034a53c93163", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-16T03:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-16T03:30:36.000Z", "avg_line_length": 29.5252525253, "max_line_length": 100, "alphanum_fraction": 0.5251453986, "num_tokens": 1449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6622225287128031}} {"text": "#getwd()\r\nlibrary(dplyr)\r\n\r\npar(mfrow = c(1, 1)) \r\n\r\n# Načtení dat z xlsx souboru\r\ndata_xlsx = readxl::read_excel(\"./1S/ukol_123.xlsx\", \r\n sheet = \"Vysledky mereni\", \r\n skip = 0) \r\n\r\ndata_xlsx = data_xlsx[,-1] # odstraníme první sloupec s indexy\r\ncolnames(data_xlsx)=c(\"A22\",\"A5\",\"B22\",\"B5\",\"C22\",\"C5\",\"D22\",\"D5\") \r\nhead(data_xlsx)\r\n\r\ndata_xlsx$A_d = data_xlsx$A22-data_xlsx$A5\r\ndata_xlsx$B_d = data_xlsx$B22-data_xlsx$B5\r\ndata_xlsx$C_d = data_xlsx$C22-data_xlsx$C5\r\ndata_xlsx$D_d = data_xlsx$D22-data_xlsx$D5\r\n\r\n\r\ndata=reshape(data=as.data.frame(data_xlsx),\r\n direction=\"long\",\r\n varying=list(c(\"A5\", \"B5\", \"C5\", \"D5\"),\r\n c(\"A22\",\"B22\",\"C22\",\"D22\"),\r\n c(\"A_d\",\"B_d\",\"C_d\",\"D_d\")),\r\n v.names=c(\"C5\",\"C22\",\"delta\"), \r\n times=c(\"Amber\",\"Bright\",\"Clear\",\"Dim\"), \r\n timevar=\"vyrobce\")\r\nrow.names(data) = 1:nrow(data)\r\ndata = data[-length(data)] \r\ndata = na.omit(data)\r\n\r\nhead(data)\r\ntail(data)\r\n\r\n# data_A = data %>% filter(vyrobce==\"Amber\")\r\n# data_A = data_A[-1]\r\n\r\n# data_B = data %>% filter(vyrobce==\"Bright\")\r\n# data_B = data_B[-1]\r\n\r\n# data_A_d = data_A$C22-data_A$C5\r\n\r\n# data_A_DK = quantile(data_A_d, 0.25, na.rm=T)\r\n# data_A_HK = quantile(data_A_d, 0.75, na.rm=T)\r\n# data_A_IQR = data_A_HK - data_A_DK\r\n# data_A_DM = data_A_DK - 1.5*data_A_IQR\r\n# data_A_HM = data_A_HK + 1.5*data_A_IQR\r\n\r\n# data_A_d_bezOP = data_A_d\r\n# data_A_d_bezOP[data_A_d<=data_A_DM|data_A_d>=data_A_HM] = NA\r\n\r\ndata_A_d = data %>% filter(vyrobce==\"Amber\") %>% pull(delta)\r\ndata_A_d_bezOP = data_A_d\r\ndata_A_d_bezOP[data_A_d_bezOP %in% boxplot(data_A_d, plot = FALSE)$out] = NA\r\n\r\n# data_B_d = data_B$C22-data_B$C5\r\n\r\n# data_B_DK = quantile(data_B_d, 0.25, na.rm=T)\r\n# data_B_HK = quantile(data_B_d, 0.75, na.rm=T)\r\n# data_B_IQR = data_B_HK - data_B_DK\r\n# data_B_DM = data_B_DK - 1.5*data_B_IQR\r\n# data_B_HM = data_B_HK + 1.5*data_B_IQR\r\n\r\n# data_B_d_bezOP = data_B_d\r\n# data_B_d_bezOP[data_B_d<=data_B_DM|data_B_d>=data_B_HM] = NA\r\n\r\ndata_B_d = data %>% filter(vyrobce==\"Bright\") %>% pull(delta)\r\ndata_B_d_bezOP = data_B_d\r\ndata_B_d_bezOP[data_B_d_bezOP %in% boxplot(data_B_d, plot = FALSE)$out] = NA\r\n\r\nsd(data_A_d_bezOP, na.rm=TRUE)\r\nsd(data_B_d_bezOP, na.rm=TRUE)\r\n\r\npar(mfrow = c(1, 1)) \r\n\r\nboxplot(data_A_d, data_B_d, names=c(\"Amber\",\"Bright\"), ylab=\"pokles světelného toku (lm)\", main=\"Boxploty světelnosti\")\r\n\r\npar(mfrow = c(2, 2)) \r\n\r\nhist(data_A_d_bezOP,\r\n main=\"Amber\",\r\n xlab=\"pokles světelného toku (lm)\",\r\n ylab=\"četnost\",\r\n xlim=c(-15,15),\r\n ylim=c(0,15))\r\n\r\nqqnorm(data_A_d_bezOP,\r\n xlab=\"Teoretické kvantily\",\r\n ylab=\"Výběrové kvantily\",\r\n main=\"Amber\")\r\nqqline(data_A_d_bezOP)\r\n\r\nhist(data_B_d_bezOP,\r\n main=\"Bright\",\r\n xlab=\"pokles světelného toku (lm)\",\r\n ylab=\"četnost\",\r\n xlim=c(-15,15),\r\n ylim=c(0,15))\r\n\r\nqqnorm(data_B_d_bezOP,\r\n xlab=\"Teoretické kvantily\",\r\n ylab=\"Výběrové kvantily\",\r\n main=\"Bright\")\r\nqqline(data_B_d_bezOP)\r\n\r\n\r\nmoments::skewness(data_A_d_bezOP, na.rm=T)\r\nmoments::skewness(data_B_d_bezOP, na.rm=T)\r\n\r\nmoments::kurtosis(data_A_d_bezOP, na.rm=T)-3\r\nmoments::kurtosis(data_B_d_bezOP, na.rm=T)-3\r\n\r\n# test normality Shapirovovým - Wilkovovým testem\r\nshapiro.test(data_A_d_bezOP)$p.value\r\nshapiro.test(data_B_d_bezOP)$p.value\r\n\r\n# test symetrie\r\nlawstat::symmetry.test(data_A_d_bezOP, boot=FALSE)$p.value\r\nlawstat::symmetry.test(data_B_d_bezOP, boot=FALSE)$p.value\r\n\r\nmean(data_A_d_bezOP, na.rm=T)\r\nmean(data_B_d_bezOP, na.rm=T)\r\n\r\nt.test(data_A_d_bezOP, conf.level = 0.95, alternative = \"greater\")$conf.int\r\nt.test(data_B_d_bezOP, conf.level = 0.95, alternative = \"greater\")$conf.int\r\n\r\nt.test(data_A_d_bezOP, alternative=\"greater\", conf.level=0.95)$p.value\r\nt.test(data_B_d_bezOP, alternative=\"greater\", conf.level=0.95)$p.value\r\n\r\nvar(data_A_d_bezOP,na.rm=T)\r\nvar(data_B_d_bezOP,na.rm=T)\r\n\r\n\r\nprumer = mean(data_A_d_bezOP, na.rm=T) - mean(data_B_d_bezOP, na.rm=T)\r\n\r\n# F-Test\r\nvar.test(x = data_A_d_bezOP, y = data_B_d_bezOP, ratio = 1, conf.level = 0.95, alternative = \"two.sided\")$p.value\r\n\r\n# 95% oboustranný interval\r\nt.test(x = data_A_d_bezOP, y = data_B_d_bezOP, mu = prumer, conf.level = 0.95, alternative = \"two.sided\")$conf.int\r\n\r\n# Dvouvýběrový studentův T-test (p-hodnota)\r\nt.test(x = data_A_d_bezOP, y = data_B_d_bezOP, mu = prumer, conf.level = 0.95, alternative = \"two.sided\")$p.value\r\n\r\n# medián x0,1 - median()\r\n# stř.hodnota je mean() - průměr", "meta": {"hexsha": "537f1bfa15611a159df41bfebff6b5ff9a2819b7", "size": 4553, "ext": "r", "lang": "R", "max_stars_repo_path": "2S/2S.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "2S/2S.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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": "2S/2S.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "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.9727891156, "max_line_length": 120, "alphanum_fraction": 0.6485833516, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.662163993489272}} {"text": "#' windspeed\n#'\n#' @description Calculate meteorological wind speed.\n#' \n#' @param u numeric U zonal component (m/s), \n#' @param v numeric V meridian component (m/s), \n#' @return wind speed (m/s)\n#'\n#' @author Istituto per la Bioeconomia CNR Firenze Italy Alfonso Crisci \\email{alfonso.crisci@@ibe.cnr.it}\n#' @keywords Scaler speed wind\n#' \n#' \n#' @export\n\nwindspeed=function(u, v) {return(sqrt(u^2+v^2))}\n", "meta": {"hexsha": "8a7ef500318de36cd8051f00805d0eea96ccf02e", "size": 410, "ext": "r", "lang": "R", "max_stars_repo_path": "R/windspeed.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/windspeed.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/windspeed.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": 25.625, "max_line_length": 110, "alphanum_fraction": 0.6780487805, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6621175831069499}} {"text": "# Simpson's paradox\n\n# Generate data\ndatalist = list()\n\nfor (i in seq(0, 100, 10)) {\n age = runif(10, i, i + 10)\n exercise = (runif(10) + .1 * age) / 10 + .1 * rnorm(10, 0, 2)\n cholesterol = (i / 10) - exercise + .4 * rnorm(10, 0, 2)\n df = data.frame(age, exercise, cholesterol)\n datalist[[(i / 10) + 1]] = df\n}\n\n# Combine all data\ndata_simpson = do.call(rbind, datalist)\n\n# Plot\nplot(data_simpson$age, data_simpson$exercise)\nplot(data_simpson$age, data_simpson$cholesterol)\nplot(data_simpson$exercise, data_simpson$cholesterol)\n\n# Model\nmodel_1 = lm(cholesterol ~ exercise, data=data_simpson)\nmodel_2 = lm(cholesterol ~ exercise + age, data=data_simpson)\n\n# Check\nsummary(model_1)\nsummary(model_2)\n\n\n", "meta": {"hexsha": "563cb25b10b040140e375905db979f4182c1bc5f", "size": 706, "ext": "r", "lang": "R", "max_stars_repo_path": "paradoxes/simpsons_pradox.r", "max_stars_repo_name": "AlxndrMlk/statistics", "max_stars_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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": "paradoxes/simpsons_pradox.r", "max_issues_repo_name": "AlxndrMlk/statistics", "max_issues_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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": "paradoxes/simpsons_pradox.r", "max_forks_repo_name": "AlxndrMlk/statistics", "max_forks_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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.7741935484, "max_line_length": 63, "alphanum_fraction": 0.6855524079, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.6620627187630841}} {"text": "## ----echo=FALSE---------------------------------------------------------------\nrequire(Hmisc)\nknitrSet('parsurv')\n\n\n## ----hr-vs-surv,echo=FALSE,cap='Absolute clinical benefit as a function of survival in a control subject and the relative benefit (hazard ratio). The hazard ratios are given for each curve.',scap='Absolute clinical benefit as a function of survival in a control subject and the relative benefit.'----\nplot(0, 0, type=\"n\", xlab=\"Survival for Control Subject\",\n ylab=\"Improvement in Survival\",\n xlim=c(0,1), ylim=c(0,.7))\ni <- 0\nhr <- seq(.1, .9, by=.1)\nfor(h in hr) {\n i <- i + 1\n p <- seq(.0001, .9999, length=200)\n p2 <- p^h\n d <- p2 - p\n lines(p, d, lty=i)\n maxd <- max(d)\n smax <- p[d==maxd]\n text(smax,maxd+.02, format(h), cex=.6)\n}\n\n\n## ----t-hazard,mfrow=c(2,2),top=1,h=5,w=5,cap='$\\\\log(T)$ distribution for $\\\\sigma=0.25, 0.6, 1, 2$ and for degrees of freedom $1, 2, 3, 5, 7, 15, 500$ (almost log-normal). The top left plot has degrees of freedom written in the plot.',scap='Hazard functions for $\\\\log(T)$ distribution'----\nrequire(rms)\nhaz <- survreg.auxinfo$t$hazard\ntimes <- c(seq(0, .25, length=100), seq(.26, 2, length=150))\nhigh <- c(6, 1.5, 1.5, 1.75)\nlow <- c(0, 0, 0, .25)\ndfs <- c(1, 2, 3, 5, 7, 15, 500)\ncols <- rep(1, 7)\nltys <- 1:7\ni <- 0\nfor(scale in c(.25, .6, 1, 2)) {\n i <- i + 1\n plot(0, 0, xlim=c(0,2), ylim=c(low[i], high[i]),\n xlab=expression(t), ylab=expression(lambda(t)), type=\"n\")\n col <- 1.09\n j <- 0\n for(df in dfs) {\n j <- j+1\n ## Divide by t to get hazard for log t distribution\n lines(times,\n haz(log(times), 0, c(log(scale), df))/times,\n col=cols[j], lty=ltys[j])\n if(i==1) text(1.7, .23 + haz(log(1.7), 0,\n c(log(scale),df))/1.7, format(df))\n }\n title(paste(\"Scale:\", format(scale)))\n} # Figure (*\\ref{fig:parsurv-t-hazard}*)\n\n\n## ----kprats-check,mfrow=c(2,2),h=5,w=6,bot=1,ps=9,cap='Altschuler--Nelson--Fleming--Harrington nonparametric survival estimates for rats treated with DMBA,~\\\\cite{pik66} along with various transformations of the estimates for checking distributional assumptions of three parametric survival models.',scap='Examples of checking parametric survival model assumptions'----\ngetHdata(kprats)\nkprats$group <- factor(kprats$group, 0:1, c('Group 1', 'Group 2'))\ndd <- datadist(kprats); options(datadist=\"dd\")\n\nS <- with(kprats, Surv(t, death))\nf <- npsurv(S ~ group, type=\"fleming\", data=kprats)\nsurvplot(f, n.risk=TRUE, conf='none', # Figure (*\\ref{fig:parsurv-kprats-check}*)\n label.curves=list(keys='lines'), levels.only=TRUE)\ntitle(sub=\"Nonparametric estimates\", adj=0, cex=.7)\n\n# Check fits of Weibull, log-logistic, log-normal\nxl <- c(4.8, 5.9)\nsurvplot(f, loglog=TRUE, logt=TRUE, conf=\"none\", xlim=xl,\n label.curves=list(keys='lines'), levels.only=TRUE)\ntitle(sub=\"Weibull (extreme value)\", adj=0, cex=.7)\nsurvplot(f, fun=function(y)log(y/(1-y)), ylab=\"logit S(t)\",\n logt=TRUE, conf=\"none\", xlim=xl,\n label.curves=list(keys='lines'), levels.only=TRUE)\ntitle(sub=\"Log-logistic\", adj=0, cex=.7)\nsurvplot(f, fun=qnorm, ylab=\"Inverse Normal S(t)\",\n logt=TRUE, conf=\"none\",\n xlim=xl,cex.label=.7,\n label.curves=list(keys='lines'), levels.only=TRUE)\ntitle(sub=\"Log-normal\", adj=0, cex=.7)\n\n\n## ----fittedpsm,results='asis'-------------------------------------------------\nfw <- psm(S ~ group, data=kprats, dist='weibull')\nfl <- psm(S ~ group, data=kprats, dist='loglogistic',\n y=TRUE)\nfn <- psm(S ~ group, data=kprats, dist='lognormal')\nlatex(fw, fi='')\nlatex(fl, fi='')\nlatex(fn, fi='')\n\n\n## ----kprats-psm-np,w=3.75,h=2.5,cap='Agreement between fitted log-logistic model and nonparametric survival estimates for rat vaginal cancer data.',scap='Fitted log-logistic model'----\nsurvplot(f, conf.int=FALSE, # Figure (*\\ref{fig:parsurv-kprats-psm-np}*)\n levels.only=TRUE, label.curves=list(keys='lines'))\nsurvplot(fl, add=TRUE, label.curves=FALSE, conf.int=FALSE)\n\n\n## ----echo=FALSE,results='asis'------------------------------------------------\nlatex(pphsm(fw), fi='', digits=4)\n\n\n## ----kprats-resid-np,w=3.75,h=2.5,cap='Kaplan--Meier estimates of distribution of standardized censored residuals from the log-logistic model, along with the assumed standard log-logistic distribution (dashed curve). The step functions in red is the estimated distribution of all residuals, and the step functions in black are the estimated distributions of residuals stratified by group, as indicated. The blue curve is the assumed log-logistic distribution.',scap='Checking AFT distributional assumption using residuals'----\nr <- resid(fl, 'cens')\nsurvplot(npsurv(r ~ group, data=kprats),\n conf='none', xlab='Residual',\n label.curves=list(keys='lines'), levels.only=TRUE)\nsurvplot(npsurv(r ~ 1), conf='none', add=TRUE, col='red')\nlines(r, lwd=1, col='blue') # Figure (*\\ref{fig:parsurv-kprats-resid-np}*)\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## psm(Surv(d.time, event) ~ 1)\n\n\n## ----eval=FALSE---------------------------------------------------------------\n## units(d.time) <- \"Year\"\n## f <- psm(Surv(d.time,cdeath) ~ lsp(age,65)*sex)\n## # default is Weibull\n## anova(f)\n## summary(f) # summarize effects with delta log T\n## latex(f) # typeset math. form of fitted model\n## survest(f, times=1) # 1y survival est. for all subjects\n## survest(f, expand.grid(sex=\"female\", age=30:80), times=1:2)\n## # 1y, 2y survival estimates vs. age, for females\n## survest(f, data.frame(sex=\"female\",age=50))\n## # survival curve for an individual subject\n## survplot(f, sex=NA, age=50, n.risk=T)\n## # survival curves for each sex, adjusting age to 50\n## f.ph <- pphsm(f) # convert from AFT to PH\n## summary(f.ph) # summarize with hazard ratios\n## # instead of changes in log(T)\n\n\n## ----kprats-Functions,results='asis'------------------------------------------\nmed <- Quantile(fl)\nmeant <- Mean(fl)\nhaz <- Hazard(fl)\nsurv <- Survival(fl)\nlatex(surv, file='', type='Sinput')\n\n## ----kprats-hazard,w=4,h=2.75,top=.6,ps=9,cap='Estimated hazard functions for log-logistic fit to rat vaginal cancer data, along with median survival times.',scap='Estimated log-logistic hazard functions'----\n# Plot estimated hazard functions and add median\n# survival times to graph\nsurvplot(fl, group, what=\"hazard\") # Figure (*\\ref{fig:parsurv-kprats-hazard}*)\n# Compute median survival time\nm <- med(lp=predict(fl,\n data.frame(group=levels(kprats$group))))\nm\nmed(lp=range(fl$linear.predictors))\nm <- format(m, digits=3)\ntext(68, .02, paste(\"Group 1 median: \", m[1],\"\\n\",\n \"Group 2 median: \", m[2], sep=\"\"))\n# Compute survival probability at 210 days\nxbeta <- predict(fl,\n data.frame(group=c(\"Group 1\",\"Group 2\")))\nsurv(210, xbeta)\n\n", "meta": {"hexsha": "238580d9c032618f25ae1aa039dd18938ffc31db", "size": 6878, "ext": "r", "lang": "R", "max_stars_repo_path": "RMScode/18_parametric_survival_theory.r", "max_stars_repo_name": "fabarrios/Regression", "max_stars_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:27:09.000Z", "max_issues_repo_path": "RMScode/18_parametric_survival_theory.r", "max_issues_repo_name": "fabarrios/Regression", "max_issues_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T23:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T23:59:10.000Z", "max_forks_repo_path": "RMScode/18_parametric_survival_theory.r", "max_forks_repo_name": "fabarrios/Regression", "max_forks_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T03:43:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:43:53.000Z", "avg_line_length": 44.0897435897, "max_line_length": 530, "alphanum_fraction": 0.6190753126, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919973399709, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6619415176189581}} {"text": "server <- function(input, output) {\n output$coolplot <- renderPlot({\n n<-input$n\n x<-input$x\n H0<-input$H0\n H1<-input$H1\n LR<-round(max(dbinom(x,n,H0)/dbinom(x,n,H1),dbinom(x,n,H1)/dbinom(x,n,H0)),digits=2) #Calculate LR (H1 over H0 and H0 over H1, pick max)\n H0H1<-ifelse(dbinom(x,n,H0)>dbinom(x,n,H1),\"The data are more likely under the null hypothesis than the alternative hypothesis\",\"The data are more likely under the alternative hypothesis than the null hypothesis\") \n theta<- seq(0,1,len=1000)\n like <- dbinom(x,n,theta)\n plot(theta,like,type='l',xlab=expression(theta), ylab='Likelihood', lwd=2)\n points(H0,dbinom(x,n,H0), lwd=2)\n points(H1,dbinom(x,n,H1), lwd=2)\n segments(H0, dbinom(x,n,H0), x/n, dbinom(x,n,H0), lty=2, lwd=2)\n segments(H1, dbinom(x,n,H1), x/n, dbinom(x,n,H1), lty=2, lwd=2)\n segments(x/n, dbinom(x,n,H0), x/n, dbinom(x,n,H1), lwd=2)\n abline(v=H0, col=\"gray40\", lty=3, lwd=2)\n abline(v=H1, col=\"gray40\", lty=3, lwd=2)\n title(paste('Likelihood Ratio:',LR))\n \n #create Table\n studies<-c(0:n)\n ProbH0<-dbinom(studies,n,H0)\n ProbH1<-dbinom(studies,n,H1)\n table<-cbind(studies,ProbH0,ProbH1)\n colnames(table) <- c(\"Number of significant studies\", \"Probability of observing x out of n significant studies when H0 is true\",\"Probability of observing x out of n significant studies when H1 is true\")\n \n output$text1 <- renderText({ \n paste(\"When H1 is true, in the long run, the probability of observing\", x,\" out of \",n, \" significant studies, given\" ,H1, \"power, is:\", dbinom(x,n,H1),\". If all studies examine true effects with\",100*H1,\"% power,\",100*round(dbinom(x,n,H1),digits=4),\"% of published articles with\",n,\"studies should observe\",x,\"significant results. When power is less than\",100*round(0.5^(1/n), digits=4),\"% observing\",n,\"out of\",n,\"significant results is less likely (i.e., occurs less than 50% of the time) than observing mixed results.\")\n })\n output$text2 <- renderText({ \n paste(\"When H0 is true, in the long run, the probability of observing\", x,\" out of \",n, \" significant studies, given a\" ,H0, \"Type 1 error rate, is:\", round(dbinom(x,n,H0),digits=10),\". When all studies examine null-effects with a\",100*H0,\"% Type 1 error rate,\",100*round(dbinom(x,n,H0),digits=4),\"% of published articles with\",n,\"studies should observe\",x,\"significant results.\")\n })\n output$text3 <- renderText({ \n paste(H0H1, \"with a likelihood ratio of\",LR,\".\")\n })\n output$table = renderDataTable(\n table,\n options = list(paging = FALSE, searching = FALSE)\n )\n })\n}", "meta": {"hexsha": "5d20b8f2f42da9b026408680c93a182a5d6cbc01", "size": 2609, "ext": "r", "lang": "R", "max_stars_repo_path": "mixed_results_likelihood/server.r", "max_stars_repo_name": "Lakens/shiny_apps", "max_stars_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-01-31T17:07:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T12:13:38.000Z", "max_issues_repo_path": "mixed_results_likelihood/server.r", "max_issues_repo_name": "Lakens/shiny_apps", "max_issues_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-21T00:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T12:35:30.000Z", "max_forks_repo_path": "mixed_results_likelihood/server.r", "max_forks_repo_name": "Lakens/shiny_apps", "max_forks_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-12-08T06:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T04:50:02.000Z", "avg_line_length": 62.119047619, "max_line_length": 529, "alphanum_fraction": 0.6627060176, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6618203165629383}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\n\r\nrm(list=ls(all=TRUE))\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\ncat(\"Stan version:\", stan_version(), \"\\n\")\r\nstanmodelcode <- \"\r\n\r\n\r\n#### define GP function\r\nfunctions {\r\n\r\nreal normal_generalized_poisson_log(int y, real theta, real lambda, real sigob) { \r\n return (log(theta) \r\n + (y - 1) * log(theta + y * lambda) \r\n - lgamma(y + 1) \r\n - y * lambda \r\n - theta)*(y<=500)\r\n +(normal_lpdf(y|theta,sigob))*(y>500);\r\n\t\t ### +log(1-normal_cdf(0.08*u,u,0.01))*(b0>0.08*u); #### +log(b0>0.08*u); (b0>0.08*u)\r\n } \r\n\r\n}\r\n\r\n\r\n#### define our data, integer value\r\ndata {\r\nint N;\r\nint y[N];\r\nreal E[N];\r\n}\r\n\r\n\r\n#### define parameters \r\nparameters {\r\n\r\nreal lambda;\r\nreal u;\r\nreal b0;\r\nreal sig2;\r\nvector[N] e;\r\nreal sigob;\r\n}\r\n\r\n\r\n#### define some parameters which is the function of other parameters \r\ntransformed parameters {\r\nvector[N] mu;\r\n\r\n### define the mean function\r\n#mu[1] <- exp(u*exp(-b0)+e[1]);\r\n\r\nmu[1] <- y[1]; ## not tested\r\n\r\n for (n in 2:N) {\r\n\t\r\n mu[n] <- mu[n-1]*exp(u*exp(-b0*n)+e[n]); \r\n\t \r\n\t }\r\n\r\n}\r\n\r\n\r\n\r\n##### define piror and likelihood function\r\nmodel {\r\nlambda~uniform(-1,1);\r\nu ~ normal(0.24,0.01);\r\nb0 ~ normal(0.031,0.001);\r\nsig2 ~ gamma(1,1); \r\ne~normal(0,sig2);\r\nsigob ~ uniform(100,1100);\r\n\r\nfor (j in 1:N) {\r\n\r\ny[j] ~ normal_generalized_poisson( mu[j]*E[j], lambda, sigob);\r\n}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n#### calculate DIC\r\ngenerated quantities {\r\nvector[N] log_lik;\r\nreal dev; // deviance\r\n\r\n\r\n for (n in 1:N){\r\n log_lik[n] <- normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n dev <- 0;\r\n for ( n in 1:N ) {\r\n dev <- dev + (-2) * normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\"\r\n\r\n\r\n###### \r\n\r\n\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covid19modelrisk/data/covid19_infected/\")\r\n\r\n y=read.csv(\"COVID-19_confirmed__Germany.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Italy.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Japan.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Spain.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__US.csv\")\r\n## y=read.csv(\"COVID-19_confirmed_Australia.csv\")\r\n\r\ny=y[,2]\r\n\r\n\r\n\r\n\r\nE=rep(1,length(y))\r\n\r\nN=length(y)\r\ndat <- list(N = N, y = y,E=E)\r\n\r\n\r\n#### initial values\r\ninits =list(list(lambda=0,u=0.24,b0=0.031,sig2=0.0005,e=rep(0.01,N),sigob=1000)) ### 134\r\n\r\n\r\nfit <- stan(model_code = stanmodelcode, model_name = \"example\",init =inits,\r\ndata = dat, warmup=10000,iter = 100000, chains = 1, seed=999,thin=1)\r\nprint(fit,digits = 4)\r\n\r\n\r\n#### threshold =500\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###############################################################################\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################### trace plot\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\nk=7\r\n\r\n\r\npdf(paste(\"M2_\",abn[k],\"_p1.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"u\",\"b0\",\"lambda\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\npdf(paste(\"M2_\",abn[k],\"_p2.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"sigob\",\"sig2\"), inc_warmup = T, nrow = 2, ncol = 1, window = NULL, include = TRUE)\r\ndev.off()\r\n\r\n\r\n\r\n################## plot 30/45/60/ length(y)\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M2_\",abn[k],\"_30.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=30\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M2_\",abn[k],\"_45.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=45\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M2_\",abn[k],\"_60.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=60\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M2_\",abn[k],\"_all.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n######## log plot ####################################################\r\n\r\nk=2\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\ny=log(y)\r\nEpars_m=log(Epars_m)\r\nEpars_9=log(Epars_9)\r\nEpars_5=log(Epars_5)\r\n\r\nsetwd(\"./covid19modelrisk/output/plot/\")\r\n\r\npdf(paste(\"M2_\",abn[k],\"_log.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n#####################################################################################################################################################\r\n###################################### forecast ###################################\r\n\r\nGP.r <- function(L, s)\r\n{\r\n\r\nv=0\r\nLp=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nsLp=Lp\r\n\r\n# calculate the vector of cum pmf\r\nv=1\r\nwhile((sLp<0.9999999) & ((L + v * s )> 0)) \r\n{Lp1=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nLp=c(Lp,Lp1)\r\nsLp=sLp+Lp1\r\nv=v+1\r\n}\r\n\r\ncsLp=c(cumsum(Lp),1) ##### add a max for it \r\nx=length(Lp)\r\n\r\n# first check if you are in the first interval\r\n\r\nU = runif(1)\r\nB = FALSE\r\ni = 1\r\n \r\nwhile(B == FALSE) { \r\n \r\n if(U > csLp[i]) ### U may greater than max of csLp if do not set 1\r\n { i=i+1}\r\n else\r\n {X=i-1\r\n B=TRUE} \r\n\r\n}\r\n\r\nreturn(X)\r\n\r\n}\r\n\r\n################################################\r\n\r\nP=20\r\nMu=matrix(,nrow=90000,ncol=P)\r\nX=matrix(,nrow=90000,ncol=P)\r\n\r\n\r\nlambda_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,1]\r\nu_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,2]\r\nb0_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,3]\r\nsig2_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,4]\r\n\r\n\r\nset.seed(999)\r\n\r\nfor (r in 1:90000){\r\n\r\n\r\n\r\nMu[r,1]=y[length(y)]\r\nfor (s in 1:(P-1) ){\r\n\r\ne=rnorm(1,0,sig2_p[r])\r\n\r\nMu[r,s+1]=Mu[r,s]*exp(u_p[r]*exp(-b0_p[r]*(s+length(y)))+e)\r\n\r\n\r\n}}\r\n\r\n\r\n\r\nsigob=1000\r\nfor (r in 1:90000){\r\nfor (s in 1:P ){\r\n\r\nX[r,s]=rnorm(1,Mu[r,s], sigob)\r\n\r\n\r\n}}\r\n\r\n\r\n\r\n\r\nXm=apply(X,2,mean)\r\n\r\nX5 <- apply( X , 2 , quantile, probs=0.05 )\r\n\r\nX9 <- apply( X , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\nZm=c(y,Xm)\r\nZ5=c(y,X5)\r\nZ9=c(y,X9)\r\n\r\n\r\n##### read forecast\r\nsetwd(\"./covid19modelrisk/data/covid19_infected/\")\r\n\r\n## FT=read.csv(\"COVID-19_confirmed__Germany_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Italy_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Japan_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Spain_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__United Kingdom_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__US_FT.csv\")[,2]\r\nFT=read.csv(\"COVID-19_confirmed_Australia_FT.csv\")[,2]\r\n\r\n\r\n\r\n\r\n\r\nM=length(FT)\r\n\r\ne=FT-Xm\r\nmae=mean(abs(e))\r\nrmse=sqrt(mean(e^2))\r\n############ PR\r\n p=e/FT\r\n# p1=e1/mean(mo1)\r\nmape=mean(abs(p))\r\n########## QR\r\nmd=sum(abs(FT[2:M]-FT[1:(M-1)]))/(M-1)\r\nqj=e/md\r\nmase=mean(abs(qj))\r\n\r\n\r\nlist(mae,rmse,mape,mase)\r\n\r\n\r\n\r\n\r\nZ_FT=c(y,FT)\r\n\r\n\r\nk=7\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nm=length(Zm)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/forecast/\")\r\n\r\npdf(paste(\"M2_\",abn[k],\"_F.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M2 model for \",name[k],sep=\"\"),pch=19,col=\"red\",xaxt = 'n')\r\npolygon(c(rev(newx), newx), c(rev(Z9[1:m]), Z5[1:m]), col = \"grey80\", border = NA)\r\n\r\npar(new=TRUE)\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M2 model for \",name[k],sep=\"\"),pch=19,col=\"red\",xaxt = 'n')\r\nlines(newx,Z9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Z5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(Z_FT[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M2 model for \",name[k],sep=\"\"),pch=19,xaxt = 'n')\r\nlegend(\"topleft\", legend=c(\"Observed data\", \"Forecasted data\"), col=c(\"black\", \"red\"), lty=c(1,1), lwd = 3,cex=2)\r\n\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/27\",\"Mar/17\",\"May/05\",\"Jun/25\",\"Aug/06\")) ### GM\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/31\",\"Mar/13\",\"May/09\",\"Jun/29\",\"Aug/06\")) ### IT\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/22\",\"Mar/12\",\"Apr/30\",\"Jun/19\",\"Aug/06\")) ### JP\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Feb/01\",\"Mar/20\",\"May/10\",\"Jun/30\",\"Aug/06\")) ### SP\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/31\",\"Mar/21\",\"May/09\",\"Jun/29\",\"Aug/06\")) ### UK\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/22\",\"Mar/12\",\"Apr/30\",\"Jun/19\",\"Aug/06\")) ### US\r\naxis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/26\",\"Mar/16\",\"May/04\",\"Jun/24\",\"Aug/06\")) ### AU\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###### RMSE results ###############################################################\r\n\r\n### Germany\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 12517.73\r\n\r\n[[2]]\r\n[1] 14479.24\r\n\r\n[[3]]\r\n[1] 0.05425658\r\n\r\n[[4]]\r\n[1] 10.42504\r\n\r\n\r\n## Italy\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 28633.06\r\n\r\n[[2]]\r\n[1] 33356.15\r\n\r\n[[3]]\r\n[1] 0.1114455\r\n\r\n[[4]]\r\n[1] 42.5554\r\n\r\n\r\n## Japan\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 3407.51\r\n\r\n[[2]]\r\n[1] 3475.616\r\n\r\n[[3]]\r\n[1] 0.06044399\r\n\r\n[[4]]\r\n[1] 3.404822\r\n\r\n\r\n\r\n## Spain\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 6404.752\r\n\r\n[[2]]\r\n[1] 7764.212\r\n\r\n[[3]]\r\n[1] 0.01816862\r\n\r\n[[4]]\r\n[1] 1.153605\r\n\r\n\r\n\r\n## UK\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 21333.73\r\n\r\n[[2]]\r\n[1] 24918.48\r\n\r\n[[3]]\r\n[1] 0.06618652\r\n\r\n[[4]]\r\n[1] 20.42946\r\n\r\n\r\n\r\n## US\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 378799.5\r\n\r\n[[2]]\r\n[1] 464800.3\r\n\r\n[[3]]\r\n[1] 0.06784786\r\n\r\n[[4]]\r\n[1] 8.161634\r\n\r\n\r\n## AU\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 3069.551\r\n\r\n[[2]]\r\n[1] 3986.055\r\n\r\n[[3]]\r\n[1] 0.1254013\r\n\r\n[[4]]\r\n[1] 12.61277\r\n\r\n\r\n\r\n\r\n\r\n\r\n##########################################################################################################################\r\n##########################################################################################################################\r\n##########################################################################################################################\r\nn=length(y)\r\n\r\nu=0.04\r\nb0=0.004\r\n\r\n\r\n\r\nn=length(y)\r\n\r\nx=c()\r\nx[1]=100\r\nfor (i in 1:(n-1) ){\r\n\r\nx[i+1]=x[i]*exp(u*exp(-b0*i))\r\n}\r\nx=round(x)\r\n\r\n\r\nplot(y,ylim=c(min(y),max(y)))\r\npar(new=TRUE)\r\nplot(x,col=\"red\",ylim=c(min(y),max(y)))\r\n\r\n\r\n\r\n\r\n##### initial values ##########################################################################\r\n\r\n### Germany\r\nu=0.24\r\nb0=0.031#u*0.08 ### \r\n\r\n\r\n## Italy\r\nu=0.24\r\nb0=0.03#u*0.08 ### \r\n\r\n\r\n\r\n## Japan\r\nu=0.05\r\nb0=0.0055\r\n\r\n\r\n\r\n## Spain\r\nu=0.3\r\nb0=0.037\r\n\r\n\r\n\r\n## UK\r\nu=0.3\r\nb0=0.037\r\n\r\n\r\n\r\n## US\r\nu=0.1\r\nb0=0.0067\r\n\r\n\r\n## AU\r\nu=0.04\r\nb0=0.004\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7de695b33cae440da0a481eb1e21432f8020c42c", "size": 16057, "ext": "r", "lang": "R", "max_stars_repo_path": "R/M2 run.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M2 run.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M2 run.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 21.669365722, "max_line_length": 183, "alphanum_fraction": 0.5256274522, "num_tokens": 5923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6614515339716294}} {"text": "# Data frame\n# Друга структура за съхраняване на данни в R е data frame. Разликата с матрицата е,\n# че елементите в матрицата е вектор от вектори и всички елементи са от един тип, докато\n# data frame-a е лист от вектори и елементите на data frame-а са от един тип, само в рамките\n# на отделния вектор.\n\nset.seed(104)\n\n#\tИскаме да създадем data frame със симулирани 30 наблюдения.\nN <- 30\n\ngirl_names <- c(\"Ashley Cooper\", \"Doris Parker\", \"Linda Torres\", \"Cynthia Collins\", \"Paula Taylor\",\n \"Maria Perez\", \"Kelly Gray\", \"Wanda Bryant\", \"Kimberly Griffin\", \"Theresa Watson\",\n \"Ruby Brown\", \"Christine Wright\", \"Rose Washington\", \"Marilyn Perry\", \"Teresa Baker\",\n \"Andrea Roberts\", \"Amanda Reed\", \"Tina Harris\", \"Judy Murphy\", \"Nicole Howard\",\n \"Susan Flores\", \"Janice Martin\", \"Pamela Johnson\")\n\nboys_dating_diary <- data.frame(\n #\tDates - 30 дни от днес назад\n asking_for_dating_DATE = as.Date(Sys.time()) - N:1,\n #\tStrings - names of the girls\n girl_names = sample(x = girl_names, size = N, replace = T),\n # Boolean\n accept = sample(x = c(T, F), size = N, replace = T, prob = c(0.1, 0.9)),\n # Uniform distribution from 1 to 10\n rating = round(runif(N, 1, 10))\n)\n\nsample(x = girl_names, size = N, replace = T)\nsample(x = c(T, F), size = N-10, replace = T, prob = c(0.1, 0.9))\nsort(round(runif(N, 1, 10)))\n?runif\n\n#\t- N:1 - създава се вектор с числа от N до 1 (намаляващ вариационен ред)\n#\t- sample(x, size, replace, prob) - на случаен принцип се избират\n#\t - x - вектор, от който се избират елементите,\n#\t - size - размерът на желаната извадка (в нашия случай 30),\n#\t - replace - опцията дали да се преизбират наново елементи.\n# Ако size > x, то задължително трябва replace = TRUE\n#\t - prob - вектор с вероятностите за избиране на случаен елемент.\n# Трябва дължината на prob да бъде равна на дължината на x и сборът да бъде равен на 1.\n\n# Date frame to string\nstr(boys_dating_diary)\n\n# В R можем да вземем първите и последните няколко реда с помощта на функциите head() и tail()\n# Default for n is 6\nhead(x = boys_dating_diary)\nhead(x = boys_dating_diary, n = 3)\ntail(x = boys_dating_diary, n = 3)\n\n# Обединяване на матрици и data frame-ове по редове и колони\n# Union of metrices by rows and cols\nM1 <- matrix(data = 1:20, nrow = 10, byrow = T)\nM2 <- matrix(data = 21:30, nrow = 2, byrow = T)\nM1; M2\n\n# Функциите за обединяване на две матрици/data frame-ове са:\n# - rbind - обединение по редове - долепя втората матрица под първата\n# - cbind - обединение по колони - долепя втората матрица след първата\n\n# Error! Numbers of Rows and Columns must match!\nrbind(M1, M2)\n\n# Check dimensions of matrices\nnrow(M1)\nncol(M1)\ndim(M2)\n\n# Transponse matrices\n# Нека да транспонираме втората матрица (транспонирането е операция, за която редовете се\n# превръщат в колони). Функцията за транспониране в R е t()\nM2.t <- t(M2)\nM2\nM2.t\ndim(M2.t)\n\nrbind(M1, M2.t)\n\n# Union of cols\nM3 <- matrix(data = 21:40, nrow = 10, byrow = T)\ncbind (M1, M3)\n\n# cbind and rbind on Date Frames\nboys_dating_diary_2 <- data.frame(\n #\tDates - 30 дни от днес назад\n asking_for_dating_DATE = as.Date(Sys.time()) - 30 -N:1,\n #\tStrings - names of the girls\n girl_names = sample(x = girl_names, size = N, replace = T),\n # Boolean\n accept = sample(x = c(T, F), size = N, replace = T, prob = c(0.5, 0.5)),\n # Uniform distribution from 1 to 10\n rating = round(runif(N, 1, 10))\n)\ntest = cbind(boys_dating_diary, boys_dating_diary_2)\n\n# Функциите apply, lapply, sapply и т.н. могат да се прилагат и върху data frame-ове\n\n# Взимане на ред, колона и елемент от data frame\n# Всеки от начините, които споменахме при взиамне на елементи от матрица, са приложими и\n# за data frame, като отделно имаме и допълнителни.\n\n#\tdataframe[rows, cols]\n\n# First row and every columns\nboys_dating_diary[1, ]\n\n# First col of every row\nboys_dating_diary[, 1]\nboys_dating_diary[1:nrow(boys_dating_diary), 2]\n\n# Fifth row - second and third col\nboys_dating_diary[5, c(2, 3)]\n\n# Fifth row, second col\nboys_dating_diary[5, 2]\n\n#\tGet or set row names\nrow.names(boys_dating_diary)\nrow.names(boys_dating_diary) <- paste(\"try\", 1:nrow(boys_dating_diary), sep = \"_\")\n#\tС paste() обединяваме вектори със стрингове (n-тия елемент на единия вектор с n-тия елемент на друг вектор)\n# Имената трябва да са уникални\n\n# При data frame-а можем да вземем елементи и посредством техните имена\n\n# - По колони\n#\tС \"$\" взимаме елементи от листа. Data frame-а е ЛИСТ от ВЕКТОРИ => взимаме вектора\nboys_dating_diary$girl_names\nboys_dating_diary[, \"girl_names\"]\nboys_dating_diary[, 2]\n# Последните 3 са еквивалентни\n\n# - По редове - име на реда\nboys_dating_diary[\"try_1\", ]\n\n# - По имена на редове и колони\nboys_dating_diary[\"try_1\", c(\"girl_names\", \"accept\")]\n\n# -----------\n# Филтриране\n# Следващата стъпка е филтрирането на данни и взимането на подгрупи по зададен признак\n\n#\t& - логическо \"и\", | - логическо \"или\", == - проверка за равенство\n\n# which() - Връща вектор с индекстите на елементите, за които булевото условие връща TRUE.\n#\tТоест взимаме индексите на елементите, които ни вълнуват по някакъв начин.\n\n# Нека да проверим кои от всички 30 опита са се оказали сполучиливи. Тоест,\n# приели са поканата на момчето\n# Връща реда\nwhich(boys_dating_diary$accept)\n# Prints the rows\nboys_dating_diary[which(boys_dating_diary$accept), girl_names]\n# Prints only the names\nboys_dating_diary[which(boys_dating_diary$accept), \"girl_names\"]\n\n# More complex filter\nboys_dating_diary[which(boys_dating_diary$rating >= 7 & boys_dating_diary$accept), ]\n# Returns only FALSE AND TRUE for every row\nboys_dating_diary$rating >= 7\n\n# Where IN\nboys_dating_diary[which(boys_dating_diary$girl_names %in% c(\"Doris Parker\", \"Theresa Watson\")), ]\n\n# Как да вземем имената на момичетата, с които въпросният индивид се е опитал да се свърже през последната седмица?\n# Дали са приели?\nlastWeekdays <- as.Date(Sys.time()) - 7:0\nboys_dating_diary[which(boys_dating_diary$asking_for_dating_DATE %in% lastWeekdays), ]\n\nattach(boys_dating_diary)\ngirl_names\ndetach(boys_dating_diary)\n\n# ------------------------------------------------------------------------\n# О П И С А Т Е Л Н А С Т А Т И С Т И К А\n# 1. Променливи\n# Най-простата дефиниция за променливи е характеристика, която се варира от един човек/обект\n# до друг. Променливите са категоризирани в два типа\n# - количествени или числови (представят се с числа)\n# - категорийни или качествени (нечислово изобразяване)\n\n# Категорийните променливи се разбиват на два подтипа\n# - номинални (без подредба) - Примери за стойности на НОМИНАЛНИ променливи са: видове заведения, различни\n# държави и организции, видове алкохол, раси и т.н.\n# - ординални (с подредба) - Примери за стойности на ОРДИНАРНИ променливи са:\n# степени на образование/квалификация, нива на социалните общества и т.н.\n\n# Количествените се разбиват на два подтипа\n# - Непрекъснати (стойностите могат да варират в даден числов интервал) - възраст, различни съотношения, тегло\n# - Дискретни (възможните стойности могат да бъдат изброени) - брой катастрофи на шофьори, брой на деца\n\n# 2. Разпределения\n# Разпределение - това е таблица, графика или формула, съдържаща стойностите на наблюденията\n# и колко често се случват. Разпределенията се характеризират с\n# - форма\n# - модалност (modality)\n# - локация\n# - размах\n# - симетричност/асиметричност\n# - ексцес.\n# - плътност\n\n# ------------------------------------------------------\n# На графиката по-долу са представени няколко от формите на плътността на разпределенията\nN <- 2*(10^4) # 20k\ndistributions <- c(\"Kambanovidna\", \"J-\", \"Pravoygylna\", \"Dqsno asimetrichna\", \"Dvumodalna\")\npar(mfrow = c(2, 3))\n\nfor (distr in distributions) {\n distribution_values <- switch(distr,\n \"Kambanovidna\" = rnorm(N), # Normal distribution\n \"J-\" = rexp(N), # Exponential distribution\n \"Pravoygylna\" = round(runif(N), 2), # Uniform distribution - Равномерно разпределение\n \"Dqsno asimetrichna\" = rgamma(N, shape = 5), # Gamma distribution\n \"Dvumodalna\" = c(rnorm(N, mean = -2, sd = 2), rnorm(N, mean = 3, sd = 1)) #\n )\n\n distr_density <- density(distribution_values)\n ?hist\n hist(\n distribution_values,\n col = \"pink\",\n prob = T,\n main = paste(distr, \"forma na razpredelenie\"),\n ylab = \"Density\",\n xlab = \"Values\",\n ylim = range(distr_density$y),\n xlim = range(distr_density$x)\n )\n\n lines(distr_density, lwd = 3, col = \"blue\") # lwd - width of line\n}\npar(mfrow = c(1, 1))\n\n# ----------------------------------------------------------------------\n# Salaries\ncountry = c('Switzerland', 'Norway', 'Iceland', 'Denmark', 'Finland', 'Netherlands', 'Germany',\n 'Ireland', 'Sweden', 'United Kingdom', 'Austria', 'Belgium', 'France', 'Italy',\n 'Spain', 'Malta', 'Slovenia', 'Estonia', 'Czech Republic', 'Portugal', 'Slovakia',\n 'Poland', 'Croatia', 'Lithuania', 'Greece', 'Latvia', 'Hungary', 'Romania',\n 'Bulgaria', 'Russia', 'Bosnia And Herzegovina', 'Serbia', 'Belarus', 'Albania',\n 'Macedonia', 'Ukraine', 'Moldova')\n\navg_sal_in_USD = c(4959.48, 3416.1, 3136.95, 2975.8, 2583.43, 2575.2, 2538.92, 2521.51, 2494.39,\n 2394.78, 2219.23, 2162.23, 2140.64, 1675.32, 1480.64, 1278.04, 1180.66,\n 1158.76, 1069.03, 925.84, 894.2, 884.81, 852.23, 804.68, 795.34, 771.91,\n 708.91, 649.68, 611.41, 558.01, 481.17, 412.22, 409.62, 348.56, 346.15,\n 293.26, 284.94)\n\nsalaryDF <- data.frame(country, avg_sal_in_USD)\n\n# Cars\nCountry <- c(\"Austria\", \"Belgium\", \"Croatia\", \"Czechia\", \"Denmark\", \"Estonia\", \"Finland\",\n \"France\", \"Germany\", \"Greece\", \"Hungary\", \"Ireland\", \"Italy\", \"Latvia\",\n \"Lithuania\", \"Luxembourg\", \"Netherlands\", \"Norway\", \"Poland\", \"Portugal\",\n \"Romania\", \"Slovakia\", \"Slovenia\", \"Spain\", \"Sweden\", \"Switzerland\", \"UK\")\n\nCar <- c(\"Volkswagen\", \"Volkswagen\", \"Skoda\", \"Skoda\", \"Peugeot\", \"Toyota\", \"Nissan\",\n \"Renault\", \"Volkswagen\", \"Toyota\", \"Suzuki\", \"Hyundai\", \"Fiat\", \"Volkswagen\",\n \"Fiat\", \"Volkswagen\", \"Volkswagen\", \"Nissan\", \"Skoda\", \"Renault\", \"Dacia\",\n \"Skoda\", \"Renault\", \"Seat\", \"Volvo\", \"Skoda\", \"Ford\")\n\ncarsDF <- data.frame(Country, Car)\n\n# --------------------------------------------------------------------------------\n# А Н А Л И З Н А Е Д Н О М Е Р Н А П Р О М Е Н Л И В А\n# (UNIVARIATE ANALYSIS)\n\n# ------------\n# 3. Категорийни променливи\n# Категорийните промеенливи като цяло носят по-малко информация отколкото числовите променливи.\n# Често обаче, те носят по-голяма стабилност за прогнозните моделите отколкото числовите.\n\n# Освен графично представяне на данните (ще го разгледаме по-късно), най-добре честотата се\n# вижда посредством таблици. Функцията, която ни трябва е table()\n\n# Взима първите 6 реда\nhead(carsDF)\n\n# Взима честотното разпределение на категориините променливи\ntt <- table(carsDF$Car)\ntt\nsort(tt)\n\n# Взима процентното разпределение на променливите\nround(prop.table(tt) * 100, 2)\nsort(round(prop.table(tt) * 100, 2))\n\n# Volkswagen държи най-голям пазарен дял по страни в Европа, следван от Skoda\n\n# --------------\n# 4. Числови променливи\n# 4.1. Оценка на центъра (локацията) на разпределение (mean)\n# 4.1.1. Средна стойност (Очакване)\nmeanFunc <- function(x) {\n sum(x) / length(x)\n}\n\nsalaryDF$avg_sal_in_USD\nmeanFunc(salaryDF$avg_sal_in_USD)\nmean(salaryDF$avg_sal_in_USD)\n\n# 4.1.2. Медиана (Median)\n# Подреждаме данните във вариационен ред. Взимаме средната стойност (при нечетен брой)\n# или средната стойност на средните два елемента (при четен брой елементи).\n\nmedianFunction <- function(x) {\n x_sorted <- sort(x)\n length_of_x <- length(x_sorted)\n\n if (length_of_x %% 2 == 0) {\n x_sorted[length_of_x/2 + c(0, 1)]\n return (mean(x_sorted[length_of_x/2 + c(0, 1)]))\n } else {\n print(round(length_of_x/2 + 0.25))\n return (x_sorted[round(length_of_x/2 + 0.25)])\n }\n}\n\nmedianFunction(c(1, 2, 3))\nmedianFunction(salaryDF$avg_sal_in_USD)\nmedian(salaryDF$avg_sal_in_USD)\n\nmedianFunction(1:10)\nmedian(1:10)\n\n# 4.1.3. Мода - най-често срещаната стойност\nmodeFunction <- function(x) {\n tt <- table(x)\n\n return (names(tt))[tt == max(tt)]\n}\n\ntable(round(salaryDF$avg_sal_in_USD / 100))\n\nmodeFunction(round(salaryDF$avg_sal_in_USD / 100))\n\n# Модата може да има повече от една стойност\n# table() - честотоното разпределение на променлива (коя стойност колко пъти се повтаря)\n# which.max() - връща индекса на първото число, което приема МАКСИМАЛНА стойност\n# which.min() - връща индекса на първото число, което приема МИНИМАЛНА стойност\n# names() - връща имената на стойностите\n\n# Описателна статистика за центъра на разпределението\nsummary(salaryDF$avg_sal_in_USD)\n\n# Квантили\nquantile(salaryDF$avg_sal_in_USD, prob = seq(0.1, 0.9, by = 0.1))\n?quantile\n\n# Задача 1 - Ежедневни инциденти с мотоциклети\n# Шотландският изпълнителен директор в отдел \"Аналитични услуги\" на Транспортна\n# статистика събира данни за произшествията с мотоциклети. В таблицата по-долу са\n# представени, броят на инцидентите с мотоциклети в Шотландия по пътища с ограничение\n# до 30 и над 30 мили в час, случили се по дни от седмицата.\nDay <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\")\nBuilt_up <- c(88, 100, 76, 98, 103, 85, 69)\nNon_built_up <- c(70, 58, 59, 53, 56, 94, 102)\n\nmotorcycleAccidentsDF <- data.frame(Day, Built_up, Non_built_up)\n# а. Каква е средната стойност и медианата на броя на произшествията за двата вида пътища\nmean(motorcycleAccidentsDF$Built_up)\nmedian(motorcycleAccidentsDF$Built_up)\n\nmean(motorcycleAccidentsDF$Non_built_up)\nmedian(motorcycleAccidentsDF$Non_built_up)\n\n# б. Каква е формата на разпределението по различните пътища. Интересува ни само модалността.\n\n# Задача 2 - Инвестиции в акциите \"LMT\" и \"FB\"\nDate <- c('2015-09', '2015-10', '2015-11', '2015-12', '2016-01', '2016-02', '2016-03', '2016-04',\n '2016-05', '2016-06', '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12',\n '2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07', '2017-08',\n '2017-09', '2017-10', '2017-11', '2017-12', '2018-01', '2018-02', '2018-03', '2018-04',\n '2018-05', '2018-06', '2018-07', '2018-08', '2018-09')\nFB <- c(89.9, 101.97, 104.24,\n 104.66, 112.21, 106.92, 114.1, 117.58, 118.81, 114.28, 123.94, 126.12, 128.27, 130.99,\n 118.42, 115.05, 130.32, 135.54, 142.05, 150.25, 151.46, 150.98, 169.25, 171.97, 170.87,\n 180.06, 177.18, 176.46, 186.89, 178.32, 159.79, 172, 191.78, 194.32, 172.58, 175.73,\n 164.46)\nLMT <- c(207.31, 219.83, 219.16, 217.15, 211, 215.79, 221.5, 232.38, 236.23, 248.17, 252.73,\n 242.97, 239.72, 246.38, 265.25, 249.94, 251.33, 266.58, 267.6, 269.45, 281.13, 277.61,\n 292.13, 305.39, 310.29, 308.16, 319.12, 321.05, 354.85, 352.44, 337.93, 320.84, 314.54,\n 295.43, 326.1, 320.41, 345.96)\nstocksDF <- data.frame(Date, LMT, FB)\n\n# Анализът трябва да се извърши върху възвръщаемостите на цените, получени по diff(log(x)),\n# където \"x\" е цената на актива\n\n# а. Какви са средните стойности и медианите. Според вас как се интерпретират тези числа\n# б. Можете ли да кажете в кой актив бихте инвестирали при наличието само на тази информация\n\nlog(10, base = 10)\n\nx = 1:5\n", "meta": {"hexsha": "3c92d89d02d7503b02c88e32948b41badef7a1d5", "size": 15450, "ext": "r", "lang": "R", "max_stars_repo_path": "fmi-course-notes/ex2_basic_data_operations.r", "max_stars_repo_name": "ymihaylov/R-playground", "max_stars_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "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": "fmi-course-notes/ex2_basic_data_operations.r", "max_issues_repo_name": "ymihaylov/R-playground", "max_issues_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "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": "fmi-course-notes/ex2_basic_data_operations.r", "max_forks_repo_name": "ymihaylov/R-playground", "max_forks_repo_head_hexsha": "70ce16567992da1d339407d506ac385c51e95099", "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": 39.0151515152, "max_line_length": 115, "alphanum_fraction": 0.6693851133, "num_tokens": 6414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.6614266342824358}} {"text": "# 4. faza: Analiza podatkov\n\nl <- data.frame(leto=c(2020, 2021, 2022))\n\n# Graf za napoved števila delovno aktivnih moških z visokošolsko ali višješolsko izobrazbo\n\nvisokoizobrazeni_moski <- tabela_po_izobrazbi %>% filter(izobrazba == 'Višješolska, visokošolska') %>%\n filter(spol == 'Moški')\nvisokoizobrazeni_moski$leto = as.numeric(as.character(visokoizobrazeni_moski$leto))\n\nmodel_visokoizobrazeni.moski <- lm(stevilo ~ leto, data=visokoizobrazeni_moski)\nnapoved_moski <- mutate(l, stevilo=predict(model_visokoizobrazeni.moski,l))\n\ngraf_napovedi_visokoizobrazeni.moski <- ggplot(visokoizobrazeni_moski, aes(x=leto, y=stevilo)) +\n geom_point() + geom_smooth(method=lm, fullrange=TRUE) +\n geom_point(data=napoved_moski, aes(x=leto, y=stevilo), color='plum1', size=3) +\n scale_x_continuous(breaks=2008:2022) + theme_minimal() + \n labs(title = 'Napoved števila delovno aktivnih moških \\nz visokošolsko ali višješolsko izobrazbo', \n x = 'Leto', y = 'Število v 1000')\n\n# Graf za napoved števila delovno aktivnih žensk z visokošolsko ali višješolsko izobrazbo\n\nvisokoizobrazene_zenske <- tabela_po_izobrazbi %>% filter(izobrazba == 'Višješolska, visokošolska') %>%\n filter(spol == 'Ženske')\nvisokoizobrazene_zenske$leto = as.numeric(as.character(visokoizobrazene_zenske$leto))\n\nmodel_visokoizobrazene.zenske <- lm(stevilo ~ leto, data=visokoizobrazene_zenske)\nnapoved_zenske <- mutate(l, stevilo=predict(model_visokoizobrazene.zenske,l))\n\ngraf_napovedi_visokoizobrazene.zenske <- ggplot(visokoizobrazene_zenske, aes(x=leto, y=stevilo)) +\n geom_point() + geom_smooth(method=lm, fullrange=TRUE) +\n geom_point(data=napoved_zenske, aes(x=leto, y=stevilo), color='plum1', size=3) +\n scale_x_continuous(breaks=2008:2022) + theme_minimal() + \n labs(title = 'Napoved števila delovno aktivnih žensk \\nz visokošolsko ali višješolsko izobrazbo', \n x = 'Leto', y = 'Število v 1000')\n", "meta": {"hexsha": "8ab2bc981e258329d2a35b90b05b368f1323305c", "size": 1888, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "NezaLesnjak/APPR-2020-21", "max_stars_repo_head_hexsha": "833e666bcf6f8b28a01cc2a398b745d727402373", "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": "NezaLesnjak/APPR-2020-21", "max_issues_repo_head_hexsha": "833e666bcf6f8b28a01cc2a398b745d727402373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-06T16:20:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T08:21:15.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "NezaLesnjak/APPR-2020-21", "max_forks_repo_head_hexsha": "833e666bcf6f8b28a01cc2a398b745d727402373", "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.4444444444, "max_line_length": 103, "alphanum_fraction": 0.7648305085, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6613978444895195}} {"text": "#' Calculate the realized volatility for a transction price time-series\n#'\n#' @param price and xts object containting transaction prices\n#' @param interval the window size to calculate realized volatility over. The\n#' default is 5 mintes.\n#' @param interval const the number of trading periods specified by the interval\n# for example if you are looking at daily this should be set to 252, which\n#' is the number of trading days in a year. It should be noted that this is \n#' only needed for calculations like realized volatility. For comparison\n#' of two stocks over the same intervals it is fine to leave this as 1.\n#' @examples\n#' data(aapl_fix)\n#' ctp = consolidate_prices(aapl_fix$sys_date, aapl_fix$sys_time, \n#' aapl_fix$td_price, aapl_fix$td_size, date_format=\"%Y-%m-%d\", \n#' time_format=\"%H:%M:%S\")\n#' rv = realized_volatility(ctp$price)\n#' plot(rv)\n#' @export\nrealized_volatility = function(price, interval=minutes(5),\n interval_const=1) {\n log_price = log(price)\n log_diff_price = na.omit(diff(log_price))\n if (is.null(getDoParName())) registerDoSEQ()\n ret=foreach(it=inclusive_window_gen(time(log_diff_price), interval), \n .combine=rbind) %dopar% {\n ldp = log_diff_price[it]\n data.frame(\n list(volatility=\n 100*sqrt(interval_const/length(ldp)*mean(ldp^2, na.rm=TRUE)),\n time=tail(time(ldp), 1)))\n }\n xts(ret$volatility, order.by = ret$time)\n}\n\n", "meta": {"hexsha": "f448ac80698737814c826422afe5b77a165603f9", "size": 1422, "ext": "r", "lang": "R", "max_stars_repo_path": "R/windowed_metrics.r", "max_stars_repo_name": "hafen/nxcore", "max_stars_repo_head_hexsha": "56811368b22e954083a765bb9d4946c15d83fa40", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-04-14T17:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-02T00:21:05.000Z", "max_issues_repo_path": "R/windowed_metrics.r", "max_issues_repo_name": "hafen/nxcore", "max_issues_repo_head_hexsha": "56811368b22e954083a765bb9d4946c15d83fa40", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-03-27T20:13:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T16:27:57.000Z", "max_forks_repo_path": "R/windowed_metrics.r", "max_forks_repo_name": "hafen/nxcore", "max_forks_repo_head_hexsha": "56811368b22e954083a765bb9d4946c15d83fa40", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-05-16T06:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T06:34:48.000Z", "avg_line_length": 40.6285714286, "max_line_length": 80, "alphanum_fraction": 0.7074542897, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6613525449493157}} {"text": "### Obtain effectRatio code from GitHub ###\nsource(\"https://raw.githubusercontent.com/hyunseungkang/matchIV/master/effectRatio.r\")\n\n##### Example Run #####\n### Generate simulated data ###\n\n### Simulated data contains n=1000 individuals, \n### the response (denoted as R), the exposure\n### (denoted as D), the instrument (denoted as\n### Z), and the covariates (denoted as X)\n\n### Simulated Data Characteristics\n### R is continuous (e.g. height)\n### D is continuous (e.g. amount of malaria parasite in plasma)\n### Z is binary (1/0 e.g. Sickle cell trait status)\n### X1 is a continuous variable (e.g. birthweight),\n### X2 is a binary variable (1/0, e.g. sex)\n### NOTE1: our method can handle continuous, discrete, binary R,D,Xs, \n### and many covariates. Our method only\n### requires that Z is binary (1/0) and non-missing.\n### NOTE2: If some values of Xs are missing \n### (e.g. contains NAs), then\n### you must provide a \"cleaned\" X\n### without NAs, depending on how \n### you want to take care of missing\n### values (e.g. imputation, MCAR, MAR, etc.) \n### NOTE3: If R or D are missing, then you must provide a \n### cleaned R and D without NAs.\n\nset.seed(1) #Random number generator seed. Change it as you please!\nn = 1000\nZ = runif(n) < 0.5\nX1 = rnorm(n,rep(c(0,1),n/2))\nX2 = rep(c(0,1),n/2)\nX = cbind(X1,X2)\n\n# Generate R and D\n# Note that R and D are non-linear functions of X.\n# -3 is the true value of the causal effect of D on R in this example\n# Our point estimator should be close to -3 and our confidence interval\n# should have the desired level of coverage\nD = -1 + 0.2 * Z + X1 - 2*X1^2 - 2 * X2 + rnorm(n)\nR = 2 - 3 * D + X1 - 2*X1^2 - 2 * X2 + rnorm(n)\n\n\n### Run our method (automatically matches and estimateds Lambda)\nestLambda(Z,R,D,X)\n\n### Run 2SLS\nest2SLS(Z,R,D,X)\n\n### EXPECTED RESULT: \n### In most cases, you will notice that our method (estLambda)'s\n### point estimate will be closer to -3. Furthermore, our confidence\n### interval should have the desired 95% level of coverage. \n### In contrast, 2SLS (est2SLS) will be off from -3 most of the \n### time and its confidence interval will not have the desired \n### 95% level of coverage.\n\n\n#### Some other functions\n### Match analysis\nfullmatchvec = matching(Z,X) #full-match individuals\nbalanceCheck(Z,X,fullmatchvec) #checks balance of covariates\n", "meta": {"hexsha": "679cdba7c16f4f4e1eb790fadb14f42af71edd1f", "size": 2420, "ext": "r", "lang": "R", "max_stars_repo_path": "example.r", "max_stars_repo_name": "hyunseungkang/matchIV", "max_stars_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-01T17:10:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T06:30:30.000Z", "max_issues_repo_path": "example.r", "max_issues_repo_name": "hyunseungkang/matchIV", "max_issues_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "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": "example.r", "max_forks_repo_name": "hyunseungkang/matchIV", "max_forks_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "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.2307692308, "max_line_length": 86, "alphanum_fraction": 0.6566115702, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6613525199874991}} {"text": "mean mean<- 15.28\r\nvar <- 9.07\r\n\r\ndomanda1_a <- 13.92\r\ndomanda1_b <- 16.19\r\ndomanda2 <- 10.87\r\ndomanda3 <- 12.85\r\n\r\n\r\n\r\nsd <- sqrt(var)\r\nx <- seq(mean-5, mean+5, length.out = 100)\r\n\r\nrisposta1 <- pnorm(mean = mean, sd = sd, q = c(domanda1_a,domanda1_b))\r\nrisposta2 <- pnorm(mean = mean, sd = sd, q = domanda2)\r\nrisposta3 <- c(pnorm(mean = mean, sd = sd, q = -domanda3),\r\n pnorm(mean = mean, sd = sd, q = domanda3))\r\n\r\n\r\nplot(x, dnorm(mean = mean, sd = sd, x = x), type=\"l\")\r\nprint(risposta1[2]-risposta1[1])\r\nprint(risposta2)\r\nprint( risposta3[1] + (1-risposta3[2]))", "meta": {"hexsha": "47ef772b9989843b66a82e074b3acf94320929ed", "size": 580, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 41.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 41.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 41.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": 25.2173913043, "max_line_length": 71, "alphanum_fraction": 0.5931034483, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6609303022730385}} {"text": "# Function that returns the Proba-V tile number when given a set of coordinates\nProbaVTileID = function(point)\n{\n # X00Y00 is -180.0005, -170.0005, 65.0005, 75.0005 (xmin, xmax, ymin, ymax)\n # X12Y13 is -60.0005, -50.0005, -64.9995, -54.9995\n # X17Y03 is -10.0005, -0.0005, 35.0005, 45.0005\n # X18Y04 is -0.0005, 9.9995, 25.0005, 35.0005\n # X18Y06 is -0.0005, 9.9995, 5.0005, 15.0005\n # X18Y07 is -0.0005, 9.9995, -4.9995, 5.0005\n # X35Y12 is 169.9995, 179.9995, -54.9995, -44.9995\n # Point 0,0 is at X18Y07\n \n # xmin: -180.0005 + 10 * X\n # xmax: xmin + 10\n # ymin: 65.0005 - 10 * Y\n # ymax: ymin + 10\n \n # Inversion: (180.0005 + xmin)/10 = X\n XID = as.integer((180.0005 + point$x)/10)\n # Inversion: (75.0005 - ymin)/10 = Y\n YID = as.integer((75.0005 - point$y)/10)\n \n return(sprintf(\"X%02dY%02d\", XID, YID))\n}\n\n# Africa is from X16Y03 to X23Y10\n", "meta": {"hexsha": "4311de07cd28f9f596410165e103cf64d5c60585", "size": 944, "ext": "r", "lang": "R", "max_stars_repo_path": "src/pixel-based/utils/ProbaVTileID.r", "max_stars_repo_name": "GreatEmerald/master-classification", "max_stars_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-18T07:28:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T07:28:55.000Z", "max_issues_repo_path": "src/pixel-based/utils/ProbaVTileID.r", "max_issues_repo_name": "GreatEmerald/master-classification", "max_issues_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "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": "src/pixel-based/utils/ProbaVTileID.r", "max_forks_repo_name": "GreatEmerald/master-classification", "max_forks_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-07T08:58:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-02T14:07:32.000Z", "avg_line_length": 34.962962963, "max_line_length": 82, "alphanum_fraction": 0.5699152542, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6608041710716309}} {"text": "#!/usr/bin/Rscript\n\n################################################################################\n# Fundamentos de la Ciencia de Datos - 78106 - R-PL1 #\n# Grupo 4 - P1 #\n# Authors: #\n# - David Emanuel Craciunescu #\n# - Laura Pérez Medeiro #\n# #\n################################################################################\n\n################################################################################\n# IMPORTS AND DEPENDENCY CHECKS #\n################################################################################\n\nlibrary(docopt)\nlibrary(foreign)\nlibrary(tools)\nlibrary(splus2R)\n\n# list_of_packages[!(list_of_packages %in% installed.packages()[, \"Package\"])]\n\n################################################################################\n# CALCULATIONS #\n################################################################################\n\n# 1. Calculate absolute and relative satellite radius frequencies.\n\n## 1.1. Absolute frequencies.\nabsoluteFreq <- function(set) {table(set)}\ncumAbsoluteFreq <- function(set) {cumsum(absoluteFreq(set))}\n\n## 1.2. Relative frequencies.\n relativeFreq <- function(set) {table(set) / length(set)}\ncumRelativeFreq <- function(set) {cumsum(relativeFreq(set))}\n\n################################################################################\n\n# 2. Arithmetic mean.\narithmeticMean <- function(set, usrTrim = 0) (mean(set, trim = usrTrim))\n\n################################################################################\n\n# 3. Measures of dispersion.\n\n# The following page was used as a reference for this section.\n# http://iridl.ldeo.columbia.edu/dochelp/StatTutorial/Dispersion/index.html#Intro\n\n## 3.1. Range.\n range <- function(set) {max(set) - min(set)}\n\n## 3.2. Standard Deviation.\n stdDeviation <- function(set)\n{\n sd(set) * (sqrt((length(set) - 1) / length(set)))\n}\n\n## 3.3. Variance.\n variance <- function(set) {var(set) * (length(set) - 1 / length(set))}\n\n## 3.4. Root Mean Square.\n rootMeanSqr <- function(set) {sqrt(mean(set ^ 2))}\n\n## 3.5. Root Mean Square Anomaly.\n rootMeanSqrAn <- function(set) {sqrt(sum(set - mean(set)) ^ 2) / length(set)}\n\n## 3.6. Interquartile Range.\ninterQuartRange <- function(set) {IQR(set)}\n\n## 3.7. Median Absolute Deviation.\nmedAbsDeviation <- function(set) {mad(set)}\n\n################################################################################\n\n# 4. Measures of order.\n\n## 4.1. Median.\ngetMedian <- function(set) {median(set)}\n\n## 4.2. Mode.\ngetMode <- function(set)\n{\n uniqueVal <- unique(set)\n uniqueVal[which.max(tabulate(match(set, uniqueVal)))]\n}\n\n## 4.2. Quartiles.\ngetQuartiles <- function(set) {quantile(set)}\n\n## 4.3. 54th Quantile.\ngetQuantiles <- function(set, range = 0) {quantile(set, probs = range)}\n\n################################################################################\n# INTERFACE #\n################################################################################\n\n'\nsStats 1.1, a simple statistical analyzer\n\nUsage:\n sstats freq (--abs | --cum_abs | --rel | --cum_rel) (--path=PATH --var=VAR)\n sstats mean (--path=PATH --var=VAR)\n sstats disp (--iq | --mad | --rng | --rms | --rmsa | --std | --vari) (--path=PATH --var=VAR)\n sstats ord (--med | --mod | --qnt=QUANT | --qrt) (--path=PATH --var=VAR)\n sstats -a | --authors\n sstats -h | --help\n sstats -l | --license\n sstats --version\n\nOptions:\n -a --authors Show authors of the program.\n -h --help Show this screen.\n -l --license Show license information.\n --version Show version information.\n\nCommands:\n freq - frequency analyzer\n --abs Absolute frequency\n --cum_abs Cumulative absolute frequency\n --rel Relative frequency\n --cum_rel Cumulative relative frequency\n\n mean Arithmetic mean\n\n disp - dispersion measures\n --iq Interquartile range\n --mad Median absolute deviation\n --rng Range\n --rms Root mean square\n --rmsa Root mean square anomaly\n --std Standard deviation\n --vari Variance\n \n ord - ordering measures\n --med Median\n --mod Mode\n --qnt=QUANT Quantile\n --qrt Quartile\n\nInput:\n Only processes .txt and .sav files.\n' -> docString\n\nargs <- docopt(docString, version = 'sStats 1.1')\n\n################################################################################\n# PARSE INPUT #\n################################################################################\n\nif (args $ authors) {\n cat(\"Proudly developed by @craciunescu and @laurapm\\n\")\n\n} else if (args $ license) {\n cat(readLines(\"../LICENSE\"), fill = T)\n\n} else {\n\n # Process input file | Check for supported extension\n ext <- lowerCase(file_ext(file.path(args$path)))\n\n if (ext == \"txt\") {\n dataset <- read.table(args$path)\n } else if (ext == \"sav\") {\n dataset <- read.spss(args$path, to.data.frame = T)\n } else {\n print(\"The input file cannot be processed\")\n }\n\n # R does not accept direct variable reference to dataset column.\n \n column <- args$var\n data <- c(dataset[column][!is.na(dataset[column])]) \n\n ############################################################################\n # COMMANDS #\n ############################################################################\n\n # Frequencies.\n if (args $ freq) {\n \n if (args $ abs) {\n cat(\"Absolute frequency of data\")\n absoluteFreq(data)\n \n } else if (args $ cum_abs) {\n cat(\"Cumulative absolute frequency\\n\")\n cumAbsoluteFreq(data)\n\n } else if (args $ rel) {\n cat(\"Relative frequency of data\") \n relativeFreq(data)\n \n } else if (args $ cum_rel) {\n cat(\"Cumulative relative frequency of data\")\n cumRelativeFreq(data)\n \n } else {\n cat(\"Unsupported behavior for FREQ command\")\n print(docString)\n }\n\n # Means.\n } else if (args $ mean) {\n cat(\"Arithmetic mean =\", arithmeticMean(data), \"\\n\")\n\n # Dispersion.\n } else if (args $ disp) {\n if (args $ iq) {\n cat(\"Interquartile Range =\", interQuartRange(data), \"\\n\")\n\n } else if (args $ mad) {\n cat(\"Median Absolute Deviation =\", medAbsDeviation(data), \"\\n\")\n\n } else if (args $ rng) {\n cat(\"Range =\", range(data), \"\\n\")\n\n } else if (args $ rms) {\n cat(\"Root mean square =\", rootMeanSqr(data), \"\\n\")\n\n } else if (args $ rmsa) {\n cat(\"Root mean square anomaly =\", rootMeanSqrAn(data), \"\\n\")\n\n } else if (args $ std) {\n cat(\"Standard deviation =\", stdDeviation(data), \"\\n\")\n\n } else if (args $ vari) {\n cat(\"Variance =\", variance(data), \"\\n\")\n\n } else {\n cat(\"Unsupported behavior for DISP command\")\n cat(docString)\n }\n \n # Ordering.\n } else if (args $ ord) {\n if (args $ med) {\n cat(\"Median =\", getMedian(data), \"\\n\")\n\n } else if (args $ mod) {\n cat(\"Mode =\", getMode(data), \"\\n\")\n\n } else if (!is.null(args$qnt)) {\n \n quant <- as.numeric(args$qnt)\n\n if ((quant > 0) && (quant <= 1))\n {\n cat(\"Quantile\", quant*100, \"% =\" , getQuantiles(data, quant), \"\\n\")\n } else {\n cat(\"Unsupported Quantile Value\\n\")\n cat(\"--qnt=[0-1]\\n\")\n }\n\n } else if (args$qrt) {\n cat(\"Quartiles\\n\")\n getQuartiles(data)\n\n } else {\n cat(\"Unsupported behavior for ORD command\")\n cat(docString)\n }\n\n # Unsupported behavior.\n } else {\n cat(\"An unidentified error has occurred\")\n cat(\"Please report bugs to github.com/craciunescu/sstats\")\n cat(\"\\n\")\n cat(docString)\n }\n}\n", "meta": {"hexsha": "ac60a4c40fc0b815bc1c11fc38292c97509fab56", "size": 8690, "ext": "r", "lang": "R", "max_stars_repo_path": "PL1/src/r/sstats.r", "max_stars_repo_name": "craciunescu/DataScience", "max_stars_repo_head_hexsha": "e246994974d817f48d6861162f2804ed4c9539ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-22T15:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T15:58:11.000Z", "max_issues_repo_path": "PL1/src/r/sstats.r", "max_issues_repo_name": "craciunescu/DataScience", "max_issues_repo_head_hexsha": "e246994974d817f48d6861162f2804ed4c9539ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T00:46:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T00:46:53.000Z", "max_forks_repo_path": "PL1/src/r/sstats.r", "max_forks_repo_name": "craciunescu/datascience", "max_forks_repo_head_hexsha": "e246994974d817f48d6861162f2804ed4c9539ff", "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.0664206642, "max_line_length": 96, "alphanum_fraction": 0.4369390104, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6605831417207988}} {"text": "# book: Design and Analysis of Experiments with R\n# review: the theory is a mess, but can be used as a guide for which packages to use for specific plans\n\nset.seed(42)\n\nf = factor(rep(c(35, 40, 45), each = 4))\nf\n\n# randomize\nf1 = sample(f, 12)\nf1\n\n# numbers of observations\ne = 1:12\ne\n\nplan = data.frame(loaf = e, time = f1)\nplan\n\ngetwd()\nsetwd(\"/home/tony/source/design-of-experiments\")\nwrite.csv(plan, file = 'plan.csv', row.names = FALSE)\n\nbread = read.csv(\"plan.csv\")\nbread\n\nheight = c(9.75, 8.75, 4.5, 6.5, 6.5, 5.0, 10.5, 5.5, 6.5, 9.5, 8.25, 6.75)\nbread = data.frame(loaf = plan$loaf, time = plan$time, height = height)\nbread\n\n\ninstall.packages('daewr')\nlibrary(daewr)\n\nmodel1 = lm(height ~ time, data = bread)\nsummary(model1)\n\n# - 1 removes the free coefficient\nmodel2 = lm(height ~ time - 1, data = bread)\nsummary(model2)\n\ninstall.packages('gmodels')\nlibrary(gmodels)\n\n# compare 35 to 40 minutes\nfit.contrast(model1, \"time\", c(1, -1, 0))\n# the same fit.contrast won't work on model2, because it is missing its free coefficient\n\n# build ANOVA table\nmodel3 = aov(height ~ time, data = bread)\nsummary(model3)\n\nplot(model3, which = 1)\nplot(model3, which = 2) # qq-plot\n\nlibrary(MASS)\nbc = boxcox(model3)\nlambda = bc$x[which.max(bc$y)]\nlambda\n\n# when you have observations close to being outliers, you can normalize (transform) the data\nbreadtr = transform(bread, heighttr = height ^ lambda)\nbreadtr\n\nmodel4 = aov(heighttr ~ time, data = breadtr)\nsummary(model4) # the p-value is smaller for model4 than for model3\nsummary(model3)\n\n# the probability distributions in the plots are hardly influenced by transformations\nplot(model4, which = 2)\n\n# use this plot to see if the order of the observations made in time has a functional dependence\n# it is possible to have a time series\nplot(residuals(model4) ~ loaf, data = bread)\n\nmodel3tukey = TukeyHSD(model3, ordered = T)\nmodel3tukey\n\ncontr.poly(3)\ncontrasts(bread$time)\n\ninstall.packages('agricolae')\nlibrary(agricolae)\n\n# Newman-Koils test\nprint(SNK.test(model3, 'time', group = FALSE))\n\ninstall.packages('multcomp')\nlibrary(multcomp)\n\ncontrd = glht(model3, linfct = mcp(treat = 'Dunnet'), alternative = 'greater')\nsummary(contrd)\n", "meta": {"hexsha": "717fc11e60fc2c329cdb8c62d216a67cfb35491a", "size": 2184, "ext": "r", "lang": "R", "max_stars_repo_path": "models/01-first-plan.r", "max_stars_repo_name": "antonpetkoff/design-of-experiments", "max_stars_repo_head_hexsha": "04009bc48a89d214a602b4400310b9fecb83c7f6", "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": "models/01-first-plan.r", "max_issues_repo_name": "antonpetkoff/design-of-experiments", "max_issues_repo_head_hexsha": "04009bc48a89d214a602b4400310b9fecb83c7f6", "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": "models/01-first-plan.r", "max_forks_repo_name": "antonpetkoff/design-of-experiments", "max_forks_repo_head_hexsha": "04009bc48a89d214a602b4400310b9fecb83c7f6", "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": 23.4838709677, "max_line_length": 103, "alphanum_fraction": 0.717032967, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6605324700341095}} {"text": "\r\n\r\n# Goals: Simulate a dataset from a \"fixed effects\" model, and\r\n# obtain \"least squares dummy variable\" (LSDV) estimates.\r\n#\r\n# We do this in the context of a familiar \"earnings function\" -\r\n# log earnings is quadratic in log experience, with parallel shifts by\r\n# education category.\r\n\r\n# Create an education factor with 4 levels --\r\neducation <- factor(sample(1:4,1000, replace=TRUE),\r\n labels=c(\"none\", \"school\", \"college\", \"beyond\"))\r\n# Simulate an experience variable with a plausible range --\r\nexperience <- 30*runif(1000) # experience from 0 to 20 years\r\n# Make the intercept vary by education category between 4 given values --\r\nintercept <- c(0.5,1,1.5,2)[education]\r\n\r\n# Simulate the log earnings --\r\nlog.earnings <- intercept +\r\n 2*experience - 0.05*experience*experience + rnorm(1000)\r\nA <- data.frame(education, experience, e2=experience*experience, log.earnings)\r\nsummary(A)\r\n\r\n# The OLS path to LSDV --\r\nsummary(lm(log.earnings ~ -1 + education + experience + e2, A))\r\n\r\n", "meta": {"hexsha": "61903372578411358aa1ad13a43fc8e2f1f83b95", "size": 1029, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o4.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o4.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/o4.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "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.1111111111, "max_line_length": 79, "alphanum_fraction": 0.6822157434, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6600956673596984}} {"text": "# ......................................................................................\n# ...............Exercise 13. Nonparametric tests, goodness-of-fit tests ...............\n# ..................Michal Béreš, Martina Litschmannová, Adéla Vrtková..................\n# ......................................................................................\n\n# If text does not display correctly, set File \\Reopen with Encoding ... to UTF-8 \n# Use CTRL + SHIFT + O to display the contents of the script \n# Use CTRL + ENTER to run commands on a single line \n\n# Conformance distribution probability testing of discrete NV(finite number of values) ####\n# - good agreement test\n# \n# - we test whether the measured data(their relative frequencies) agree with any\n# specific distribution(ie its probabilities)\n# \n# - we test using the $\\chi^2$ good match test\n# \n# - assumptions of the test:(ATTENTION relate to the expected frequencies - ie those\n# that we would monitor if the measured data were 100% according to the distribution in\n# the hypothesis)\n# \n# - Expected frequencies ≥ 2,\n# \n# - at least 80% of expected frequencies>5\n# \n# - test statistic(the one with $\\chi^2$ distribution) is $G = \\sum_{i = 1}^k (O_i -\n# E_i)^2 / E_i$\n# \n# - distribution has degree of freedom $df = k - 1 - h$\n# \n# - k is the number of options\n# \n# - h is the number of estimated parameters(this applies to incompletely specified\n# tests)\n# \n\n\n# example see example 1\n\n\n# * Good match test for a continuous random variable(or discrete with an infinite ####\n# number of values)\n# \n# - we have to convert to a table with a finite number of values\n# \n# - for discrete(eg poison) we group from a certain number of columns eg 4,5,6,... to \"4\n# and more\"\n# \n# - for continuous we produce a series of intervals and see how many values fall within\n# the given interval\n# \n# - eg:(- $\\infty$, 3),<3, 4),...,<10, $\\infty$)\n# \n# - then we have to calculate for each interval how many% of data belong to each\n# interval, thus obtaining a table of expected probabilities\n# \n# - we continue as before\n# \n# - there is a pearson.test(data) function from the nortest package to test the\n# normality of the distribution\n# \n\n\n# example 2,3,4\n\n\n# PivotTables ####\n# \n# - tables containing data depending on two factors\n# \n# - one of the factors is, as a rule, an independent variable in which we monitor\n# whether it affects the other factor(dependent variable)\n# \n# - The independent variable is usually in rows\n# \n# - is usually dependent in columns\n# \n# - beware the whole test examines the correlation, not the causality! Causality can be\n# assessed by \"expert\" evaluation\n# \n# - statistical conclusion: there is a statistically significant dependence between the\n# independent and dependent variable(correlation)\n# \n# - expert assessment: an independent variable statistically significantly affects the\n# dependent variable(causality)\n# \n\n\n# * PivotTable Visualization ####\n# \n# - visualization eg using the barplot function\n# \n# - pay attention to what rows and columns are, we always want individual divided\n# columns to be via independent variables(each column for one value of an independent\n# variable)\n# \n# - beside=T determines whether we want to merge adjacent columns into one split column\n# or not\n# \n# - preferred visualization using mosaicplot\n# \n# - the same as for barlot, the connected columns must be via independent variables\n# \n\n\n# examples in Examples 5,6,7\n\n\n# * Dependency table dependencies ####\n# \n# - Correlation coefficient CC\n# \n# - Corrected correlation coefficient CCcor\n# \n# - Cramer's coefficient V\n# \n# - we will use this first\n# \n# - cramersV(cont.tab) function from lsr package\n# \n\n\n# Examples in Examples 5,6,7\n\n\n# * PivotTable Dependency Test ####\n# \n# - $H_0:$ there is no dependency between an independent(eg is a smoker) and a\n# dependent(eg suffering from a disease) variable\n# \n# - $H_A: \\neg H_0$\n# \n# - chisq.test function(cont.tab)\n# \n# - assumptions: Expected frequencies ≥ 2, at least 80% of expected frequencies>5\n# \n# - expected frequencies can be found from chisq.test(cont.tab) \\ $ expected\n# \n\n\n# Association tables ####\n# \n# - this is a special PivotTable case\n# \n# - always has exactly 2 options for the dependent and exactly 2 options for the\n# independent variable\n# \n\n\n# * Mandatory form of the association table ####\n# \n# - Lines indicate independent variable options\n# \n# - the first line is the so-called exposed part of the population(the one exposed to\n# the phenomenon we study - eg smokers try to study the effects of smoking)\n# \n# - the second line is the unexposed part of the population\n# \n# - The columns indicate the options of the dependent variable\n# \n# - the first column indicates the occurrence of the phenomenon under investigation(eg\n# occurrence of the disease, product error,...)\n# \n# - the second column indicates the remainder - no occurrence of the investigated\n# phenomenon\n# \n\n\n# * Relative risk and odds ratio ####\n# \n# - Relative risk and odds ratio provide the same information, only in a different\n# format\n# \n# - all point IOs are calculated using the function epi.2by2(associ.tab) from the\n# package epiR\n# \n# - the function takes the association table as input, which must be in the correct\n# format!\n# \n\n\n# ** Relative risk ####\n# \n# - denotes $RR$\n# \n# - this is the risk ratio(probability of occurrence of the investigated phenomenon) in\n# exposed and unexposed populations\n# \n# - if it is equal to 1, it means the same probabilities of occurrence in exposed and\n# unexposed\n# \n# - if it is greater than 1 then the exposed population is more likely to occur\n# \n# - if less than 1 then the exposed population is less likely to occur\n# \n# - point estimate $\\hat{RR}$ is calculated as the ratio rel. frequency of the studied\n# phenomenon in exposed and unexposed populations\n# \n# - epi.2by2 provides interval estimates\n# \n# - if the IO does not contain the value 1 then there is a statistically significant\n# dependence between the dependent and independent variable\n# \n\n\n# ** Odds ratio ####\n# \n# - we denote $OR$\n# \n# - this is the ratio of chances(chance of occurrence of the studied phenomenon) in\n# exposed and unexposed populations\n# \n# - if it is equal to 1, it means the same chances of occurrence in exposed and\n# unexposed\n# \n# - if it is greater than 1 then the exposed population has a greater chance of\n# occurrence\n# \n# - if less than 1 then the exposed population has a lower chance of occurrence\n# \n# - point estimate $\\hat{OR}$ is calculated as the ratio of chances(selective) of the\n# studied phenomenon in exposed and unexposed population\n# \n# - epi.2by2 provides interval estimates\n# \n# - if the IO does not contain the value 1 then there is a statistically significant\n# dependence between the dependent and independent variable\n# \n\n\n# example in example 7\n\n\n# Examples(good match tests) ####\n# \n# * Example 1. ####\n# \n# The dice were rolled 6,000 times and the number of falling meshes was recorded.\n# [image.png](attachment:64f1169e-6bc1-470a-8afb-b282230c2c9f.png)\n# \n\n\n# H0: The cube is fair.(so all probabilities are 1/6)\n# Ha: The cube is not fair.(H0 negation)\n\nx = c(1,2,3,4,5,6)\nn.obs = c(979,1002,1015,980,1040,984)\np.exp = c(1/6,1/6,1/6,1/6,1/6,1/6)\nn.exp = 6000*p.exp\nn.exp # test assumptions must be checked\n# All expected frequencies are greater than 5.\n\n\nx.obs = sum(((n.obs-n.exp)^2)/n.exp)\nx.obs\n\np.hodnota = 1 - pchisq(x.obs,5)\np.hodnota\n\n# At the significance level of 0.05 we do not reject HO(p-value=0.711,\n# Chi-square test of independence, df=5).\n\n\n# * Example 2. ####\n# \n# The manufacturing company estimates the number of failures of a particular device in\n# 100 hours using a Poisson distribution with parameter 1.2. Employees recorded the\n# actual number of failures at a total of 150 100-hour intervals for inspection(results\n# are shown in the table). Verify with a clean significance test that the number of\n# failures of a given device within 100 hours actually has a Poisson distribution with\n# the parameter λt=1.2.\n# \n\n\n# Fully specified test\n\n# H0: The number of faults during 100 operating hours can be modeled\n# Poisson distribution with parameter 1.2.\n# Ha: The number of faults during 100 operating hours cannot be modeled\n# Poisson distribution with parameter 1.2.\n\nx = c(0,1,2,3,4)\nn.obs = c(52,48,36,10,4)\n\np.exp = dpois(x,1.2)\np.exp[5] = 1 - sum(p.exp[1:4])\np.exp\nsum(p.exp)\n\nn.exp = 150*p.exp\nn.exp # test assumptions must be checked\n# 4 of the 5 expected frequencies, ie 80%, are greater than 5.\n\n\nx.obs = sum(((n.obs-n.exp)^2)/n.exp)\nx.obs\n\np.hodnota = 1-pchisq(x.obs,4)\np.hodnota\n\n# At the significance level of 0.05 we do not reject HO(p-value=0.590,\n# Chi-square test of independence, df=4).\n\n\n# * Example 3. ####\n# \n# Employees recorded a total of 150 100-hour breakdowns at check(results are shown in\n# the table). Use a clean significance test to see if the number of failures in a given\n# device has a true Poisson distribution in 100 hours.
\n# ![Image.png](attachment:4da89057-87d1-4bcd-a488-3365237654f7.png)\n# \n\n\n# Incompletely specified test\n\n# H0: The number of faults during 100 operating hours can be modeled\n# Poisson distribution.\n# Ha: The number of faults during 100 operating hours cannot be modeled\n# Poisson distribution.\n\nx = c(0,1,2,3,4)\nn.obs = c(52,48,36,10,4)\n\nlambda.t = weighted.mean(x,n.obs) # Poisson distribution parameter estimate\nlambda.t\n\np.exp = dpois(x,lambda.t)\np.exp[5] = 1 - sum(p.exp[1:4])\np.exp\nsum(p.exp)\n\nn.exp = 150*p.exp\nn.exp # test assumptions must be checked\n# 4 out of 5 expected frequencies, ie 80%, are greater than 5.\n\n\nx.obs = sum(((n.obs-n.exp)^2)/n.exp)\nx.obs\n\np.hodnota = 1-pchisq(x.obs,3)\np.hodnota\n\n# At the significance level of 0.05 we do not reject HO(p-value=0.491,\n# Chi-square test of independence, df=3).\n\n\n# * Example 4. ####\n# \n# Time intervals(s) between the passages of individual vehicles were measured on the\n# motorway within a few minutes. The detected values of these distances are recorded in\n# the file dalnice.xlsx. Verify that this is data from a normal distribution(use a good\n# match test).\n# \n\n\n# automatic test of good agreement from continuous data\n\ndalnice = readxl::read_excel(\"data/neparametricke_hypotezy.xlsx\", sheet=2)\ncolnames(dalnice)=\"hodnoty\"\nhead(dalnice)\n\nmu = mean(dalnice$hodnoty)\nsigma = sd(dalnice$hodnoty)\nmu \nsigma\n\n# Generate values for the x-axis\nxfit=seq(from = -20, to = 30, length = 100) \n# Generate values for the y-axis\nyfit=dnorm(xfit, mean = mu, sd = sigma) \n\nhist(dalnice$hodnoty, freq = FALSE, xlim = c(-20, 30))\n# Add a curve to the last graph based on the values generated above\nlines(xfit, yfit, col=\"black\", lwd=2) \n\n# install.packages(\"nortest\")\n\n\n# H0: Spacing between vehicles can be modeled by normal distribution.\n# Ha: Spacing between vehicles cannot be modeled by normal distribution.\n\nnortest::pearson.test(dalnice$hodnoty)\n\n# Specify the number of degrees of freedom\npom = nortest::pearson.test(dalnice$hodnoty, n.classes = 5)\nattributes(pom)\n\npom$method\npom$n.classes\npom$df\npom$p.value\n\n# HO can be rejected at the significance level of 0.05(p-value<<0.001,\n# Chi-square test of good agreement, df=12).\n\n\n# test what you already know\nshapiro.test(dalnice$hodnoty)\n\n# Examples of PivotTable and Association Tables ####\n# \n# * Example 5. ####\n# \n# Decide on the basis of the data file experimentovani-s-telem.xls(Dudová, J. -\n# Experimentování s tělem(survey results), 2013. Available online at\n# http://experimentovani-stelem.vyplnto.cz), whether there is a connection between\n# gender of respondents and whether they have tattoos. Use Cramer V to assess the\n# contingency rate.\n# \n\n\ntet = readxl::read_excel(\"data/neparametricke_hypotezy.xlsx\", sheet=3)\nhead(tet)\n\ntet = tet[,c(6,10)]\ncolnames(tet) = c(\"pohlavi\",\"tetovani\")\nhead(tet)\n\n# Preprocessing\n# Variants of cat. Variables(factors) must be arranged and named so\n# how they should be arranged and named in the accounts. table\n\n\nkont.tab = table(tet$pohlavi, tet$tetovani)\nkont.tab\n\ncolnames(kont.tab) = c(\"má tetování\",\"nemá tetování\")\nkont.tab\n\n# Exploratory analysis\nprop.table(kont.tab) # associated relative frequencies\nprop.table(kont.tab,1) # line relative frequencies\nprop.table(kont.tab,2) # columnar relative frequencies\n\n\n# Visualization in standard R\n# Cluster bar graph\n# compare graphs, which of the graphs is more suitable for the presentation of the data\n\noptions(repr.plot.width = 12) # width of graphs in Jupyter\npar(mfrow = c(1, 2)) # matrix of 1x2 graphs\n\nbarplot(t(kont.tab),\n legend = colnames(kont.tab),\n beside = T)\n\nbarplot(kont.tab,\n legend = rownames(kont.tab),\n beside = T)\n\n# Stacked bar graph\n\noptions(repr.plot.width = 12) # width of graphs in Jupyter\npar(mfrow = c(1, 2)) # matrix of graphs 1x2\n\nbarplot(t(kont.tab),\n legend = colnames(kont.tab))\n\nbarplot(kont.tab,\n legend = rownames(kont.tab))\n\n# Mosaic chart\n\noptions(repr.plot.width = 8) # width of graphs in Jupyter\n\nmosaicplot(t(kont.tab),\n las = 1, # Rotate y-axis labels\n color = gray.colors(2))\n\n# compare which of the graphs is more suitable for the presentation of the given data\nmosaicplot(kont.tab,\n las = 1,\n color = gray.colors(2))\n\n# install.packages(\"lsr\")\n\n\n# Cramer V calculation ####\nlsr::cramersV(kont.tab)\n\n# PivotTable independence test\n\n# H0: Data is independent ->whether the individual is male or female\n# Does not affect his likelihood of having a tattoo\n# HA: negation H0(there is a dependency)\n\npom = chisq.test(kont.tab)\nattributes(pom)\n\npom$expected # Necessary for verification of assumptions\n# All expected frequencies are greater than 5.\n\n\npom\n\n# HO can be rejected at the significance level of 0.05(p-value=0.003,\n# Chi-square goodness-of-fit test, df=1).\n# The observed dependence can be assessed as weak(Cramer's V=0.121).\n\n\n# * Example 6. ####\n# \n# For a differentiated approach in personnel policy, the company's management needs to\n# know whether job satisfaction depends on whether it is a Prague plant or non-Prague\n# plants. The results of the survey are in the following table. Display the data using a\n# mosaic chart and, based on the independence test in the combination table, decide on\n# the dependence of job satisfaction on the company's location. To assess the\n# contingency rate, use Cramer V.
\n# ![Image.png](attachment:ebc6062c-1020-4fab-8855-6665d65d59a7.png)\n# \n\n\n# We do not have a data matrix, ie cont. we must enter the table \"manually\"\nkont.tab = matrix(c(10,25,50,15,20,10,130,40),\n nrow=2,byrow=T)\nrownames(kont.tab) = c(\"Praha\",\"Venkov\")\ncolnames(kont.tab) = c(\"velmi nespokojen\",\"spíše nespokojen\",\n \"spíše spokojen\",\"velmi spokojen\")\nkont.tab = as.table(kont.tab)\nkont.tab\n\n# Exploratory Analysis ####\nprop.table(kont.tab) # associated relative frequencies\nprop.table(kont.tab,1) # line relative frequencies\nprop.table(kont.tab,2) # columnar relative frequencies\n\n\n# Visualization in standard R\n# Mosaic chart\nmosaicplot(kont.tab,\n las = 1, # Rotate yo axis labels 90\n color = gray.colors(4))\n\n# Cramer V\nlsr::cramersV(kont.tab)\n\n# H0: There is no connection between job satisfaction and company location.\n# Ha: There is a connection between job satisfaction and the location of the company.\n\n# Chi-square PivotTable Independence Test ####\npom = chisq.test(kont.tab)\npom$expected\n# All expected frequencies are greater than 5.\n\n\npom\n\n# HO can be rejected at the significance level of 0.05(p-value<<0.001,\n# Chi-square test of good agreement, df=3).\n# The observed dependence can be assessed as moderate(Cramer's V=0.296)\n\n\n# * Example 7.(Association table) ####\n# \n# Between 1965 and 1968, a cohort study of cardiovascular disease under the Honolulu\n# Heart Program began monitoring 8,006 men, of whom 7,872 did not have a history of\n# stroke at the start of the study. Of this number, there were 3,435 smokers and 4,437\n# non-smokers. When followed for 12 years, 171 men in the group of smokers and 117 men\n# in the group of non-smokers suffered a stroke.\n# \n# *** a) ####\n# \n# Record the results in the association table.\n# \n\n\nkont.tab = matrix(c(171,3264,117,4320),nrow=2,byrow=T)\nrownames(kont.tab) = c(\"kuřák\",\"nekuřák\")\ncolnames(kont.tab) = c(\"ano\",\"ne\")\nkont.tab\n\n# completion of the table of absolute frequencies\nkont.tab.full = matrix(rep(0,9), nrow=3, ncol=3)\nrownames(kont.tab.full) = c(\"kuřák\", \"nekuřák\", \"sum\")\ncolnames(kont.tab.full) = c(\"ano\", \"ne\", \"sum\")\n\nkont.tab.full[1:2, 1:2] = kont.tab\nkont.tab.full[1:2, 3] = rowSums(kont.tab)\nkont.tab.full[3, 1:2] = colSums(kont.tab)\nkont.tab.full[3, 3] = sum(kont.tab) \nkont.tab.full\n\n# addition of the table of relative frequencies\nkont.tab.rel = matrix(rep(0,9), nrow=3, ncol=3)\nrownames(kont.tab.rel) = c(\"kuřák\", \"nekuřák\", \"sum\")\ncolnames(kont.tab.rel) = c(\"ano\", \"ne\", \"sum\")\n\nkont.tab.rel[1:2, 1:2] = prop.table(kont.tab)\nkont.tab.rel[1:2, 3] = rowSums(kont.tab.rel[1:2, 1:2])\nkont.tab.rel[3, 1:2] = colSums(kont.tab.rel[1:2, 1:2])\nkont.tab.rel[3, 3] = sum(kont.tab.rel[1:2, 1:2]) \nkont.tab.rel\n\n# *** b) ####\n# \n# Based on visual assessment, estimate the effect of smoking on the incidence of\n# cardiovascular disease.\n# \n\n\n# Visualization by mosaic graph in basic R\nmosaicplot(kont.tab,\n color = gray.colors(2))\n\n# Cramer V calculation ####\nlsr::cramersV(kont.tab)\n\n# According to the mosaic graph and Cramer's V(0.061) there is a connection between smoking\n# and the occurrence of apoplexy evaluated as very weak.\n\n\n# *** c) ####\n# \n# Determine the absolute risk of cardiovascular disease in smokers and non-smokers.\n# \n\n\n# risk=probability\nkont.tab.full\n\n# Smokers\n# Assumptions check\np = 171/3435\np\n\n9/(p*(1-p)) \n# OK(3,435>190.3)\n\n\n# Calculation of point and 95% Clopper-Pearson interval estimation\nprop.test(x = 171, n = 3435)\n\n# The smoker has an apoplexy risk of about 5.0%. 95% Clopper-Pearson\n# the interval estimate of this risk is 4.2% to 5.8%.\n\n\n# Non-smokers\n# Assumption check\np = 117/4437\np\n\n9/p/(1-p) \n# OK(4,437>350.6)\n\n\n# Calculation of point and 95% Clopper-Pearson interval estimation\nprop.test(117,4437)\n\n# In non-smokers, the risk of apoplexy is about 2.6%. 95% Clopper-Pearson\n# the interval estimate for this risk is 2.1% to 3.2%.\n\n\n# *** d) ####\n# \n# Determine the relative risk(including 95% of the interval estimate) of cardiovascular\n# disease in smokers and non-smokers. Explain the practical significance of the results\n# obtained.\n# \n\n\n# install.packages(\"epiR\")\n\n\nkont.tab\n\nepiR::epi.2by2(kont.tab)\n\n# Smokers have about 1.89 times higher risk of apoplexy than non-smokers. 95%\n# the interval estimate for this relative risk is 1.50 to 2.38.\n# According to the interval estimate of relative risk, it is clear that at the surface\n# significance 0.05 is a statistically significantly higher risk for smokers\n# apoplexy than in non-smokers.\n\n\n# *** e) ####\n# \n# Determine the absolute chances of cardiovascular disease in smokers and non-smokers.\n# \n\n\n# In a smoker, the chance of apoplexy is about 52: 1,000. at 1,052 smokers\n# about 52 occurrences of apoplexy can be expected.\n# In non-smokers, the chance of developing apoplexy is about 27: 1,000. for 1,027 non-smokers\n# approximately 27 occurrences of apoplexy can be expected.\n\n\n# *** f) Determine the relative chances of cardiovascular disease in smokers. ####\n# \n\n\n# Smokers have about 1.93(=0.0524/0.0271) times higher chance of apoplexy\n# than for non-smokers. 95% interval estimate of this ratio\n# the odds are 1.52 to 2.46.\n# According to the interval estimate of the odds ratio, it is clear that on the surface\n# Significance 0.05 is for smokers\n# statistically significantly higher chance of developing apoplexy than in non-smokers.\n\n\n# *** g) ####\n# \n# Decide at a significance level of 0.05 on the dependence of the incidence of\n# cardiovascular disease on smoking.\n# \n\n\n# Attention! The epi.2by2 command does not output the expected frequency for\n# Chi-square test of independence.\n# It is not possible to verify the test assumptions!\n\n# H0: There is no link between smoking and the occurrence of apoplexy.\n# Ha: There is a link between smoking and the occurrence of apoplexy.\n\npom = chisq.test(kont.tab)\npom$expected\n# All expected frequencies are greater than 5.\n\n\npom\n\nlsr::cramersV(kont.tab)\n\n# At the significance level of 0.05, HO can be rejected(p-value<<0.001,\n# Chi-square goodness-of-fit test,\n# df=1). The observed dependence can be assessed as very weak\n# Cramer's V=0.061).\n\n\n\n\n", "meta": {"hexsha": "d32c8501db0af112aa4bab717e1b6ef1b36f7369", "size": 20613, "ext": "r", "lang": "R", "max_stars_repo_path": "other/Exercise 13/T15_contingency_tables.r", "max_stars_repo_name": "Beremi/PS_eng_2022", "max_stars_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "other/Exercise 13/T15_contingency_tables.r", "max_issues_repo_name": "Beremi/PS_eng_2022", "max_issues_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "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": "other/Exercise 13/T15_contingency_tables.r", "max_forks_repo_name": "Beremi/PS_eng_2022", "max_forks_repo_head_hexsha": "178bc329f3d67aa3bf6d8d16356692525502a87d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:35:24.000Z", "avg_line_length": 28.2369863014, "max_line_length": 93, "alphanum_fraction": 0.7044098385, "num_tokens": 5776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6600625665988854}} {"text": "horner <- function(a, x) {\n y <- 0\n for(c in rev(a)) {\n y <- y * x + c\n }\n y\n}\n\ncat(horner(c(-19, 7, -4, 6), 3), \"\\n\")\n", "meta": {"hexsha": "8ab73ba33186c6fa6dfefcafaa757f62c59adc0b", "size": 126, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.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/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.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/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.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": 12.6, "max_line_length": 38, "alphanum_fraction": 0.3968253968, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6600625653374924}} {"text": " C02AGJ Example Program Results\n\n\n Example 1\n\n\n Degree of polynomial = 5\n\n Computed roots of polynomial\n\n z = -1.4918E+00\n z = 5.5169E-01 +/- 1.2533E+00*i\n z = -8.0579E-01 +/- 1.2229E+00*i\n\n\n Example 2\n\n Degree of polynomial = 5\n\n Computed roots of polynomial Error estimates\n (machine-dependent)\n\n z = -1.4918E+00 +0.0000E+00*i 7.4E-16\n z = 5.5169E-01 +1.2533E+00*i 1.1E-16\n z = 5.5169E-01 -1.2533E+00*i 1.1E-16\n z = -8.0579E-01 +1.2229E+00*i 3.0E-16\n z = -8.0579E-01 -1.2229E+00*i 3.0E-16\n", "meta": {"hexsha": "8e10c18e09f3c420166939fcbb860e68ff7bbeec", "size": 577, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/c02agje.r", "max_stars_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_stars_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-03T22:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T01:44:03.000Z", "max_issues_repo_path": "simple_examples/baseresults/c02agje.r", "max_issues_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_issues_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "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": "simple_examples/baseresults/c02agje.r", "max_forks_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_forks_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-03T22:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T01:00:53.000Z", "avg_line_length": 20.6071428571, "max_line_length": 51, "alphanum_fraction": 0.5563258232, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6600625613686453}} {"text": "\n# 4. faza: Analiza podatkov\n\n# Po desetletjih ###############################################################\n\npovprecne_starosti_tabela <- izvajalci_ostalo %>% \n mutate(Desetletje=(Leto%/%10*10)) %>%\n group_by(Desetletje) %>% \n summarise_at(vars(-c(Leto, \n Izvajalec, \n Ustanovitev, \n Izvor, \n Spol, \n Festival, \n Lokacija, \n Grofija)), \n funs(mean(., na.rm=TRUE)))\n\nmodel <- lm(Starost ~ Desetletje, data = povprecne_starosti_tabela)\nnovo_desetletje <- data.frame(Desetletje = 2020)\npredict(model, novo_desetletje)\nnapoved <- novo_desetletje %>% mutate(Starost = predict(model, .))\n\npovprecne_starosti <- ggplot(povprecne_starosti_tabela, \n aes(x = Desetletje, y = Starost)) +\n geom_point(color = 'darkgreen',\n size = 2) + \n geom_smooth(method = lm, formula=y~x, fullrange=TRUE) +\n geom_point(data=napoved, aes(x = Desetletje, y = Starost),\n color = 'red', \n size = 5) +\n labs(title = \"Povprečna starost izvajalcev - po desetletjih\")\n\n\n# Po letih ##################################################################### \n\npovprecne_starosti_tabela_leta <- izvajalci_ostalo %>% \n group_by(Leto) %>% \n summarise_at(vars(-c(Izvajalec, \n Ustanovitev, \n Izvor, \n Spol, \n Festival, \n Lokacija, \n Grofija)), \n funs(mean(., na.rm=TRUE)))\n\nmodel_leta <- lm(Starost ~ Leto, data = povprecne_starosti_tabela_leta)\nnova_leta <- data.frame(Leto = c(2018:2029))\npredict(model_leta, nova_leta)\nnapoved_leta <- nova_leta %>% mutate(Starost = predict(model_leta, .))\n\npovprecne_starosti_leta <- ggplot(povprecne_starosti_tabela_leta, \n aes(x = Leto, y = Starost)) +\n geom_point(color = 'darkgreen',\n size = 2) + \n geom_smooth(method = lm, formula=y~x, fullrange=TRUE) +\n geom_point(data=napoved_leta, aes(x = Leto, y = Starost),\n color = 'red', \n size = 2) + \n labs(title = \"Povprečna starost izvajalcev - po letih\")", "meta": {"hexsha": "7ec81e077d0dccd78744680c084151600dcf03d2", "size": 2260, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "oskarvavtar/APPR-2020-21", "max_stars_repo_head_hexsha": "cf1547883c167dfd45b7faaa72b402f490a9fce2", "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": "oskarvavtar/APPR-2020-21", "max_issues_repo_head_hexsha": "cf1547883c167dfd45b7faaa72b402f490a9fce2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-16T22:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-15T14:40:26.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "oskarvavtar/APPR-2020-21", "max_forks_repo_head_hexsha": "cf1547883c167dfd45b7faaa72b402f490a9fce2", "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.0491803279, "max_line_length": 82, "alphanum_fraction": 0.5185840708, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.659693154234084}} {"text": "#Q5. The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.\r\n#We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.\r\n#You are given that a2 = 512 and a10 = 614656.\r\n#Find a30.\r\n\r\nList a = new List();\r\n \r\nfor (int b = 2; b < 400; b++) {\r\n BigInteger value = b;\r\n for (int e = 2; e < 50; e++) {\r\n value *= b;\r\n \r\n if (DigitSum(value) == b) {\r\n a.Add(value); \r\n }\r\n if (a.Count > 50) break; \r\n }\r\n if (a.Count > 50) break; \r\n}", "meta": {"hexsha": "d2da5cd803a0c5b7cc88c376fd399a8e11bb909e", "size": 768, "ext": "r", "lang": "R", "max_stars_repo_path": "Q.5.r", "max_stars_repo_name": "Subr1ata/D.A.-Lab-Assignments", "max_stars_repo_head_hexsha": "75e9eab3483e8650bd0396b0e102c89d0533b1eb", "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": "Q.5.r", "max_issues_repo_name": "Subr1ata/D.A.-Lab-Assignments", "max_issues_repo_head_hexsha": "75e9eab3483e8650bd0396b0e102c89d0533b1eb", "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": "Q.5.r", "max_forks_repo_name": "Subr1ata/D.A.-Lab-Assignments", "max_forks_repo_head_hexsha": "75e9eab3483e8650bd0396b0e102c89d0533b1eb", "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.4210526316, "max_line_length": 195, "alphanum_fraction": 0.5390625, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6596013432638361}} {"text": "t=9\r\nv=16\r\nr=3\r\nsw2=2.847\r\nqvalue=qtukey(1-0.05,t,v)\r\nW=qvalue*sqrt(sw2/r)\r\nW\r\n # any pair of treatment means having a difference between corresponding\r\n#sample means exceeding 4.9 would be declared significantly different", "meta": {"hexsha": "e04b41a6222f4af7c6271afd35b87ff6256b6050", "size": 222, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.11/Ex15_11.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.11/Ex15_11.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH15/EX15.11/Ex15_11.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 24.6666666667, "max_line_length": 73, "alphanum_fraction": 0.7522522523, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6595645463038634}} {"text": "arithmeticMean <- function(a, b) { (a + b)/2 }\ngeometricMean <- function(a, b) { sqrt(a * b) }\n\narithmeticGeometricMean <- function(a, b) {\n rel_error <- abs(a - b) / pmax(a, b)\n if (all(rel_error < .Machine$double.eps, na.rm=TRUE)) {\n agm <- a\n return(data.frame(agm, rel_error));\n }\n Recall(arithmeticMean(a, b), geometricMean(a, b))\n}\n\nagm <- arithmeticGeometricMean(1, 1/sqrt(2))\nprint(format(agm, digits=16))\n", "meta": {"hexsha": "dfba6ab740d7fe0fea8949531bd404df123b6b67", "size": 424, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Arithmetic-geometric-mean/R/arithmetic-geometric-mean-1.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-geometric-mean/R/arithmetic-geometric-mean-1.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-geometric-mean/R/arithmetic-geometric-mean-1.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": 28.2666666667, "max_line_length": 57, "alphanum_fraction": 0.6367924528, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6595645446282944}} {"text": "divisors <- function (n) {\n Filter( function (m) 0 == n %% m, 1:(n/2) )\n}\n\ntable = sapply(1:19999, function (n) sum(divisors(n)) )\n\nfor (n in 1:19999) {\n m = table[n]\n if ((m > n) && (m < 20000) && (n == table[m]))\n cat(n, \" \", m, \"\\n\")\n}\n", "meta": {"hexsha": "da5bb9580ebc0c8c11d2b85af28e900d79d654e1", "size": 245, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Amicable-pairs/R/amicable-pairs.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Amicable-pairs/R/amicable-pairs.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/Amicable-pairs/R/amicable-pairs.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4166666667, "max_line_length": 55, "alphanum_fraction": 0.4816326531, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6587548717954063}} {"text": "# NOTE: This is the first thing I've ever written in R!\n# I had to learn R to solve this programming problem during the competition.\n# I'm very proud of this code.\n\nf <- file(\"stdin\")\non.exit(close(f))\n\nT <- readLines(f)\nT <- strsplit(T, \" \")\n\ntestcases <- as.numeric(T[[1]])\n\nfor(q in 1:testcases) {\n testcase_input = T[[q+1]]\n A = as.numeric(testcase_input[[1]])\n B = as.numeric(testcase_input[[2]])\n V = as.numeric(testcase_input[[3]])\n \n constants = pi/(4*A**2)\n f_of_y = function(x){\n return((4*A*log(x) + 2*B**2 - 2*B*sqrt(4*A*log(x)+B**2)))\n }\n \n goal = V\n accuracy = .2\n test_inp = 1\n test_result = integrate(f_of_y, 1, test_inp)[[1]]\n \n step_sizes = list(.01, .05, .1, .2, 1, 5, 10)\n step_pos = length(step_sizes)\n last_val = -1\n \n while (!((goal-accuracy) <= test_result && test_result <= (goal+accuracy))) {\n poss_new_val = integrate(f_of_y, 1, test_inp+step_sizes[[step_pos]])[[1]]*constants\n #print(step_pos)\n #print(poss_new_val)\n if (poss_new_val > goal+accuracy){\n if(step_pos != 1){\n step_pos = step_pos - 1\n next\n }\n } else {\n test_inp = step_sizes[[step_pos]] + test_inp\n test_result = poss_new_val\n }\n #print(\"last\")\n #print(last_val)\n #print(\"test\")\n #print(test_result)\n # Check if the code is getting stuck in a loop\n # If it is, break, since the actual value is nearby\n if(last_val == test_result){\n break\n }\n last_val = test_result\n }\n \n # Test to see if there's a better fit nearby\n ret = test_inp\n min_err = abs(V - test_result)\n \n # Make sure the range of the inputs fit the range of the problem/function\n left_bound = max(1, test_inp-.5)\n for(i in seq(left_bound, test_inp+.5, .01)){\n res = integrate(f_of_y, 1, i)[[1]]*constants\n err = abs(V-res)\n if(err < min_err){\n min_err = err\n ret = i\n }\n }\n \n ret = format(round(ret, 2), nsmall = 2)\n write(ret, stdout())\n}\n\n", "meta": {"hexsha": "ec9c2d32d4e11191a6ce437c90eee16ecb1329aa", "size": 2143, "ext": "r", "lang": "R", "max_stars_repo_path": "Super_Monkey_Challenge_IV/Vodka_Volume/vodka_volume_solution.r", "max_stars_repo_name": "christophergeiger3/Competition_Problems", "max_stars_repo_head_hexsha": "0bf99a5cd9b12c22c3dbf515cdb62ce8343f359b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-08T20:41:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-08T20:41:42.000Z", "max_issues_repo_path": "Super_Monkey_Challenge_IV/Vodka_Volume/vodka_volume_solution.r", "max_issues_repo_name": "christophergeiger3/Competition_Problems", "max_issues_repo_head_hexsha": "0bf99a5cd9b12c22c3dbf515cdb62ce8343f359b", "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": "Super_Monkey_Challenge_IV/Vodka_Volume/vodka_volume_solution.r", "max_forks_repo_name": "christophergeiger3/Competition_Problems", "max_forks_repo_head_hexsha": "0bf99a5cd9b12c22c3dbf515cdb62ce8343f359b", "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.8311688312, "max_line_length": 91, "alphanum_fraction": 0.5496966869, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.658413820507849}} {"text": "###########################################################################\n# Pricing European Put Options Through Simulated Levy Processes \n# Research proposed by Liming Feng, Zisheng Chen, and Xiong Lin\n# University of Illinois, Urbana-Champaign\n#\n# Created by Joseph Loss on 12/17/2018\n# Co-developers: Yuchen Duan (UIUC MSFE) and Daniel Liberman (UIC Finance)\n#\n# Algorithm 1: Simulating a Normal Inverse Gaussian process through a Brownian subordination\n#\n###########################################################################\n# set.seed(2017)\nlibrary(tictoc)\n\nno_of_simulations.1 <- 256 * 10 ^ 3\nno_of_simulations.2 <- (256 * 4) * 10 ^ 3\nno_of_simulations.3 <- (256 * 8) * 10 ^ 3\nno_of_simulations.4 <- (256 * 16) * 10 ^ 3\nno_of_simulations.5 <- (256 * 32) * 10 ^ 3\nno_of_simulations.6 <- (256 * 64) * 10 ^ 3\n\nno_of_simulations.list <- c(no_of_simulations.1, no_of_simulations.2, \n no_of_simulations.3, no_of_simulations.4, \n no_of_simulations.5, no_of_simulations.6)\n\nfor (i in 1:6)\n{\n # Input Parameters --------------------------------------------------------\n # taken from Feng et al, pg.22-23\n alpha = 15;\n beta = -5; \n delta = 0.5; \n r = 0.05; \n q = 0.02; \n s0 = 100; \n K = s0; \n T = 0.5; \n N = 1.0; \n \n # no_of_simulations = no_of_simulations.list[i]; # run through difference total no_of_simulations back-to-back\n no_of_simulations = no_of_simulations.3; # change number of iterations here\n \n # calculate mu using the formula given at the top of pg. 19\n mu = r - q + delta*(sqrt(alpha^2 - (beta+1)^2) - sqrt(alpha^2 - beta^2));\n \n # calculate gamma using the formula given in the Algorithm 1 pseudocode\n gamma = sqrt(alpha^2 - beta^2)\n \n stock_prc <- rep(0, no_of_simulations) # create array of possible stock_prices (1 for each iteration)\n put_prc <- rep(0, no_of_simulations) # create array of possible put_prices (1 for each iteration)\n call_prc <- rep(0, no_of_simulations) # create array of possible call_prices (1 for each iteration)\n euro_vanilla_put <- rep(0, no_of_simulations) \n nigv <- rep(0, no_of_simulations) # create NIG random vector\n \n # Box-Muller Function Template --------------------------------------------\n BoxMuller <- function() \n {\n n = 2 * N\n z = numeric(n)\n \n u1 = runif(n / 2, 0, 1)\n u2 = runif(n / 2, 0, 1)\n \n z1 = sqrt(-2 * log(u1)) * cos(2 * pi * u2) # half of normal variates\n z2 = sqrt(-2 * log(u1)) * sin(2 * pi * u2) # other half\n z[seq(1, n, by = 2)] = z1 # interleave\n z[seq(2, n, by = 2)] = z2 # two halves\n \n return(z1) # return half\n }\n \n \n # Algorithm 1: Normal Inverse Gaussian, Monte-Carlo Simulation --------------------------------------------\n for (j in 1:no_of_simulations) \n {\n # Step 1: Generate G1 and compute zeta --------------------------------------------------\n G1 <- BoxMuller() # generate standard normal random variable G1\n Z <- (G1^2)/gamma # compute Z\n \n zeta <- rep(0, N)\n for (i in 1:N) \n {\n zeta[i] = (1/gamma)*((delta*T) + (0.5*Z[i]) - sqrt((delta*T*Z[i]) + (Z[i]^2)/4)) \n }\n \n \n # Step 2: Generate uniform random variable U on (0,1) -----------------------------------\n Uniform <- function() # function to generate uniform r.v. using Algorithm 1, Step 2, on pg. 17\n {\n U = runif(N, 0, 1)\n zt <- rep(0, N)\n for (i in 1:N) \n {\n if (U[i] < (delta*T) / ((delta*T) + gamma * zeta[i])) {\n zt[i] = zeta[i]\n } else {\n zt[i] = (delta ^ 2 * T^2) / (gamma ^ 2 * zeta[i])\n }\n }\n return(zt)\n }\n \n zt = Uniform() # generate zt using uniform function above\n \n \n # Step 3: Generate StdNorm variable G2 -------------------------------------------------\n G2 <- rnorm(1,0,1)\n \n St <- rep(0, N) # create empty vector for St\n Xt <- rep(0, N) # create empty vector for Xt \n \n for (i in 1:N)\n {\n Xt[i] = mu * T + beta * zt[i] + sqrt(zt[i]) * G2[i] # compute Xt = mu*t + beta*zt + sqrt(zt)*G2\n St[i] = s0 * exp(Xt[i]) # from pg 16. compute St = S0 * e^(Xt)\n }\n \n stock_prc[j] = St[N] # reassign variable, ie St = ST (stock value at maturity)\n put_prc[j] = exp(-r*T) * max(0, K - stock_prc[j]) # compute put price at maturity \n call_prc[j] = exp(-r*T) * max(0, stock_prc[j] - K) # compute call price at maturity\n nigv[j] = Xt[N] \n \n \n # Section 5.4, pg.19: European Vanilla Options -------------------------------------------\n # We also calculate the option value \"V\" using the formula given in Section 5.4.\n \n # note that the resulting output is identical \n # to the result we generated through St = S0 * e^(Xt) above. \n euro_vanilla_put[j] = s0 * exp(-r * T) * max(0, K/s0 - exp(log(stock_prc[j] / s0)))\n \n }\n # END MonteCarlo Simulation --------------------------------------------------------------\n # ----------------------------------------------------------------------------------------\n}\n \n # Average the computed prices: -----------------------------------------------------------\n \"NIG Stock Price (t=T)\"\n sum(stock_prc) / no_of_simulations\n \n NIG_Put_Value <- sum(euro_vanilla_put) / no_of_simulations\n \"NIG Put Value: \" \n NIG_Put_Value\n \n # NIG_Put_Prc <- sum(put_prc) / no_of_simulations\n # \"NIG Put Value: \"\n # NIG_Put_Prc\n # euro_vanilla_put.value <- sum(euro_vanilla_put) / no_of_simulations\n # \"European Vanilla Put Value: \"\n # euro_vanilla_put.value\n \n # values.table <- cbind(NIG_Put_Prc, euro_vanilla_put.value)\n # values.table\n \n toc(log = TRUE)\n tic.clearlog()\n tic.clear()\n\n\n\n# Model Benchmarking & Verification ------------------------------------------------------------------\n# NIG Verification --------------------------------------------------------\nlibrary(GeneralizedHyperbolic) # testing our NIG model with GeneralizedHyperbolic built-in \"rnig\"\n\nGenHyp.NIG <- rnig(no_of_simulations, delta=delta, alpha=alpha, beta=beta)+mu\nalgo1.NIG <- nigv\n\npar(mfrow=c(1,2)) # Plot NIG distributions\n\n# GeneralizedHyperbolic NIG Histogram\nGenHyp.NIG.hist <-\n hist(GenHyp.NIG,\n breaks = 40,\n col = \"grey\",\n main = \"GeneralizedHyperbolic NIG\")\nxfit <- seq(min(GenHyp.NIG), max(GenHyp.NIG), length = 40)\nyfit <- dnorm(xfit, mean = mean(GenHyp.NIG), sd = sd(GenHyp.NIG))\nyfit <- yfit * diff(GenHyp.NIG.hist$mids[1:2]) * length(GenHyp.NIG)\nlines(xfit, yfit, col = \"blue\", lwd = 3)\n\n# Algorithm 1 NIG Histogram\nalgo1.NIG.hist <-\n hist(algo1.NIG,\n breaks = 40,\n col = \"grey\",\n main = \"Algorithm 1 NIG\")\nxfit <- seq(min(algo1.NIG), max(algo1.NIG), length = 40)\nyfit <- dnorm(xfit, mean = mean(algo1.NIG), sd = sd(algo1.NIG))\nyfit <- yfit * diff(algo1.NIG.hist$mids[1:2]) * length(algo1.NIG)\nlines(xfit, yfit, col = \"blue\", lwd = 3)\n\n\n# NIG Mean Comparison\nGenHyp.NIG.mu <- (mean(rnig(no_of_simulations, delta=delta, alpha=alpha, beta=beta)+mu))\nGenHyp.NIG.mu\nalgo1.NIG.mu = mean(nigv) # our NIG \nalgo1.NIG.mu\n\nnig_comparison_table <- cbind(algo1.NIG.mu, GenHyp.NIG.mu)\nnig_comparison_table\n\n(algo1.NIG.mu - GenHyp.NIG.mu)/GenHyp.NIG.mu # computed difference in model means\n\nnig_comparison_table\n\n# RQuantLib::EuropeanOption('put',s0,K,q,r,T,0.191)\n", "meta": {"hexsha": "938998c405399cf7d5739d658b3371fab6b0985e", "size": 7572, "ext": "r", "lang": "R", "max_stars_repo_path": "source/algo1_NIG_final.r", "max_stars_repo_name": "chicago-joe/Option-Pricing-via-Levy-Models-in-R", "max_stars_repo_head_hexsha": "308d066349228b6b5c5e913f7109dbf6b897bedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-03-07T23:08:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T18:04:56.000Z", "max_issues_repo_path": "source/algo1_NIG_final.r", "max_issues_repo_name": "chicago-joe/Option-Pricing-via-Levy-Models-in-R", "max_issues_repo_head_hexsha": "308d066349228b6b5c5e913f7109dbf6b897bedb", "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/algo1_NIG_final.r", "max_forks_repo_name": "chicago-joe/Option-Pricing-via-Levy-Models-in-R", "max_forks_repo_head_hexsha": "308d066349228b6b5c5e913f7109dbf6b897bedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-09-29T03:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-14T18:57:32.000Z", "avg_line_length": 36.7572815534, "max_line_length": 118, "alphanum_fraction": 0.530375066, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6583735408376564}} {"text": "N0 <- 100\ny0 <- 10\n\nlibrary(rstan)\nrstan_options(auto_write = TRUE)\n\noptions(mc.cores = 4)\nrstan:::rstudio_stanc(\"stan/simple_bernoulli_prior.stan\")\n\n#### Sampling from the \"prior\"\ncompiled.model.prior <- stan_model(\"stan/simple_bernoulli_prior.stan\")\n\ncc <- 1/2\ndd <- 1/2\nbb.data <- list(\n N0 = N0,\n y0 = y0,\n c = cc,\n d = dd,\n a_0 = .4\n)\n\nprior.bern <- sampling(compiled.model.prior, data = bb.data)\nprior.bern\n\npairs(prior.bern)\n\nlog.c_a0 <- bridgesampling::bridge_sampler(prior.bern)\n\nget_c_a0_bernoulli <- function(y0, n0, cc, dd, a_0){\n ans <- lbeta(a_0 * y0 + cc, a_0 *(n0 -y0) + dd)\n return(ans)\n}\n\nget_c_a0_bernoulli(\n y0 = bb.data$y0,\n n0 = bb.data$N0,\n cc = bb.data$c,\n dd = bb.data$d,\n a_0 = bb.data$a_0\n)\nlog.c_a0\n\nanaughts <- seq(0, 2, length.out = 100)\nc_a0 <- function(x) {\n get_c_a0_bernoulli(\n y0 = bb.data$y0,\n n0 = bb.data$N0,\n cc = bb.data$c,\n dd = bb.data$d,\n a_0 = x\n )\n} \nMaLs <- sapply(anaughts, c_a0)\n\nplot(anaughts, MaLs, xlab = expression(a[0]), main = \"Bernoulli\",\n ylab = expression(log(c(a[0]))), type = \"l\")\n\nplot(anaughts, exp(MaLs), xlab = expression(a[0]),\n ylab = \"Marginal likelihood\", type = \"l\")\n\n#####################\n####### Posterior using unnormalised power prior\n#####################\n\n## New data\n### will draw from the same process for simplicity\nN <- 1000\ny <- 200\n\ncompiled.model.unnorm.posterior <- stan_model(\"stan/simple_bernoulli_posterior_unnormalised.stan\")\n\ndelta <- 1\nnu <- 1\nbb.data.forposterior <- list(\n N0 = N0,\n y0 = y0,\n c = cc,\n d = dd,\n delta = delta,\n nu = nu,\n N = N,\n y = y\n)\n\nunnorm.posterior.bern <- sampling(compiled.model.unnorm.posterior, data = bb.data.forposterior)\nunnorm.posterior.bern\npairs(unnorm.posterior.bern, pars = c(\"a_0\", \"theta\"))\n\n### Now the normalised prior\n\ncompiled.model.norm.posterior <- stan_model(\"stan/simple_bernoulli_posterior_normalised.stan\")\n\nnorm.posterior.bern <- sampling(compiled.model.norm.posterior, data = bb.data.forposterior)\nnorm.posterior.bern\npairs(norm.posterior.bern, pars = c(\"a_0\", \"theta\", \"lp__\"))\n\n##### Analysis of p(a_0 | data)\na0.unnorm <- extract(unnorm.posterior.bern, 'a_0')$a_0\na0.norm <- extract(norm.posterior.bern, 'a_0')$a_0\n\na0.dt <- data.frame(a0 = c(a0.unnorm, a0.norm),\n normalisation = c( rep(\"unnormalised\", length(a0.unnorm)),\n rep(\"normalised\", length(a0.norm)) )\n)\n\nlibrary(ggplot2)\nggplot(a0.dt, aes(x = a0, fill = normalisation, colour = normalisation)) +\n geom_density() +\n stat_function(fun = function(x) dbeta(x, delta, nu),\n geom = \"line\", colour = \"black\", linetype = \"longdash\") + \n ggtitle(\"Bernoulli\") +\n facet_grid(normalisation~., scales = \"free\") +\n scale_y_continuous(\"Density\", expand = c(0, 0)) +\n scale_x_continuous(expression(a[0]), expand = c(0, 0)) +\n theme_bw()\n", "meta": {"hexsha": "b2eeb03080f2dd8fb9da5a25ae78816d5181948f", "size": 2859, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Bernoulli/simple_Bernoulli.r", "max_stars_repo_name": "maxbiostat/propriety_power_priors", "max_stars_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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/Bernoulli/simple_Bernoulli.r", "max_issues_repo_name": "maxbiostat/propriety_power_priors", "max_issues_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-29T19:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-29T15:58:08.000Z", "max_forks_repo_path": "code/Bernoulli/simple_Bernoulli.r", "max_forks_repo_name": "maxbiostat/propriety_power_priors", "max_forks_repo_head_hexsha": "43a9dc7bd007d5647bc453cd8a875e82c16ad6eb", "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": 24.4358974359, "max_line_length": 98, "alphanum_fraction": 0.6330884925, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.658373534950207}} {"text": "closest_pair_brute <-function(x,y,plotxy=F) {\n xy = cbind(x,y)\n cp = bruteforce(xy)\n cat(\"\\n\\nShortest path found = \\n From:\\t\\t(\",cp[1],',',cp[2],\")\\n To:\\t\\t(\",cp[3],',',cp[4],\")\\n Distance:\\t\",cp[5],\"\\n\\n\",sep=\"\")\n if(plotxy) {\n plot(x,y,pch=19,col='black',main=\"Closest Pair\", asp=1)\n points(cp[1],cp[2],pch=19,col='red')\n points(cp[3],cp[4],pch=19,col='red')\n }\n distance <- function(p1,p2) {\n x1 = (p1[1])\n y1 = (p1[2])\n x2 = (p2[1])\n y2 = (p2[2])\n sqrt((x2-x1)^2 + (y2-y1)^2)\n }\n bf_iter <- function(m,p,idx=NA,d=NA,n=1) {\n dd = distance(p,m[n,])\n if((is.na(d) || dd<=d) && p!=m[n,]){d = dd; idx=n;}\n if(n == length(m[,1])) { c(m[idx,],d) }\n else bf_iter(m,p,idx,d,n+1)\n }\n bruteforce <- function(pmatrix,n=1,pd=c(NA,NA,NA,NA,NA)) {\n p = pmatrix[n,]\n ppd = c(p,bf_iter(pmatrix,p))\n if(ppd[5] F_critical_value){\n print(\"Reject de null hyphotesis\")\n}else{\n print(\"No reject de null hyphotesis\")\n}\n\n", "meta": {"hexsha": "72a432d6f60040fd04f9b4da420a82e8a7f896ff", "size": 850, "ext": "r", "lang": "R", "max_stars_repo_path": "hypothesis-F-distribution.r", "max_stars_repo_name": "samuxiii/r-projects", "max_stars_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "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": "hypothesis-F-distribution.r", "max_issues_repo_name": "samuxiii/r-projects", "max_issues_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "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": "hypothesis-F-distribution.r", "max_forks_repo_name": "samuxiii/r-projects", "max_forks_repo_head_hexsha": "13a17bdf5a3db2efcf785c4810bb55c86459bfb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-06-24T17:18:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T03:39:37.000Z", "avg_line_length": 26.5625, "max_line_length": 81, "alphanum_fraction": 0.6752941176, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6574181899686087}} {"text": "# compute the expected vaccine efficacy against breakthrough infections that is\n# due to a reduction in the case attributable fraction\n\n# do this so that we can compare it against the estimated overall vaccine\n# efficacy against breakthrough infections\n\n# then compute correction factors to the infectiousness for vaccinated cases in\n# each of the 4 combinations of vaccine type and number of doses\n\n# p_s = proportion symptomatic among unvaccinated infections\n\n# p_s_star = proportion symptomatic among vaccinated infections\n\n# VE_s = vaccine efficacy (% reduction) against symptomatic disease\n\n# VE_o = vaccine efficacy (% reduction) against onward infectiousness of\n# breakthrough infections\n\n# VE_o(s) = vaccine efficacy (% reduction) against onward infectiousness of\n# breakthrough infections, that is mediated by reductions in the fraction\n# symptomatic\n\n# absolute infectiousness (z is a transmission probability) of all unvaccinated\n# people (symptomatic or asymptomatic)\n# z * (p_s + (1 - p_s) / 2)\n\n# absolute infectiousness (z is a transmission probability) of all vaccinated\n# people (symptomatic or asymptomatic)\n# z * (p_s_star + (1 - p_s_star) / 2)\n\n# relative infectiousness of vaccinated versus unvaccinated (breakthrough)\n# infections\n# (z * (p_s_star + (1 - p_s_star) / 2)) / (z * (p_s + (1 - p_s) / 2))\n# = (p_s_star + (1 - p_s_star) / 2) / (p_s + (1 - p_s) / 2)\n# = (1 + p_s_star) / (1 + p_s)\n\n# proportion symptomatic among vaccinated infections\n# p_s_star = p_s * (1 - VE_s)\n\n# correction is the multiplier for reduction in onward transmission we want,\n# divided by the one expected via reduction in symptomatics\n# correction = ((1 - VE_o) / (1 - VE_o_s))\n\n# this ^ can be multiplied by the probability of infection (by age bin, vaccine\n# type, vaccine doses) to adjust it ot the correct value\n\nlibrary(tidyverse)\n\nefficacies <- tibble::tribble(\n ~vaccine, ~dose, ~ve_infection, ~ve_symptom, ~ve_onward,\n \"pfizer\", 1, 30, 33, 46,\n \"pfizer\", 2, 79, 83, 65,\n \"AZ\", 1, 18, 33, 48,\n \"AZ\", 2, 60, 61, 65\n) %>%\n mutate(\n across(\n starts_with(\"ve\"),\n ~./100\n )\n )\n\nclinical_fractions <- structure(\n list(\n age_group_5y = c(\"0-4\", \"5-9\", \"10-14\", \"15-19\", \n \"20-24\", \"25-29\", \"30-34\", \"35-39\", \"40-44\", \"45-49\", \"50-54\", \n \"55-59\", \"60-64\", \"65-69\", \"70-74\", \"75-79\", \"80+\"),\n clinical_fraction_mean = c(\n 0.29, \n 0.29, 0.21, 0.21, 0.27, 0.27, 0.33, 0.33, 0.4, 0.4, 0.49, 0.49, \n 0.63, 0.63, 0.69, 0.69, 0.69\n )\n ),\n row.names = c(NA, -17L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nclinical_fractions %>%\n left_join(\n efficacies,\n by = character()\n ) %>%\n rename(\n clinical_fraction_unvacc = clinical_fraction_mean\n ) %>%\n mutate(\n clinical_fraction_vacc = clinical_fraction_unvacc * (1 - ve_symptom),\n ve_onward_via_symptom = 1 - ((1 + clinical_fraction_vacc) / (1 + clinical_fraction_unvacc)),\n onward_correction = ((1 - ve_onward) / (1 - ve_onward_via_symptom))\n ) %>%\n relocate(\n clinical_fraction_unvacc, .after = clinical_fraction_vacc\n ) %>%\n relocate(\n ve_onward_via_symptom, .after = ve_onward\n )\n\n# p_s <- seq(0.1, 0.9, by = 0.1)\n# VE_s <- efficacies$ve_symptom[2]\n# VE_o <- efficacies$ve_onward[2]\n# p_s_star = p_s * (1 - VE_s)\n# VE_o_s <- 1 - ((1 + p_s_star) / (1 + p_s))\n# correction <- ((1 - VE_o) / (1 - VE_o_s))", "meta": {"hexsha": "e6bfd259e208027f5f8a8431d9917c62417744c9", "size": 3514, "ext": "r", "lang": "R", "max_stars_repo_path": "R0Trial/vaccine_efficacy_R.r", "max_stars_repo_name": "aus-covid-modelling/AgentBasedModel", "max_stars_repo_head_hexsha": "14b78117332a33b96d9ffcc04963f8986abed82c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T13:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T13:51:38.000Z", "max_issues_repo_path": "R0Trial/vaccine_efficacy_R.r", "max_issues_repo_name": "aus-covid-modelling/AgentBasedModel", "max_issues_repo_head_hexsha": "14b78117332a33b96d9ffcc04963f8986abed82c", "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": "R0Trial/vaccine_efficacy_R.r", "max_forks_repo_name": "aus-covid-modelling/AgentBasedModel", "max_forks_repo_head_hexsha": "14b78117332a33b96d9ffcc04963f8986abed82c", "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.1165048544, "max_line_length": 96, "alphanum_fraction": 0.6340352874, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6573104033273612}} {"text": "#ganancias\n#lazo abierto, sistema planta 1\nTo<-1.080\nKp<-25.51\nTp<-15.0423\n#Ganancia proporcional\nGanP<-function(Tp,Kp,To){\n return(Tp/(Kp*To))\n}\nGanPr<-GanP(Tp,Kp,To)\nGanPr\n#Kp en ganancia integral\nGanI<-function(Tp,Kp,To){\n return((0.9*Tp)/(Kp*To))\n}\n#PI\nGanIn<-GanI(Tp,Kp,To)\nGanIn\n#tiempo de la integral\nTin<-3.33*To\nTin\n#Kp en ganancia derivativa\nGanD<-function(Tp,Kp,To){\n return((0.9*Tp)/(Kp*To))\n}\n#PID\nGanPID<-GanD(Tp,Kp,To)\nGanPID\n#Tiempo integral en derivaticva\nTip<-2*To\nTip\n#Tiempo derivativo\nTd<-0.5*To\nTd\n\nKI<-GanIn/Tin\nKI\n\nK<-GanPID/Tip\nK\nKD<-GanPID*Td\nKD\n\n#para un sistema planta 2 en lazo cerrado\nKu<-1.749\nTu<-1.2\nGaP<-0.5*Ku\nGaP\n\nGi<-0.45*Ku\nGi\n\nGd<-0.6*Ku\nGd\n\n#Tiempo integral\n#Para un PI\ntpi<-Tu/1.2\ntpi\n\n#Para la acción derivadiva\ntid<-Tu/2\ntid\n#Tiempo derivativo\ntpid<-Tu/8\ntpid\n\nKp<-GaP\nKp\n\nKi<-Gi/tpi\nKi\n\nkid<-Gd/tid\nkid\n\nKd<-Gd*tpid\nKd\n\n", "meta": {"hexsha": "d0189e768b18a722310964d7e51abde2c4d2e6b0", "size": 867, "ext": "r", "lang": "R", "max_stars_repo_path": "Practica 1 y 2/Parte 2 practica/2.2.2/LazoCerradoYAbierto.r", "max_stars_repo_name": "rocgar08/IAAC-2018-2019", "max_stars_repo_head_hexsha": "94424432de65601142a7bb0c35bcc5c140f949da", "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": "Practica 1 y 2/Parte 2 practica/2.2.2/LazoCerradoYAbierto.r", "max_issues_repo_name": "rocgar08/IAAC-2018-2019", "max_issues_repo_head_hexsha": "94424432de65601142a7bb0c35bcc5c140f949da", "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": "Practica 1 y 2/Parte 2 practica/2.2.2/LazoCerradoYAbierto.r", "max_forks_repo_name": "rocgar08/IAAC-2018-2019", "max_forks_repo_head_hexsha": "94424432de65601142a7bb0c35bcc5c140f949da", "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": 10.8375, "max_line_length": 41, "alphanum_fraction": 0.6897347174, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6571028181873192}} {"text": "#!/usr/bin/env Rscript\n\n# NOTE: fOptions uses non-standard definition of cost of carry: b = interestrate - carryrate, i.e. the adjusted drift κ in the geometric Brownian motion:\n# dS_t = (κ - σ^2/2) S_t dt + σ S_t dW_t\n\nlibrary(fOptions)\n\ndf = Reduce(function(x,y) merge(x,y,all=TRUE),\n list(data.frame(startprice=c(80,100,120)),\n data.frame(strikeprice=c(80,100,120)),\n data.frame(days=c(50,120)),\n data.frame(interestrate=c(0.05,0.07)),\n data.frame(carryrate=c(0.0,0.025)),\n data.frame(sigma=c(0.05,0.1,0.5))\n ))\n\nbs = df\n\nfor (type in c(\"c\",\"p\")) {\n bs[type] = with(bs,\n GBSOption(TypeFlag = type, S = startprice, X = strikeprice, Time = days/365,\n r = interestrate, b = interestrate - carryrate, sigma = sigma)@price)\n}\n\nwrite.csv(bs,\"bs.csv\",row.names=FALSE)\n\n\ncrr = merge(df,data.frame(nsteps=c(20,100)),all=TRUE)\nfor (otype in c(\"ce\",\"pe\",\"ca\",\"pa\")) {\n crr[otype] = with(crr,\n sapply(mapply(CRRBinomialTreeOption,TypeFlag = otype, S = startprice, X = strikeprice, Time = days/365,\n r = interestrate, b = interestrate - carryrate, sigma = sigma, n=nsteps),\n function(x) x@price))\n}\n\nwrite.csv(crr,\"crr.csv\",row.names=FALSE)\n\ntian = merge(df,data.frame(nsteps=c(20,100)),all=TRUE)\nfor (otype in c(\"ce\",\"pe\",\"ca\",\"pa\")) {\n tian[otype] = with(tian,\n sapply(mapply(TIANBinomialTreeOption,TypeFlag = otype, S = startprice, X = strikeprice, Time = days/365,\n r = interestrate, b = interestrate - carryrate, sigma = sigma, n=nsteps),\n function(x) x@price))\n}\nwrite.csv(tian,\"tian.csv\",row.names=FALSE)\n\njr = merge(df,data.frame(nsteps=c(20,100)),all=TRUE)\nfor (otype in c(\"ce\",\"pe\",\"ca\",\"pa\")) {\n tian[otype] = with(jr,\n sapply(mapply(JRBinomialTreeOption,TypeFlag = otype, S = startprice, X = strikeprice, Time = days/365,\n r = interestrate, b = interestrate - carryrate, sigma = sigma, n=nsteps),\n function(x) x@price))\n}\nwrite.csv(tian,\"jr.csv\",row.names=FALSE)\n", "meta": {"hexsha": "b14497635a315e7ea37bfffd0adab3fed9ace8aa", "size": 2284, "ext": "r", "lang": "R", "max_stars_repo_path": "test/ref.r", "max_stars_repo_name": "alecloudenback/Miletus.jl", "max_stars_repo_head_hexsha": "5863620f254fe234001e815d03ef603df0204a1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2019-05-18T12:52:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T18:27:10.000Z", "max_issues_repo_path": "test/ref.r", "max_issues_repo_name": "alecloudenback/Miletus.jl", "max_issues_repo_head_hexsha": "5863620f254fe234001e815d03ef603df0204a1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-09T02:20:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T16:11:04.000Z", "max_forks_repo_path": "test/ref.r", "max_forks_repo_name": "alecloudenback/Miletus.jl", "max_forks_repo_head_hexsha": "5863620f254fe234001e815d03ef603df0204a1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-05-18T19:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T12:25:00.000Z", "avg_line_length": 41.5272727273, "max_line_length": 153, "alphanum_fraction": 0.5560420315, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6568824215901327}} {"text": "=begin\n[(())] [(())]\n= Algebra\n Version: 0.72 (2006.09.14)\n Author: Shin-ichiro HARA (sinara@blade.nagaokaut.ac.jp)\n\nThis is a library of one-variate and multi-variate polynomials.\n\n== 0. First Step\n\nBegin with 'require \"algebra\"'.\n\n require \"algebra\"\n x = Polynomial(Integer, \"x\").var\n puts( (x+1)**7 )\n #=> x^7 + 7x^6 + 21x^5 + 35x^4 + 35x^3 + 21x^2 + 7x + 1\n puts( (x**7 + 7*x**6 + 21*x**5 + 35*x**4 + 35*x**3 + 21*x**2 + 7*x + 1).factorize )\n #=> (x + 1)^7\n\n== 1. Samples\n\n* (())\n\n== 2. Class and Module\n\n * (()) (Module of Algebra)\n * (()) (Class of Polynomial Ring)\n * (()) (Eulcidian Ring Module)\n * (()) (Multi-variate Polynomial Ring Class)\n * (()) (Residue Class Ring Class)\n * (()) (Algebraic Extension Class)\n * (()) (Localized Ring Class)\n * (()) (Matrix Algebra Class)\n * (()) (evaluation of algebraic strings)\n * (()) (Sets)\n * (()) (Maps)\n * (()) (Groups)\n * (()) (PermutationGroups)\n\n== 3. Other\n\n * (()) (Elementary Divisor Module)\n * (()) (Jordan Matrix Class)\n * (()) (Triplete of Matrices Class)\n * (())\n * (())\n\n== 4. Contents of package\n\n=== General\n algebra.rb File for using Algebra libraries\n\n=== One variate polynomial\n polynomial.rb Class of one variate polynomial\n euclidian-ring.rb Module of Euclidian domain\n polynomial-factor.rb Factorization:\n polynomial-factor-int.rb Integer version\n polynomial-factor-zp.rb Zp version\n polynomial-factor-alg.rb Algebraic number version\n\n=== Multi variate polynomial\n m-polynomial.rb Class of multi-variate polynomial\n m-index.rb Class of indices of degrees\n m-polynomial-factor.rb Factorization:\n m-polynomial-factor-int.rb Integer version\n m-polynomial-factor-zp.rb Zp version\n groebner-basis.rb Module of Groebner basis\n groebner-basis-coeff.rb Module of division by Groebner basis\n\n=== Foundation\n finite-set.rb Sets\n finite-map.rb Maps\n finite-group.rb Groups\n permutation-group.rb Permutation Groups\n\n=== Common part\n numeric-supplement.rb Supplement of Numeric\n prime-gen.rb Class of prime numbers\n polynomial-converter.rb Conversions between polynomial classes\n algebraic-parser.rb Evaluation of strings\n algebra-system.rb Common specification of algebras\n\n=== General algebra\n localized-ring.rb Quotient fields\n matrix-algebra.rb Matrix\n elementary-divisor.rb Elementary Divisor Class\n matrix-algebra-triplet.rb Triplet of Matrices Class\n jordan-form.rb Jordan Block Class\n residue-class-ring.rb Residue class ring\n algebraic-extention-field.rb Algebraic Extention Field of Polynomial\n splitting-field.rb Minimal Splitting Field of Polynomial\n galois-group.rb Galois Group of Polynomial\n linear-algebra.rb library for linear algebra\n algebraic-equation.rb library for algebraic equation\n\n=== Others\n array-supplement.rb Supplement of Array\n doc/ English Manuals(RD, HTML, TXT)\n doc-ja/ Japanese Manuals(RD, HTML, TXT)\n sample/ Sample Codes\n work/ (working directory for the developer)\n\n== 5. ToDo\n#<<< todo.rd\n* (())\n\n== 6. Changes\n#<<< changes.rd\n* (())\n\n=end\n\n", "meta": {"hexsha": "3c903c4e7ccad7918ec84544d355737d818d7e9b", "size": 4286, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/index.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/index.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/index.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.9292035398, "max_line_length": 106, "alphanum_fraction": 0.6810545964, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6568514396908055}} {"text": "#' sunposition\n#'\n#' @description Function to assess sun azimuth and elevation given the time in GMT format.\n#' \n#' @param timenow time indicat in time format equivalent to \"POSIXct\" or \"POSIXt\" object.\n#' @param lat numeric latitude in decimal degrees\n#' @param lon numeric longitude in decimal degrees\n#' @references \n#' Istituto di Biometeorologia Firenze Italy\n#' Centro Interdipartimentale di Bioloclimatologia University of Florence\n#' \\url{http://stackoverflow.com/questions/8708048/position-of-the-sun-given-time-of-day-latitude-and-longitude}\n#' @author Alfonso crisci \\email{a.crisci@@ibimet.cnr.it} Marco Morabito \\email{m.morabito@@unifi.it} \n#' \n#' \n#' @export\n\n\n\nsunposition <- function(timenow,lat, long) {\n \n time=as.POSIXlt(timenow, \"GMT\")\n year=as.numeric(format(time,\"%Y\"))\n hour=as.numeric(format(time,\"%H\"))\n day=as.numeric(format(time,\"%d\"))\n month=as.numeric(format(time,\"%m\"))\n min=as.numeric(format(time,\"%M\"))\n sec=as.numeric(format(time,\"%S\"))\n\n twopi <- 2 * pi\n deg2rad <- pi / 180\n\n # Get day of the year, e.g. Feb 1 = 32, Mar 1 = 61 on leap years\n \n month.days <- c(0,31,28,31,30,31,30,31,31,30,31,30)\n day <- day + cumsum(month.days)[month]\n leapdays <- year %% 4 == 0 & (year %% 400 == 0 | year %% 100 != 0) & \n day >= 60 & !(month==2 & day==60)\n day[leapdays] <- day[leapdays] + 1\n\n # Get Julian date - 2400000\n hour <- hour + min / 60 + sec / 3600 # hour plus fraction\n delta <- year - 1949\n leap <- trunc(delta / 4) # former leapyears\n jd <- 32916.5 + delta * 365 + leap + day + hour / 24\n\n # The input to the Atronomer's almanach is the difference between\n # the Julian date and JD 2451545.0 (noon, 1 January 2000)\n time <- jd - 51545.\n\n # Ecliptic coordinates\n\n # Mean longitude\n mnlong <- 280.460 + .9856474 * time\n mnlong <- mnlong %% 360\n mnlong[mnlong < 0] <- mnlong[mnlong < 0] + 360\n\n # Mean anomaly\n mnanom <- 357.528 + .9856003 * time\n mnanom <- mnanom %% 360\n mnanom[mnanom < 0] <- mnanom[mnanom < 0] + 360\n mnanom <- mnanom * deg2rad\n\n # Ecliptic longitude and obliquity of ecliptic\n eclong <- mnlong + 1.915 * sin(mnanom) + 0.020 * sin(2 * mnanom)\n eclong <- eclong %% 360\n eclong[eclong < 0] <- eclong[eclong < 0] + 360\n oblqec <- 23.439 - 0.0000004 * time\n eclong <- eclong * deg2rad\n oblqec <- oblqec * deg2rad\n\n # Celestial coordinates\n # Right ascension and declination\n num <- cos(oblqec) * sin(eclong)\n den <- cos(eclong)\n ra <- atan(num / den)\n ra[den < 0] <- ra[den < 0] + pi\n ra[den >= 0 & num < 0] <- ra[den >= 0 & num < 0] + twopi\n dec <- asin(sin(oblqec) * sin(eclong))\n\n # Local coordinates\n # Greenwich mean sidereal time\n gmst <- 6.697375 + .0657098242 * time + hour\n gmst <- gmst %% 24\n gmst[gmst < 0] <- gmst[gmst < 0] + 24.\n\n # Local mean sidereal time\n lmst <- gmst + long / 15.\n lmst <- lmst %% 24.\n lmst[lmst < 0] <- lmst[lmst < 0] + 24.\n lmst <- lmst * 15. * deg2rad\n\n # Hour angle\n ha <- lmst - ra\n ha[ha < -pi] <- ha[ha < -pi] + twopi\n ha[ha > pi] <- ha[ha > pi] - twopi\n\n # Latitude to radians\n lat <- lat * deg2rad\n\n # Azimuth and elevation\n el <- asin(sin(dec) * sin(lat) + cos(dec) * cos(lat) * cos(ha))\n az <- asin(-cos(dec) * sin(ha) / cos(el))\n\n # For logic and names, see Spencer, J.W. 1989. Solar Energy. 42(4):353\n\n cosAzPos <- (0 <= sin(dec) - sin(el) * sin(lat))\n sinAzNeg <- (sin(az) < 0)\n az[cosAzPos & sinAzNeg] <- az[cosAzPos & sinAzNeg] + twopi\n az[!cosAzPos] <- pi - az[!cosAzPos]\n\n \n\n el <- el / deg2rad\n az <- az / deg2rad\n lat <- lat / deg2rad\n\n return(list(elevation=el, azimuth=az))\n}\n", "meta": {"hexsha": "fc574fd03d37a4e5eea1ff4e37c29233c26c8177", "size": 3731, "ext": "r", "lang": "R", "max_stars_repo_path": "R/sunposition.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/sunposition.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/sunposition.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": 31.3529411765, "max_line_length": 112, "alphanum_fraction": 0.59608684, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6566224164547758}} {"text": " E04TCJ Example Program Results\n\n First solve the problem with the outliers\n\n --------------------------------------------------------\n E04GG, Nonlinear least squares method for bound-constrained problems\n Status: converged, an optimal solution was found\n Value of the objective 1.05037E+00\n Norm of gradient 8.78014E-06\n Norm of scaled gradient 6.05781E-06\n Norm of step 1.47886E-01\n \n Primal variables:\n idx Lower bound Value Upper bound\n 1 -inf 3.61301E-01 inf\n 2 -inf 9.10227E-01 inf\n 3 -inf 3.42138E-03 inf\n 4 -inf -6.08965E+00 inf\n 5 -inf 6.24881E-04 inf\n --------------------------------------------------------\n\n Now remove the outlier residuals from the problem handle\n\n --------------------------------------------------------\n E04GG, Nonlinear least squares method for bound-constrained problems\n Status: converged, an optimal solution was found\n Value of the objective 5.96811E-02\n Norm of gradient 1.19914E-06\n Norm of scaled gradient 3.47087E-06\n Norm of step 3.49256E-06\n \n Primal variables:\n idx Lower bound Value Upper bound\n 1 -inf 3.53888E-01 inf\n 2 -inf 1.06575E+00 inf\n 3 -inf 1.91383E-03 inf\n 4 -inf 2.17299E-01 inf\n 5 -inf 5.17660E+00 inf\n --------------------------------------------------------\n\n Assuming the outliers points are measured again\n we can enable the residuals and adjust the values\n\n --------------------------------------------------------\n E04GG, Nonlinear least squares method for bound-constrained problems\n Status: converged, an optimal solution was found\n Value of the objective 6.51802E-02\n Norm of gradient 2.57338E-07\n Norm of scaled gradient 7.12740E-07\n Norm of step 1.56251E-05\n \n Primal variables:\n idx Lower bound Value Upper bound\n 1 3.00000E-01 3.00000E-01 3.00000E-01\n 2 -inf 1.06039E+00 inf\n 3 -inf 2.11765E-02 inf\n 4 -inf 2.11749E-01 inf\n 5 -inf 5.16415E+00 inf\n", "meta": {"hexsha": "cd501a1c6018f78bab8424a848a02c0ac23fb594", "size": 2404, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/e04tcje.r", "max_stars_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_stars_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-03T22:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T01:44:03.000Z", "max_issues_repo_path": "simple_examples/baseresults/e04tcje.r", "max_issues_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_issues_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "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": "simple_examples/baseresults/e04tcje.r", "max_forks_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_forks_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-03T22:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T01:00:53.000Z", "avg_line_length": 40.7457627119, "max_line_length": 69, "alphanum_fraction": 0.4854409318, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.656618042909112}} {"text": "#' Linear Model Coefficients\n#' \n#' Coefficients of the linear model.\n#' \n#' @details\n#' The model is fit using a QR factorization of the input \\code{x}. At this\n#' time, that means \n#' \n#' Both of \\code{x} and \\code{y} must be distributed in an identical fashion.\n#' This means that the number of rows owned by each MPI rank should match, and\n#' the data rows \\code{x} and labels \\code{y} should be aligned. Additionally,\n#' each MPI rank should own at least one row. Ideally they should be load\n#' balanced, so that each MPI rank owns roughly the same amount of data.\n#' \n#' @section Communication:\n#' The operation has the same communication as \n#' \n#' @param x,y\n#' The input data \\code{x} and response \\code{y}. Each must be a shaq, and\n#' each must be distributed in an identical fashion. See the details section\n#' for more information.\n#' @param tol\n#' Numerical tolerance for deciding rank.\n#' \n#' @return\n#' A regular vector.\n#' \n#' @examples\n#' \\dontrun{\n#' library(kazaam)\n#' comm.set.seed(1234, diff=TRUE)\n#' \n#' x = ranshaq(rnorm, 10, 3)\n#' y = ranshaq(runif, 10)\n#' \n#' fit = lm_coefs(x, y)\n#' comm.print(fit)\n#' \n#' finalize()\n#' }\n#' \n#' @seealso \\code{\\link{glms}}\n#' @name lm_coefs\n#' @export\nlm_coefs = function(x, y, tol=1e-7)\n{\n check.is.shaq(x)\n check.is.shaq(y)\n \n R = qr_R(x)\n Q = qr_Q(x, R)\n \n ### NOTE here we assume that x (and hence Q) and y are distributed in identical fashion!\n qty = allreduce(crossprod(Data(Q), Data(y)))\n rank = max(which(abs(diag(R)) > tol))\n \n if (rank < ncol(x))\n {\n ind = 1:rank\n coefs = solve(R[ind, ind], qty[ind])\n coefs = c(coefs, rep(NA_real_, ncol(x)-rank))\n }\n else\n coefs = solve(R, qty)\n \n if (ncol(y) == 1)\n {\n dim(coefs) = NULL\n names(coefs) = paste0(\"x\", 1:ncol(x))\n }\n else\n rownames(coefs) = paste0(\"x\", 1:ncol(x))\n \n coefs\n}\n", "meta": {"hexsha": "f1ac94f3747d7c43b8673e4b56a91cd6d0c17799", "size": 1841, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lm_coefs.r", "max_stars_repo_name": "cran/kazaam", "max_stars_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_stars_repo_licenses": ["BSD-2-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": "R/lm_coefs.r", "max_issues_repo_name": "cran/kazaam", "max_issues_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "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/lm_coefs.r", "max_forks_repo_name": "cran/kazaam", "max_forks_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "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": 24.2236842105, "max_line_length": 90, "alphanum_fraction": 0.6338946225, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6565761185353459}} {"text": "# Eric Anderson\r\n#\r\n# Spline interpolate rain gauge data to 0.1\r\n# degree grids and save to .csv\r\n#\r\n# Version 1.0\r\n# 8 April 2015\r\n# \r\n# The purpose of this program is to ingest .csv\r\n# rainfall data for one day, interpolate them to\r\n# 0.1 degree grid spacing, and save them to\r\n# another .csv.\r\n\r\n# load libraries\r\nlibrary(maptools) # autoloads sp\r\nlibrary(raster)\r\nlibrary(rgeos)\r\nlibrary(rgdal)\r\nlibrary(akima)\r\nlibrary(fields)\r\n\r\n\r\n# set workspace\r\nsetwd(\"C:/Users/Eric/Dropbox/ESS508_Python/r_assign\")\r\n\r\n# Create area of interest for masking final interpolation (and\r\n# extrapolation if necessary)\r\n# This file should stay the same\r\naoi <- readShapePoly(\"aoi_sv_buff10_gcs.shp\")\r\n\r\n# Create vectors for x and y grid spacing. This will only need to # be created once per area to interpolate.\r\nygrids <- seq(13,14.5,0.1) # ~10km\r\nxgrids <- seq(-90.2,-87, 0.1) # ~10km\r\n\r\n# Load station data points (this file will be different every day)\r\n# Note that this may include missing gauge data, but it must be stored as \"NaN\"\r\npluv_raw <- read.csv(file=\"daily_rain.csv\")\t\r\n\r\n# Remove rows with missing rain data\r\npluv <- pluv_raw[complete.cases(pluv_raw),]\r\n\r\n\r\nprint(\"Rain gauge data read and missing data removed.\",quote=0)\r\n\r\n\r\n# Load coordinates to be interpolated \r\n# This file will only need to be created once per area to interpolate\r\npt <- read.csv(file=\"coords.csv\")\r\ncoordinates(pt)= ~ longitude+ latitude\r\n\r\n\r\n# Interpolate the pluviometer data to surface rasters\r\n ## Pick ONE of the following interpolation techniques by setting extLogical to TRUE or FALSE\r\n extLogical <- TRUE # if extLogical is true, spline is used (linLogical is false)\r\n #extLogical <- FALSE # if extLogical is false, linear is used (see akima documentation).\r\n # set linLogical to true or false based on extrapolation choice\r\n if (extLogical == TRUE) linLogical <- FALSE\r\n if (extLogical == FALSE) linLogical <- TRUE\r\n\r\n# Define x, y (same for every day) and interpolated z values (different for every day)\r\nx<- pluv[,4]; y<- pluv[,3]; z<- pluv[,5]\r\ninterpex <- mask(raster(interp(x,y,z, linear=linLogical, extrap=extLogical, xo=xgrids, yo=ygrids)),aoi)\r\n\r\n\r\n# Tell me I'm finished and how to plot an image\r\nprint(\"Interpolation complete. Use plot(interpex) command to see results in R console.\",quote=0)\r\n\r\n\r\n# Stack interpolated rasters... (only needed if many days are to be prepared at the same time)\r\nrStack = stack(interpex)\r\n\r\n# Perform the value extraction on the raster stack\r\n# (extracts interpolated rain values from raster to the 0.1 degree-spaced points)\r\nrVal = extract(rStack,pt)\r\nrVal[rVal<0] <- 0\t\t#replace all negative values to 0 (artifact of extrapolating to edge)\r\n\r\n\r\n# Combine these extracted results with the lat/lon of 0.1 degree-spaced csv points\r\nwrite.table(cbind(pt,data.frame(rVal)),file=\"pluv_daily_spline.csv\", append=FALSE, sep= \",\", row.names=FALSE, col.names=TRUE)\r\n\r\n\r\nprint(\"Program complete. Output saved to pluv_daily_spline.csv.\",quote=0)\r\n# Program complete.", "meta": {"hexsha": "a52c802b23d786e03312d70b47829b1f0845e13a", "size": 3000, "ext": "r", "lang": "R", "max_stars_repo_path": "interp_point_to_grid.r", "max_stars_repo_name": "andersoner/interpolate_point_to_grid_r", "max_stars_repo_head_hexsha": "65bc67d509a426aabe95b33a3b8658efd9391c5d", "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": "interp_point_to_grid.r", "max_issues_repo_name": "andersoner/interpolate_point_to_grid_r", "max_issues_repo_head_hexsha": "65bc67d509a426aabe95b33a3b8658efd9391c5d", "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": "interp_point_to_grid.r", "max_forks_repo_name": "andersoner/interpolate_point_to_grid_r", "max_forks_repo_head_hexsha": "65bc67d509a426aabe95b33a3b8658efd9391c5d", "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.1445783133, "max_line_length": 126, "alphanum_fraction": 0.7206666667, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6565761181006851}} {"text": "\n# Copyright (C) 2019 Dr. Norbert Bátfai, nbatfai@gmail.com\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (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, see \n#\n# https://youtu.be/Koyw6IH5ScQ\n\nlibrary(neuralnet)\n\na1 <- c(0,1,0,1)\na2 <- c(0,0,1,1)\nOR <- c(0,1,1,1)\n\nor.data <- data.frame(a1, a2, OR)\n\nnn.or <- neuralnet(OR~a1+a2, or.data, hidden=0, linear.output=FALSE, stepmax = 1e+07, threshold = 0.000001)\n\nplot(nn.or)\n\ncompute(nn.or, or.data[,1:2])\n\n\na1 <- c(0,1,0,1)\na2 <- c(0,0,1,1)\nOR <- c(0,1,1,1)\nAND <- c(0,0,0,1)\n\norand.data <- data.frame(a1, a2, OR, AND)\n\nnn.orand <- neuralnet(OR+AND~a1+a2, orand.data, hidden=0, linear.output=FALSE, stepmax = 1e+07, threshold = 0.000001)\n\nplot(nn.orand)\n\ncompute(nn.orand, orand.data[,1:2])\n\n\n\na1 <- c(0,1,0,1)\na2 <- c(0,0,1,1)\nEXOR <- c(0,1,1,0)\n\nexor.data <- data.frame(a1, a2, EXOR)\n\nnn.exor <- neuralnet(EXOR~a1+a2, exor.data, hidden=0, linear.output=FALSE, stepmax = 1e+07, threshold = 0.000001)\n\nplot(nn.exor)\n\ncompute(nn.exor, exor.data[,1:2])\n\n\n\na1 <- c(0,1,0,1)\na2 <- c(0,0,1,1)\nEXOR <- c(0,1,1,0)\n\nexor.data <- data.frame(a1, a2, EXOR)\n\nnn.exor <- neuralnet(EXOR~a1+a2, exor.data, hidden=c(6, 4, 6), linear.output=FALSE, stepmax = 1e+07, threshold = 0.000001)\n\nplot(nn.exor)\n\ncompute(nn.exor, exor.data[,1:2])\n\n", "meta": {"hexsha": "7b794442d78bbc88163fcd217ab48d1c11d131ff", "size": 1873, "ext": "r", "lang": "R", "max_stars_repo_path": "Prog2/bhax/attention_raising/NN_R/nn.r", "max_stars_repo_name": "mesterakos963/Prog2", "max_stars_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "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": "Prog2/bhax/attention_raising/NN_R/nn.r", "max_issues_repo_name": "mesterakos963/Prog2", "max_issues_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "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": "Prog2/bhax/attention_raising/NN_R/nn.r", "max_forks_repo_name": "mesterakos963/Prog2", "max_forks_repo_head_hexsha": "edc3e49567d29211510aa9cd3f4bf639c49c1ea6", "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": 24.9733333333, "max_line_length": 122, "alphanum_fraction": 0.6513614522, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.6564820313521437}} {"text": "# Method\npow <- function(x, y)\n{\n x <- as.numeric(x)\n y <- as.integer(y)\n prod(rep(x, y))\n}\n#Operator\n\"%pow%\" <- function(x,y) pow(x,y)\n\npow(3, 4) # 81\n2.5 %pow% 2 # 6.25\n", "meta": {"hexsha": "6caf2229689783f442b735f2ea0eb23540a50635", "size": 181, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Exponentiation-operator/R/exponentiation-operator.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/Exponentiation-operator/R/exponentiation-operator.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/Exponentiation-operator/R/exponentiation-operator.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": 13.9230769231, "max_line_length": 33, "alphanum_fraction": 0.5082872928, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6562876473441447}} {"text": "fptcdf=function(z,x0max,chi,driftrate,sddrift) {\r\n if (x0max<1e-10) return(pnorm(chi/z,mean=driftrate,sd=sddrift,lower.tail=F))\r\n zs=z*sddrift ; zu=z*driftrate ; chiminuszu=chi-zu ; xx=chiminuszu-x0max\r\n chizu=chiminuszu/zs ; chizumax=xx/zs\r\n tmp1=zs*(dnorm(chizumax)-dnorm(chizu))\r\n tmp2=xx*pnorm(chizumax)-chiminuszu*pnorm(chizu)\r\n 1+(tmp1+tmp2)/x0max\r\n}\r\n\r\nfptpdf=function(z,x0max,chi,driftrate,sddrift) {\r\n if (x0max<1e-10) return( (chi/z^2)*dnorm(chi/z,mean=driftrate,sd=sddrift))\r\n zs=z*sddrift ; zu=z*driftrate ; chiminuszu=chi-zu\r\n chizu=chiminuszu/zs ; chizumax=(chiminuszu-x0max)/zs\r\n (driftrate*(pnorm(chizu)-pnorm(chizumax)) + \r\n sddrift*(dnorm(chizumax)-dnorm(chizu)))/x0max\r\n}\r\n\r\nrlba=function(n,b,A,vs,s,t0,st0=0,truncdrifts=TRUE){\r\n n.with.extras=ceiling(n*(1+3*prod(pnorm(-vs))))\r\n drifts=matrix(rnorm(mean=vs,sd=s,n=n.with.extras*length(vs)),ncol=length(vs),byrow=TRUE)\r\n if (truncdrifts) {\r\n repeat {\r\n drifts=rbind(drifts,matrix(rnorm(mean=vs,sd=s,n=n.with.extras*length(vs)),ncol=length(vs),byrow=TRUE))\r\n tmp=apply(drifts,1,function(x) any(x>0))\r\n drifts=drifts[tmp,]\r\n if (nrow(drifts)>=n) break\r\n }\r\n }\r\n drifts=drifts[1:n,]\r\n drifts[drifts<0]=0\r\n starts=matrix(runif(min=0,max=A,n=n*length(vs)),ncol=length(vs),byrow=TRUE)\r\n ttf=t((b-t(starts)))/drifts\r\n rt=apply(ttf,1,min)+t0+runif(min=-st0/2,max=+st0/2,n=n)\r\n resp=apply(ttf,1,which.min)\r\n list(rt=rt,resp=resp)\r\n}\r\n\r\n\r\n \r\n\r\ndlba=function(t,t0,x0max,chi,v1,v0,sdI,truncdrifts=TRUE) {\r\n # Generates defective PDF for responses on node #1.\r\n # \"truncdrifts\" sets whether that part of the multi-variate\r\n # normal distribution on drift rates which would otherwise\r\n # lead to non-terminating trials is truncated.\r\n if(t < 0){\r\n drift = c(v0,v1)\r\n }else{\r\n drift = c(v1,v0)\r\n }\r\n t = abs(t)\r\n t = t - t0\r\n x0max = rep(x0max,2)\r\n chi = rep(chi,2)\r\n \r\n sdI = rep(drift,2)\r\n \r\n N=length(drift) # Number of responses.\r\n if (N>2) {\r\n tmp=array(dim=c(length(t),N-1))\r\n for (i in 2:N) tmp[,i-1]=fptcdf(z=t,x0max=x0max[i],chi=chi[i],\r\n driftrate=drift[i],sddrift=sdI[i])\r\n G=apply(1-tmp,1,prod)\r\n } else {\r\n G=1-fptcdf(z=t,x0max=x0max[2],chi=chi[2],driftrate=drift[2],sddrift=sdI[2])\r\n }\r\n out=G*fptpdf(z=t,x0max=x0max[1],chi=chi[1],driftrate=drift[1],sddrift=sdI[1])\r\n if (truncdrifts) {\r\n out=out/(1-prod(pnorm(-drift/sdI)))\r\n out[t<=0]=0\r\n out = pmax(out,1e-10)\r\n return(out)\r\n } else {\r\n out = pmax(out,1e-10)\r\n return(out)\r\n }\r\n}\r\n\r\nn1PDF=function(t,x0max,chi,drift,sdI,st0=0,truncdrifts=TRUE) {\r\n N=length(drift) # Number of responses\r\n if (length(x0max)1) st0=st0[1] # Only ONE non-decision time.\r\n if (st0==0) return(n1PDFfixedt0(t,x0max,chi,drift,sdI,truncdrifts=truncdrifts))\r\n tmpf=function(t,x0max,chi,drift,sdI,st0,truncdrifts)\r\n n1PDFfixedt0(t,x0max,chi,drift,sdI,truncdrifts=truncdrifts)/st0\r\n outs=numeric(length(t))\r\n for (i in 1:length(outs)) outs[i]=integrate(f=tmpf,lower=t[i]-st0/2,upper=t[i]+st0/2,\r\n x0max=x0max,chi=chi,drift=drift,sdI=sdI,st0=st0,truncdrifts=truncdrifts)$value\r\n outs\r\n}\r\n\r\n\r\nn1CDF=function(t,x0max,chi,drift,sdI,st0=0,truncdrifts=TRUE) {\r\n # Generates defective CDF for responses on node #1. \r\n N=length(drift) # Number of responses\r\n if (length(x0max)1) stop(\"Only one value of st0 allowed.\")\r\n if (st0<1e-6) st0=0 # Integral can fail for small st0.\r\n outs=numeric(length(t)) ; bounds=c(-st0/2,t)\r\n for (i in 1:length(t)) {\r\n tmp=\"error\"\r\n repeat {\r\n if (bounds[i]>=bounds[i+1]) {outs[i]=0;break}\r\n tmp=try(integrate(f=n1PDF,lower=bounds[i],upper=bounds[i+1],subdivisions=1000,\r\n x0max=x0max,chi=chi,drift=drift,sdI=sdI,st0=st0,truncdrifts=truncdrifts)$value,silent=T)\r\n if (is.numeric(tmp)) {outs[i]=tmp;break}\r\n # Try smart lower bound.\r\n if (bounds[i]<=0) {\r\n\tbounds[i]=max(c((chi-0.98*x0max)/(max(mean(drift),drift[1])+2*sdI)[1],0))\r\n\tnext\r\n }\r\n # Try smart upper bound.\r\n if (bounds[i+1]==Inf) {\r\n\tbounds[i+1]=0.02*max(chi)/(mean(drift)-2*mean(sdI))\r\n\tnext\r\n }\r\n stop(\"Error in n1CDF that I could not catch.\")\r\n }\r\n }\r\n cumsum(outs)\r\n}\r\n\r\nn1mean=function(x0max,chi,drift,sdI,truncdrifts=TRUE) {\r\n # Generates mean RT for responses on node #1. \r\n pc=n1CDF(Inf,x0max,chi,drift,sdI,truncdrifts=truncdrifts)\r\n fn=function(t,x0max,chi,drift,sdI,st0=0,truncdrifts,pc)\r\n t*n1PDF(t,x0max,chi,drift,sdI,st0,truncdrifts=truncdrifts)/pc\r\n tmp=integrate(f=fn,lower=0,upper=100*chi,x0max=x0max,chi=chi,pc=pc,\r\n drift=drift,sdI=sdI,st0=st0,truncdrifts=truncdrifts)$value\r\n list(mean=tmp,p=pc)\r\n}\r\n\r\n", "meta": {"hexsha": "0e034e369719c1cdc88c223fb53843d522f3fd07", "size": 4937, "ext": "r", "lang": "R", "max_stars_repo_path": "13428_2016_746_MOESM1_ESM_July/LBA/lba-math.r", "max_stars_repo_name": "bjsmith/reversallearning", "max_stars_repo_head_hexsha": "023304731d41c3109bacbfd49d4c850a92353978", "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": "13428_2016_746_MOESM1_ESM_July/LBA/lba-math.r", "max_issues_repo_name": "bjsmith/reversallearning", "max_issues_repo_head_hexsha": "023304731d41c3109bacbfd49d4c850a92353978", "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": "13428_2016_746_MOESM1_ESM_July/LBA/lba-math.r", "max_forks_repo_name": "bjsmith/reversallearning", "max_forks_repo_head_hexsha": "023304731d41c3109bacbfd49d4c850a92353978", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-15T22:00:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T22:40:20.000Z", "avg_line_length": 36.0364963504, "max_line_length": 109, "alphanum_fraction": 0.6475592465, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6562678548109211}} {"text": "# Importamos librerías\nrm(list=ls())\ninstall.packages(\"FuzzyR\")\nlibrary(FuzzyR)\n \n# Iniciamos un nuevo objeto FIS (Fuzzy inference system)\netapa <- newfis(\"Variables\")\n \n# Creamos variables de ingreso con sus rangos\netapa <- addvar(etapa, \"input\", \"edad\", c(0,60))\netapa <- addvar(etapa, \"input\", \"salario\", c(0,1000))\netapa <- addvar(etapa, \"input\", \"ingreso\", c(2000,2021))\netapa <- addvar(etapa, \"output\", \"apellidos\", c(0,3))\n \n# Creamos funciones de pertenencia trapezoidales y triangulares (inputs)\n# Funciones \"edad\"\netapa <- addmf(etapa,\"input\", 1, \"Joven\", \"trapmf\", c(0,0,25,35) )\netapa <- addmf(etapa,\"input\", 1, \"Adulto\", \"trimf\", c(25,35,45))\netapa <- addmf(etapa,\"input\", 1, \"Viejo\", \"trapmf\", c(35,45,100,100) )\n \n# Funciones \"salario\"\netapa <- addmf(etapa,\"input\", 2, \"Bajo\", \"trapmf\", c(0,0,400,650) )\netapa <- addmf(etapa,\"input\", 2, \"Medio\", \"trimf\", c(400,650,700))\netapa <- addmf(etapa,\"input\", 2, \"Alto\", \"trapmf\", c(650,700,1000,1000) )\n \n# Funciones \"ingreso\"\netapa <- addmf(etapa,\"input\", 3, \"Antiguo\", \"trapmf\", c(0,0,2005,2011) )\netapa <- addmf(etapa,\"input\", 3, \"Medio\", \"trimf\", c(2005,2011,2014))\netapa <- addmf(etapa,\"input\", 3, \"Reciente\", \"trapmf\", c(2011,2014,2021,2021) )\n \n# Funciones \"cumple requisitos\" (output)\netapa <- addmf(etapa,\"output\", 1, \"no cumple requisitos\", \"trapmf\", c(0,0,1,2) )\netapa <- addmf(etapa,\"output\", 1, \"cumple requisitos\", \"trapmf\", c(1,2,3,3))\n \n# Dibujamos las funciones\nplotmf(etapa,\"input\",1,xlab=\"Edad\",ylab=\"Pertenencia\",main=\"Edad\")\nplotmf(etapa,\"input\",2,xlab=\"Salario\",ylab=\"Pertenencia\",main=\"Dinero\")\nplotmf(etapa,\"input\",3,xlab=\"Antigüedad\",ylab=\"Pertenencia\",main=\"Ingreso\")\nplotmf(etapa,\"output\",1)\n \n# Creamos las reglas que indican qué valor resulta para valores que se encuentren\n# en cierto punto de las funciones de pertenencia, respondiendo a la pregunta\n# “Cuáles son los apellidos de las personas jóvenes o recientemente empleadas,\n# pero con sueldo alto”.\nrulelist <- rbind(c(1,3,3,3,1,1),\n c(1,3,2,2,1,1),\n c(1,3,1,2,1,1),\n \n c(2,3,3,2,1,1),\n c(2,3,2,1,1,1),\n c(2,3,1,1,1,1),\n \n c(3,3,3,2,1,1),\n c(3,3,2,1,1,1),\n c(3,3,1,1,1,1)\n )\n \n# Agregamos reglas al sistema difuso\netapa <- addrule(etapa, rulelist)\n \n# Ingresamos valores a evaluar, que son los incluídos en la tabla del enunciado\nmatrixInput <- matrix(c(30,800,2010, \n 30,600,2010, \n 25,900,2004,\n 55,700,2016,\n 25,750,2015),ncol=3, byrow=TRUE) \n \n# Realizamos la evaluación de los inputs usando el sistema difuso y sus resultados\n# son entregados en la consola de R.\nevalfis(matrixInput,etapa)", "meta": {"hexsha": "ed07d09e99faff125bfdc8af2f6f56a6c51ce960", "size": 2772, "ext": "r", "lang": "R", "max_stars_repo_path": "lab-3-fuzzy-logic.r", "max_stars_repo_name": "melipass/umayor-inteligencia-artificial", "max_stars_repo_head_hexsha": "427250964da2a012bc8085a87c68a7ef370b5bb9", "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": "lab-3-fuzzy-logic.r", "max_issues_repo_name": "melipass/umayor-inteligencia-artificial", "max_issues_repo_head_hexsha": "427250964da2a012bc8085a87c68a7ef370b5bb9", "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": "lab-3-fuzzy-logic.r", "max_forks_repo_name": "melipass/umayor-inteligencia-artificial", "max_forks_repo_head_hexsha": "427250964da2a012bc8085a87c68a7ef370b5bb9", "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": 39.6, "max_line_length": 82, "alphanum_fraction": 0.6208513709, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6562603252630596}} {"text": "R version 3.2.2 (2015-08-14) -- \"Fire Safety\"\nCopyright (C) 2015 The R Foundation for Statistical Computing\nPlatform: x86_64-w64-mingw32/x64 (64-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n[Workspace loaded from ~/.RData]\n\n install.packages(\"markovchain\")\n library(markovchain)\n \n RentalStates <- c(\"Downtown\", \"East\", \"West\")\n \n RentalStates\n \n RentalTransitionMatrix <- matrix(c(0.3, 0.3, 0.4, \n 0.4, 0.4, 0.2, \n 0.5, 0.3, 0.2),\n byrow = T, nrow = 3, dimnames = list(RentalStates, RentalStates))\n \n \n RentalTransitionMatrix\n \n mcRental <- new(\"markovchain\", states = RentalStates, byrow = T, transitionMatrix = RentalTransitionMatrix, name = \"Rental Cars\")\n \n mcRental\n \n mcRental[2]\n \n plot(mcRental)\n \n transitionProbability(mcRental, \"East\", \"West\")\n \n x <- 0.3 * 0.3\n y <- 0.3 * 0.4\n z <- 0.4 * 0.5\n x + y + z\n \n mcRental ^ 2\n \n mcRental^20\n \n mcRental ^ 30\n\n 70 * steadyStates(mcRental)\n \n summary(mcRental)\n \n conditionalDistribution(mcRental, \"Downtown\")\n \n conditionalDistribution(mcRental, \"West\")\n \n conditionalDistribution(mcRental, \"East\")\n", "meta": {"hexsha": "18919fae1cc6678c0217198c50818dd926e69165", "size": 1598, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 08/3Markov Chains - Car Rental Agency Service.r", "max_stars_repo_name": "PacktPublishing/Practical-Machine-Learning-Cookbook", "max_stars_repo_head_hexsha": "c2210aacc35fa636f888cda0c62ad5e1d3f9100e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-05-14T09:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:56.000Z", "max_issues_repo_path": "Chapter 08/3Markov Chains - Car Rental Agency Service.r", "max_issues_repo_name": "alon-begin/Practical-Machine-Learning-Cookbook", "max_issues_repo_head_hexsha": "6001dbfd1a8bff897466d9567c7d1594d2c16253", "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": "Chapter 08/3Markov Chains - Car Rental Agency Service.r", "max_forks_repo_name": "alon-begin/Practical-Machine-Learning-Cookbook", "max_forks_repo_head_hexsha": "6001dbfd1a8bff897466d9567c7d1594d2c16253", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2017-05-04T03:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T20:19:45.000Z", "avg_line_length": 25.3650793651, "max_line_length": 130, "alphanum_fraction": 0.6576971214, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6560161893098689}} {"text": "#clear environment, load runjags.\nrm(list = ls())\nlibrary(runjags)\n\n#### Generate pseudo data ####\n#10 sites, 9 plots per site, 10 observations per plot. \nn.site <- 10\nn.plot <- 9\nn.core <- 10\nsiteID <- sort(rep(LETTERS[1:n.site],n.plot*n.core))\nplotID <- rep(1:n.plot,n.site*n.core)\nplotID <-paste(siteID,plotID,sep = '_')\nsite.means <- runif(n.site,10,25)\nplot.means <- list()\nfor(i in 1:length(site.means)){\n plot.means[[i]] <- rnorm(n.plot,site.means[i],2)\n}\nplot.means <- unlist(plot.means)\n\n#get observations for each plot, based on a mean, and a sd of 2\nobs <- list()\nfor(i in 1:length(plot.means)){\n obs[[i]] <- rnorm(n.core, mean = plot.means[i], sd = 2)\n}\nx <- unlist(obs)\n\n#create true data frame.\ndat <- data.frame(siteID,plotID)\ndat <- dat[order(plotID),]\ndat$x <- x\n\n#indexing.\nplotindex <- as.factor(dat$plotID)\nsiteindex <- list()\nfor(i in 1:n.site){\n siteindex[[i]] <- rep(LETTERS[i],n.plot)\n}\nsiteindex <- as.factor(unlist(siteindex))\n\n\n#### Specify hierarchical JAGS model ####\njags.model = \"\nmodel {\n#priors\nglobal ~ dnorm(0,1.0E-4) #global level parameter prior.\nsite.tau ~ dgamma(0.1,0.1)\nplot.tau ~ dgamma(0.1,0.1)\ncore.tau ~ dgamma(0.1,0.1)\n\nfor(i in 1:N.site){ site[i] ~ dnorm(global, site.tau)} ## estimate global mean\nfor(j in 1:N.plot){ plot[j] ~ dnorm(site[siteindex[j]],plot.tau)} ## estimate site means\nfor(k in 1:N.core){ core[k] ~ dnorm(plot[plotindex[k]],core.tau)} ## estimate plot means\n\n} #end model\n\"\n##### specify JAGS data object. ####\njags.data <- list(core = dat$x, \n N.site = length(unique(dat$siteID)),\n N.plot = length(unique(dat$plotID)),\n N.core = nrow(dat),\n plotindex = plotindex, siteindex=siteindex)\n\n#### Fit JAGS model ####\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('plot','site'))\nout <- summary(jags.out)\n\n##### compare estimate plot/site means to true values. All w/in 95% credible interval. ####\npar(mfrow = c(1,2))\nfit.plot.means <- out[grep('plot',rownames(out)),][,4]\nfit.site.means <- out[grep('site',rownames(out)),][,4]\nplot(plot.means ~ fit.plot.means, main = 'plot-level fit'); abline(0,1,lwd=2, lty=2)\nplot(site.means ~ fit.site.means, main = 'site-level fit'); abline(0,1,lwd=2, lty=2)\n\n##### check uncertainty values #####\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('core.tau','plot.tau','site.tau','global'))\nsummary(jags.out)\n\n\n##### create data with missing observations. #####\nmissing <- dat\n#remove 3 observations within a plot in site A.\nmissing[2:4,3] <- NA\n#remove an entire plot in site B.\nmissing[missing$plotID == 'B_1',3] <- NA\n#remove all observations in site C.\nmissing[missing$siteID == 'C' ,3] <- NA\n\n##### create new jags data object for fitting missing data model. ####\njags.data <- list(core = missing$x, \n N.site = length(unique(dat$siteID)),\n N.plot = length(unique(dat$plotID)),\n N.core = nrow(dat),\n plotindex = plotindex, siteindex=siteindex)\n\n##### Fit missing data model. ####\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('core','plot','site'))\n\nout <- summary(jags.out)\ncomp <- dat\ncomp$pred <- out[grep('core',rownames(out)),4]\ncomp$removed <- missing$x\nz <- comp[is.na(comp$removed),]\n\n##### how are the core level predcitions compared to true values? in range. #####\ncbind(out[2:4,],dat$x[2:4])\n\n##### how about the missing plot? ####\nzz <- cbind(out[grep('core',rownames(out)),],missing,dat$x)\nzz[zz$plotID == 'B_1',]\n\n##### how about the missing site? ####\nzz[zz$siteID == 'C',]\n", "meta": {"hexsha": "d66c66be3fab7e0d3605f811fe32066cf52fbee3", "size": 3928, "ext": "r", "lang": "R", "max_stars_repo_path": "testing_development/missing data example.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "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": "testing_development/missing data example.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "testing_development/missing data example.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 32.1967213115, "max_line_length": 91, "alphanum_fraction": 0.5845213849, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6560161871002965}} {"text": "library(nloptr)\n\nget_expected = function(beta, tau1, tau2, N0, A0, observed_I=NULL) {\n \"\n Calculates expected new case counts for each step in the time series.\n \n Parameters\n ----------\n N0 : numeric\n Initial number of contagious patients.\n A0 : numeric\n Initial number of asymptomatic patients.\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n Lagged one step (beta[1] = beta(0) in our notation).\n tau1 : numeric\n Probability that an asymptomatic patient will turn contagious in the next\n time step.\n tau : numeric\n (1 / mean) number of days an individual will continue to be infectious.\n \n Returns\n -------\n expected : list\n Daily expected number of infectious (N), new asymptomatic (A), and new\n infectious (I) patients.\n \"\n steps = length(beta)\n expected_I = rep(0, steps)\n expected_N = rep(0, steps)\n expected_A = rep(0, steps)\n N_previous = N0\n A_previous = A0\n for(t in 1:steps) {\n expected_I[t] = (1 - exp(-tau1)) * A_previous\n expected_A[t] = (exp(-tau1) * A_previous) + (beta[t] * N_previous)\n expected_N[t] = (exp(-tau2) * N_previous) + expected_I[t]\n if (is.null(observed_I)) { # history not available\n N_previous = expected_N[t]\n } else { # history available; use it\n N_previous = sum(c(N0, observed_I[1:t]) * rev(pexp(0:t, rate=tau2, lower.tail=FALSE)))\n }\n A_previous = expected_A[t]\n }\n return(list(\"N\"=c(N0, expected_N), \"A\"=c(A0, expected_A), \"I\"=expected_I))\n}\n\nfit = function(observed_I, beta0, beta_min, beta_max, tau10, tau1_min,\n tau1_max, tau20, tau2_min, tau2_max, N00, N0_min, N0_max, A00,\n A0_min, A0_max, lambda, ignore_beta_diff, use_history, n_nloptr_iter=100000) {\n \"\n Fits the model to observed daily new case counts.\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta0 : numeric vector\n Initial value for beta; the expected number of cases stemming from a single\n person in a single day.\n beta_min : numeric\n Beta lower bound.\n beta_max : numeric\n Beta upper bound.\n ignore_beta_diff : numeric vector\n List of beta indices for which differences should be ignored while\n calculating the loss function. This amounts to moments in time in which we\n allow the beta series to be discontinuous.\n \n Returns\n -------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n \"\n # concatenate initial parameters into a single vector for optimization\n x0 = c(beta0, tau10, tau20, N00, A00)\n steps = length(observed_I)\n lb = c(rep(beta_min, steps), tau1_min, tau2_min, N0_min, A0_min)\n ub = c(rep(beta_max, steps), tau1_max, tau2_max, N0_max, A0_max)\n # set optimization parameters\n opts = list(\"algorithm\" = \"NLOPT_LN_BOBYQA\", \"xtol_rel\" = 1.0e-7, \"maxeval\" = n_nloptr_iter)\n # define loss function\n loss = function(x) {\n # unpack values\n beta = x[1:steps]\n tau1 = x[steps + 1]\n tau2 = x[steps + 2]\n N0 = x[steps + 3]\n A0 = x[steps + 4]\n # calculate loss\n if (use_history) {\n expected = get_expected(beta, tau1, tau2, N0, A0, observed_I)\n } else {\n expected = get_expected(beta, tau1, tau2, N0, A0)\n }\n \n regularization = (diff(beta) / beta[1:(steps - 1)]) ^ 2\n regularization = regularization[!1:length(regularization) %in% ignore_beta_diff]\n observed_I = round(observed_I, 0)\n factSum = function(x) {\n return(sum(log(1:round(x, 0))))\n }\n loglikelihood = observed_I*log(expected$I)-expected$I-sapply(as.matrix(observed_I), FUN=factSum)\n loglikelihood[observed_I==0] = -expected$I[observed_I==0]\n return(-mean(loglikelihood) + lambda*mean(regularization))\n }\n result = nloptr(x0=x0, eval_f=loss, lb=lb, ub=ub, opts=opts)\n model = list(\n \"R\" = result$solution[1:steps] / result$solution[steps + 2],\n \"beta\" = result$solution[1:steps],\n \"tau1\" = result$solution[steps + 1],\n \"tau2\" = result$solution[steps + 2],\n \"N0\" = result$solution[steps + 3],\n \"A0\" = result$solution[steps + 4],\n \"loss\" = result$objective,\n \"lambda\" = lambda,\n \"ignore_beta_diff\" = ignore_beta_diff,\n \"use_history\" = use_history\n )\n regularization = (diff(model$beta) / model$beta[1:(steps - 1)]) ^ 2\n regularization = regularization[!1:(steps - 1) %in% ignore_beta_diff]\n model$likelihood = (model$loss - lambda * mean(regularization)) * steps\n return(model)\n}\n\nfit_robust = function(observed_I, beta_min, beta_max, tau1_min, tau1_max,\n tau2_min, tau2_max, N0_min, N0_max, A0_min, A0_max, lambda,\n ignore_beta_diff, use_history, n_robust_iter, n_nloptr_iter) {\n best_loss = Inf\n best_model = NULL\n for (i in 1:n_robust_iter) {\n beta0 = runif(length(observed_I), beta_min, beta_max)\n tau10 = runif(1, tau1_min, tau1_max)\n tau20 = runif(1, tau2_min, tau2_max)\n N00 = runif(1, N0_min, N0_max)\n A00 = runif(1, A0_min, A0_max)\n model = fit(observed_I, beta0=beta0, beta_min=beta_min, beta_max=beta_max,\n tau10=tau10, tau1_min=tau1_min, tau1_max=tau1_max, tau20=tau20,\n tau2_min=tau2_min, tau2_max=tau2_max, N00=N00, N0_min=N0_min,\n N0_max=N0_max, A00=A00, A0_min=A0_min, A0_max=A0_max,\n lambda=lambda, ignore_beta_diff=ignore_beta_diff,\n use_history=use_history, n_nloptr_iter=n_nloptr_iter)\n if (model$loss < best_loss) {\n best_model = model\n best_loss = model$loss\n }\n }\n best_model[[\"n_robust_iter\"]] = n_robust_iter\n return(best_model)\n}\n\nsearch_best_model = function(observed_I, beta_min, beta_max, tau1_min, tau1_max,\n tau2_min, tau2_max, N0_min, N0_max, A0_min, A0_max,\n ignore_beta_diff, n_iter,search=FALSE) {\n best_loss = Inf\n best_model = NULL\n for (i in 1:n_iter) {\n beta0 = runif(length(observed_I), beta_min, beta_max)\n tau10 = runif(1, tau1_min, tau1_max)\n tau20 = runif(1, tau2_min, tau2_max)\n N00 = runif(1, N0_min, N0_max)\n A00 = runif(1, A0_min, A0_max)\n model = fit(observed_I, beta0=beta0, beta_min=beta_min, beta_max=beta_max,\n tau10=tau10, tau1_min=tau1_min, tau1_max=tau1_max, tau20=tau20,\n tau2_min=tau2_min, tau2_max=tau2_max, N00=N00, N0_min=N0_min,\n N0_max=N0_max, A00=A00, A0_min=A0_min, A0_max=A0_max,\n lambda=0, ignore_beta_diff=ignore_beta_diff,n_iter=10000000)\n if (model$loss < best_loss) {\n best_model = model\n best_loss = model$loss\n best_param=list(\n \"beta0\"=beta0,\n \"tau10\"=tau10,\n \"tau20\"=tau20,\n \"N00\"=N00,\n \"A00\"=A00\n )\n }\n }\n if(search){\n p_value = 0\n c_left = 0\n c_right = 1e20\n p_values = 0\n cs = c_left\n while( 0.93 > p_value | 0.96 < p_value)\n {\n c = (c_left + c_right)/2\n model = fit(observed_I, beta0=best_model$beta, beta_min=beta_min, beta_max=max(beta_max,best_model$beta),\n tau10=best_param$tau10, tau1_min=tau1_min, tau1_max=tau1_max, tau20=best_param$tau20,\n tau2_min=tau2_min, tau2_max=tau2_max, N00=best_param$N00, N0_min=N0_min,\n N0_max=N0_max, A00=best_param$A00, A0_min=A0_min, A0_max=A0_max,\n lambda=c, ignore_beta_diff=ignore_beta_diff,n_iter=10)\n LRTest=2*(model$loss-best_loss)\n p_value=pchisq(LRTest,length(best_model$beta), lower.tail=TRUE) \n p_values = c(p_values,p_value)\n cs = c(cs,c)\n if(p_value < 0.95)\n {\n c_left = c \n }\n if(p_value > 0.96)\n {\n c_right = c\n }\n }\n return(model)\n }\n return(best_model)\n }", "meta": {"hexsha": "2f14ba67885387a6505bb144c5593ff8658f61bf", "size": 7748, "ext": "r", "lang": "R", "max_stars_repo_path": "likelihood_incubation_exp/model_fitting.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "likelihood_incubation_exp/model_fitting.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "likelihood_incubation_exp/model_fitting.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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.8952380952, "max_line_length": 111, "alphanum_fraction": 0.6417139907, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6560161797562306}} {"text": "function(y,yfit,family=binomial(),variance=NULL)\n{\n # Calculate the residual for given observed y and its fitted value yfit: \n # the length between y and yfit along the quardratic variance function:\n # V(mu) = v2*mu^2+v1*mu+v0\n qvresidual<-function(y,yfit,v2,v1)\n {\n vpa <- 2*v2*yfit+v1\n svpa2 <- sqrt(1+vpa*vpa)\n \n vpb <- 2*v2*y+v1\n svpb2 <- sqrt(1+vpb*vpb)\n \n vr <- (log((vpb+svpb2)/(vpa+svpa2))+vpb*svpb2-vpa*svpa2)/(4*v2)\n vr\n }\n \n if( is.character(family) ) {\n cf <- family\n family <- get(family, mode=\"function\", envir=parent.frame())\n } else\n cf <- family$family\n\n if( pmatch(\"Negative Binomial\",cf,nomatch=F) )\n {\n theta <- as.numeric(gsub(\"(?<=\\\\()[^()]*(?=\\\\))(*SKIP)(*F)|.\",\"\", cf, perl=T))\n cf <- \"negative.binomial\"\n } else if( pmatch(\"Tweedie\",cf,nomatch=F) )\n {\n dv <- Deriv(family$variance,\"mu\")\n theta <- dv(1)\n }\n \n if( is.null(variance) )\n {\n switch(cf,\n binomial={DFUN<-function(x) qvresidual(x[1],x[2],-1,1)}, # Need modify for Y~Bin(n,p)\n gaussian={DFUN<-function(x) x[1]-x[2]},\n Gamma={DFUN<-function(x) qvresidual(x[1],x[2],1,0)},\n negative.binomial={DFUN<-function(x) qvresidual(x[1],x[2],1/theta,1)},\n poisson={DFUN<-function(x) x[1]-x[2]},\n quasibinomial={DFUN<-function(x) qvresidual(x[1],x[2],-1,1)},\n quasipoisson={DFUN<-function(x) x[1]-x[2]},\n inverse.gaussian={\n DFUN<-function(x) integrate(function(mu){sqrt(1+9*mu^4)},x[1],x[2])$value},\n Tweedie={ # var.power: 0, 1, (1,2), 2, >2\n if( (theta==0)|(theta==1) )\n DFUN<-function(x) x[1]-x[2]\n else if( theta==2 ) \n DFUN<-function(x) qvresidual(x[1],x[2],1,0)\n else\n DFUN<-function(x) integrate(function(mu){sqrt(1+theta^2*mu^(2*theta-2))},x[1],x[2])$value},\n quasi={ # variance for quasi: \"constant\",\"mu(1-mu)\",\"mu\",\"mu^2\",\"mu^3\", or other\n if( (family$varfun==\"constant\")|(family$varfun==\"mu\") )\n DFUN <- function(x) x[1]-x[2]\n else if( family$varfun==\"mu(1-mu)\" )\n DFUN<-function(x) qvresidual(x[1],x[2],-1,1)\n else if( family$varfun==\"mu^2\" )\n DFUN<-function(x) qvresidual(x[1],x[2],1,0)\n else\n DFUN<-function(x) integrate(function(mu){sqrt(1+Deriv(family$variance,\"mu\")^2)},x[1],x[2])$value})\n }\n else\n DFUN<-function(x) integrate(function(mu){sqrt(1+Deriv(variance,\"mu\")^2)},x[1],x[2])$value\n \n vresidual <- apply(cbind(y,yfit),1,DFUN)\n}\n", "meta": {"hexsha": "ccd5ddcf97538de0cca34f1e2d02a88896490111", "size": 2476, "ext": "r", "lang": "R", "max_stars_repo_path": "vresidual.r", "max_stars_repo_name": "yuting1214/2021_Fall_RA", "max_stars_repo_head_hexsha": "62bfa7d90f1330be5020eca551e1312130543fc8", "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": "vresidual.r", "max_issues_repo_name": "yuting1214/2021_Fall_RA", "max_issues_repo_head_hexsha": "62bfa7d90f1330be5020eca551e1312130543fc8", "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": "vresidual.r", "max_forks_repo_name": "yuting1214/2021_Fall_RA", "max_forks_repo_head_hexsha": "62bfa7d90f1330be5020eca551e1312130543fc8", "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.4117647059, "max_line_length": 108, "alphanum_fraction": 0.5650242326, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.6560057385023876}} {"text": "# 4. faza: Analiza podatkov\n\nlogisticna <- function(x) { 100 / (1 + exp(-x)) }\nlogisticna_inv <- function(y) { log(y / (100 - y)) }\nlogisticna_breaks <- . %>% logisticna() %>% extended_breaks()() %>% logisticna_inv()\n\nlogisticna_trans <- trans_new(\"logistična funkcija\", logisticna, logisticna_inv)\n\n\n\nprimerjava_rasti_log <- primerjava_rasti %>% mutate(delez=logisticna_inv(delez))\n\ngraf7 <- ggplot(primerjava_rasti_log %>% filter(drzava %in% c(\"Islandija\", \"Nizozemska\", \"Norveška\", \"Bolgarija\", \"Turčija\", \"Grčija\")),\n aes(x=leto, y=delez, col=drzava)) +\n geom_point() + ggtitle(\"Primerjava rasti držav z največjo in najmanjšo rastjo\") + \n xlab(\"leto\") + ylab(\"delež v %\") + facet_grid(. ~ drzava) + stat_smooth(method=\"lm\") +\n coord_trans(y=logisticna_trans) + scale_y_continuous(breaks=logisticna_breaks,\n labels=logisticna) + \n theme(axis.text.x=element_text(angle=45, vjust=0.5, hjust=1))\n\n\nbolgarija = c('Bolgarija')\nrasti_b <- primerjava_rasti_log %>% filter(drzava==\"Bolgarija\")\nrasti_b$vrsta <- \"podatki\"\nnames(rasti_b)[names(rasti_b) == \"delez\"] <- \"rast\"\nmodel7b <- lm(rast~leto, data=rasti_b)\npr <- predict(model7b, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_rasti_b <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(pr[1], pr[2], pr[3], pr[4], pr[5], pr[6]))\nnapoved_rasti_b$drzava <- bolgarija\nnapoved_rasti_b$vrsta <- \"napoved\"\nskupne_rasti_b <- rbind(rasti_b, napoved_rasti_b)\n\nturcija = c('Turčija')\nrasti_t <- primerjava_rasti_log %>% filter(drzava==\"Turčija\")\nrasti_t$vrsta <- \"podatki\"\nnames(rasti_t)[names(rasti_t) == \"delez\"] <- \"rast\"\nmodel7t <- lm(rast~leto, data=rasti_t)\nprt <- predict(model7t, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_rasti_t <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(prt[1], prt[2], prt[3], prt[4], prt[5], prt[6]))\nnapoved_rasti_t$drzava <- turcija\nnapoved_rasti_t$vrsta <- \"napoved\"\nskupne_rasti_t <- rbind(rasti_t, napoved_rasti_t)\n\ngrcija = c('Grčija')\nrasti_g <- primerjava_rasti_log %>% filter(drzava==\"Grčija\")\nrasti_g$vrsta <- \"podatki\"\nnames(rasti_g)[names(rasti_g) == \"delez\"] <- \"rast\"\nmodel7g <- lm(rast~leto, data=rasti_g)\nprg <- predict(model7g, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_rasti_g <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(prg[1], prg[2], prg[3], prg[4], prg[5], prg[6]))\nnapoved_rasti_g$drzava <- grcija\nnapoved_rasti_g$vrsta <- \"napoved\"\nskupne_rasti_g <- rbind(rasti_g, napoved_rasti_g)\n\nnapoved_rasti <- rbind(skupne_rasti_b, skupne_rasti_g, skupne_rasti_t)\n\ngraf7a <- ggplot(napoved_rasti, aes(x=leto, y=rast, col=drzava, shape=vrsta)) +\n geom_point() + ggtitle(\"Napoved rasti držav z največjo rastjo\") + \n xlab(\"leto\") + ylab(\"delež v %\") + facet_grid(. ~ drzava) + stat_smooth(method=\"lm\") +\n coord_trans(y=logisticna_trans) + scale_y_continuous(breaks=logisticna_breaks,\n labels=logisticna)\n\n################################################################################################\n\nprimerjava_rasti_komunikacije_log <- primerjava_rasti_komunikacije %>% mutate(delez=logisticna_inv(delez))\n\ngraf8 <- ggplot(primerjava_rasti_komunikacije_log %>% filter(drzava %in% c(\"Latvija\", \"Estonija\", \"Danska\", \"Bolgarija\", \"Italija\")),\n aes(x=leto, y=delez, col=drzava)) +\n geom_point() + ggtitle(\"Primerjava rasti držav z največjo in najmanjšo stopnjo komunikacije\") + \n xlab(\"leto\") + ylab(\"delež v %\") + facet_grid(. ~ drzava) + stat_smooth(method=\"lm\") +\n coord_trans(y=logisticna_trans) + scale_y_continuous(breaks=logisticna_breaks,\n labels=logisticna) + \n theme(axis.text.x=element_text(angle=45, vjust=0.5, hjust=1))\n\nkomunikacija_b <- primerjava_rasti_komunikacije_log %>% filter(drzava==\"Bolgarija\")\nkomunikacija_b$vrsta <- \"podatki\"\nnames(komunikacija_b)[names(komunikacija_b) == \"delez\"] <- \"rast\"\nmodel8b <- lm(rast~leto, data=komunikacija_b)\nprb <- predict(model8b, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_komunikacije_b <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(prb[1], prb[2], prb[3], prb[4], prb[5], prb[6]))\nnapoved_komunikacije_b$drzava <- bolgarija\nnapoved_komunikacije_b$vrsta <- \"napoved\"\nskupna_komunikacija_b <- rbind(komunikacija_b, napoved_komunikacije_b)\n\ndanska <- c('Danska')\nkomunikacija_d <- primerjava_rasti_komunikacije_log %>% filter(drzava==\"Danska\")\nkomunikacija_d$vrsta <- \"podatki\"\nnames(komunikacija_d)[names(komunikacija_d) == \"delez\"] <- \"rast\"\nmodel8d <- lm(rast~leto, data=komunikacija_d)\nprd <- predict(model8d, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_komunikacije_d <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(prd[1], prd[2], prd[3], prd[4], prd[5], prd[6]))\nnapoved_komunikacije_d$drzava <- danska\nnapoved_komunikacije_d$vrsta <- \"napoved\"\nskupna_komunikacija_d <- rbind(komunikacija_d, napoved_komunikacije_d)\n\nestonija <- c('Estonija')\nkomunikacija_e <- primerjava_rasti_komunikacije_log %>% filter(drzava==\"Estonija\")\nkomunikacija_e$vrsta <- \"podatki\"\nnames(komunikacija_e)[names(komunikacija_e) == \"delez\"] <- \"rast\"\nmodel8e <- lm(rast~leto, data=komunikacija_e)\npre <- predict(model8e, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_komunikacije_e <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(pre[1], pre[2], pre[3], pre[4], pre[5], pre[6]))\nnapoved_komunikacije_e$drzava <- estonija\nnapoved_komunikacije_e$vrsta <- \"napoved\"\nskupna_komunikacija_e <- rbind(komunikacija_e, napoved_komunikacije_e)\n\nitalija <- c('Italija')\nkomunikacija_i <- primerjava_rasti_komunikacije_log %>% filter(drzava==\"Italija\")\nkomunikacija_i$vrsta <- \"podatki\"\nnames(komunikacija_i)[names(komunikacija_i) == \"delez\"] <- \"rast\"\nmodel8i <- lm(rast~leto, data=komunikacija_i)\npri <- predict(model8i, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_komunikacije_i <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(pri[1], pri[2], pri[3], pri[4], pri[5], pri[6]))\nnapoved_komunikacije_i$drzava <- italija\nnapoved_komunikacije_i$vrsta <- \"napoved\"\nskupna_komunikacija_i <- rbind(komunikacija_i, napoved_komunikacije_i)\n\nlatvija <- c('Latvija')\nkomunikacija_l <- primerjava_rasti_komunikacije_log %>% filter(drzava==\"Latvija\")\nkomunikacija_l$vrsta <- \"podatki\"\nnames(komunikacija_l)[names(komunikacija_l) == \"delez\"] <- \"rast\"\nmodel8l <- lm(rast~leto, data=komunikacija_l)\nprl <- predict(model8l, data.frame(leto=seq.int(2020, 2025, 1)))\nnapoved_komunikacije_l <- data.frame(leto = c(2020, 2021, 2022, 2023, 2024, 2025), rast = c(prl[1], prl[2], prl[3], prl[4], prl[5], prl[6]))\nnapoved_komunikacije_l$drzava <- latvija\nnapoved_komunikacije_l$vrsta <- \"napoved\"\nskupna_komunikacija_l <- rbind(komunikacija_l, napoved_komunikacije_l)\n\nnapoved_komunikacije <- rbind(skupna_komunikacija_b, skupna_komunikacija_d, skupna_komunikacija_e, \n skupna_komunikacija_i, skupna_komunikacija_l)\n\ngraf8a <- ggplot(napoved_komunikacije, aes(x=leto, y=rast, col=drzava, shape=vrsta)) +\n geom_point() + ggtitle(\"Napoved komunikacije državljanov z oblastmi\") + \n xlab(\"leto\") + ylab(\"delež v %\") + facet_grid(. ~ drzava) + stat_smooth(method=\"lm\") +\n coord_trans(y=logisticna_trans) + scale_y_continuous(breaks=logisticna_breaks,\n labels=logisticna) +\n theme(axis.text.x=element_text(angle=45, vjust=0.5, hjust=1))\n", "meta": {"hexsha": "ea93dfe90827d93dae9e1d7719b04089fa04262a", "size": 7497, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "M4rble/APPR-2019-20", "max_stars_repo_head_hexsha": "f247539508025cb8c0ccfb0d9c9d2d60118f51ef", "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": "M4rble/APPR-2019-20", "max_issues_repo_head_hexsha": "f247539508025cb8c0ccfb0d9c9d2d60118f51ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-12-15T15:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T21:41:32.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "M4rble/APPR-2019-20", "max_forks_repo_head_hexsha": "f247539508025cb8c0ccfb0d9c9d2d60118f51ef", "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": 54.3260869565, "max_line_length": 140, "alphanum_fraction": 0.6921435241, "num_tokens": 2773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.655965674385415}} {"text": "install.packages(\"rstan\", repos = \"https://cloud.r-project.org/\", dependencies = TRUE)\nlibrary(rstan)\n\ny <- read.table(\"hw4data_stan.txt\")\nN <- length(y[,1])\n\nplot(density(y[,1]))\nplot(density(y[,2]))\nplot(density(y[,3]))\nplot(density(y[,4]))\n\n## stan data\nstan_data <- list(N = N, y = y, K = 3, D = 4)\n\nwrite(\"// Stan model\n\n data {\n int N; // sample size\n int D; // dimension of observed vars\n int K; // number of latent groups\n vector[D] y[N]; // data\n }\n\n parameters {\n ordered[K] mu; // locations of hidden states\n vector[K] sigma; // variances of hidden states\n simplex[K] theta[D]; // mixture components\n }\n \n model {\n vector[K] obs[D];\n \n // priors\n for(k in 1:K){\n mu[k] ~ normal(0,10);\n sigma[k] ~ inv_gamma(1,1);\n }\n\n for(d in 1:D){\n theta[d] ~ dirichlet(rep_vector(2.0, K));\n }\n \n \n // likelihood\n for(d in 1:D){\n for(i in 1:N) {\n for(k in 1:K) {\n obs[d][k] = log(theta[d][k]) + normal_lpdf(y[i][d] | mu[k], sigma[k]);\n }\n target += log_sum_exp(obs[d]);\n } \n }\n } \",\n\n\"stan_model.stan\")\n\n## check\nstanc(\"stan_model.stan\")\n\n## save filepath\nstan_model <- \"stan_model.stan\"\n\n## fit\nfit <- stan(file = stan_model, data = stan_data, warmup = 500, iter = 1000, chains = 4, cores = 2, thin = 1)\n\n## check it out\nfit\n\n## look at posterior\nposterior <- extract(fit)\nhist(posterior$mu)\n\n## some other diagnostics\ntraceplot(fit)\nstan_dens(fit)\nstan_hist(fit)\n\n## try out some variational inference methods in Stan...\nm <- stan_model(file = \"stan_model.stan\")\nfit2 <- vb(m, data = stan_data, algorithm = \"meanfield\")\nfit2\n", "meta": {"hexsha": "7d842c628b097d05dd6378d2c20c28a55cac7fab", "size": 1789, "ext": "r", "lang": "R", "max_stars_repo_path": "hw/stanhw.r", "max_stars_repo_name": "harryreyesnieva/p8124_graphical_models", "max_stars_repo_head_hexsha": "2b4c6e90a83a5a0be99cbbe78c9f73d636ceff15", "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": "hw/stanhw.r", "max_issues_repo_name": "harryreyesnieva/p8124_graphical_models", "max_issues_repo_head_hexsha": "2b4c6e90a83a5a0be99cbbe78c9f73d636ceff15", "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": "hw/stanhw.r", "max_forks_repo_name": "harryreyesnieva/p8124_graphical_models", "max_forks_repo_head_hexsha": "2b4c6e90a83a5a0be99cbbe78c9f73d636ceff15", "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": 21.8170731707, "max_line_length": 108, "alphanum_fraction": 0.5399664617, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.655816038988195}} {"text": "# Example : 2.5B Chapter : 2.5 Pageno : 88\n# Inverse of the given matrices\nB<-matrix(c(4,8,3,7),ncol=2)\nC<-matrix(c(6,6,6,0),ncol=2)\nS<-matrix(c(1,1,1,0,1,1,0,0,1),ncol=3)\nB1<-solve(B)\nC1<-solve(C)\nS1<-solve(S)\nprint(\"Inverses of given matrices \")\nprint(B1)\nprint(C1)\nprint(S1)", "meta": {"hexsha": "2266f6ca549f237199990e01e32548fb1bcf98a0", "size": 281, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.5.b/Ex2_2.5B.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.5.b/Ex2_2.5B.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.5.b/Ex2_2.5B.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 23.4166666667, "max_line_length": 46, "alphanum_fraction": 0.6441281139, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.655795887914907}} {"text": "##### rmse function\r\nrmse <- function(y, yhat){\r\n\r\n\tyhat[yhat < 0] = 0\r\n\tr = sqrt(mean((y - yhat)^2));\r\n\treturn(r);\r\n}\r\n##### rmsle function\r\nrmsle <- function(y, yhat){\r\n\r\n\tyhat[yhat < 0] = 0\r\n\tr = sqrt(mean((log(y+1) - log(yhat+1))^2));\r\n\treturn(r);\r\n}\r\n#################################################################\r\n# RMSLE based Objective function t\r\nrmsle_objfun <- function(beta,y,x){\r\n\t\r\n\tyhat = x%*%beta;\r\n\tyhat[yhat <0] =0;\r\n\tres <- rmsle(y,yhat)\r\n\t#n = length(y);\r\n\t#attr(res, \"gradient\") <- -t((log(y+1) - log(yhat+1))/(yhat+1))%*%x/(n*res); \r\n\treturn(res);\r\n}\r\n# RMSLog_Yratio based Objective function\r\nrmslyr_objfun <- function(beta,yr,x){\r\n\t\r\n\tyrhat = x%*%beta;\r\n\t\r\n\tres <- sqrt(mean((log(yr) - log(yrhat))^2));\t\r\n\treturn(res);\r\n}\r\n# RMSE based Objective function\r\nrmse_objfun <- function(beta,y,x){\r\n\t\r\n\tyhat = x%*%beta;\r\n\t\r\n\tres <- sqrt(mean((y - yhat)^2));\t\r\n\treturn(res);\r\n}\r\n\r\n###################################################################\r\nsingle_test <- function(dtest,params,onresids=F){\r\n\ttest.x = as.matrix(dtest$X)\r\n\tif (onresids){\r\n\t\t\r\n\t\tyratio_hat <- test.x %*% params\r\n\t\ttest.yhat <- yratio_hat*dtest$yhat_prev + yratio_hat - 1\r\n\t}\r\n\telse{\r\n\t\ttest.yhat <- test.x %*% params\r\n\t}\r\n test.yhat[test.yhat < 0] = 0\r\n\ttest.rmsle <- rmsle(dtest$Y, test.yhat)\r\n\treturn(list(rmsle = test.rmsle,yhat=test.yhat))\r\n\r\n}\r\nsingle_fit <- function(dtrain,init.param,onresids=F){\r\n\t\r\n\ttrain.x = as.matrix(dtrain$X)\r\n\tif(onresids){\r\n\t\toptim.y = dtrain$yratio\t\r\n\t\t# oout = nlm(rmslyr_objfun, init.param, optim.y,train.x);\r\n\t\t# oout = nlm(rmse_objfun, init.param, optim.y,train.x);\r\n\t\t\r\n\t\toout = optim(init.param, rmslyr_objfun, gr = NULL, optim.y, train.x, method = \"BFGS\", control=list((maxit = 1E3)));\r\n\t}\r\n\telse{\r\n\t\toptim.y = dtrain$Y\r\n\t\t# oout = nlm(rmsle_objfun, init.param, optim.y,train.x);\r\n\t\t\r\n\t\toout = optim(init.param, rmsle_objfun, gr = NULL, optim.y, train.x, method = \"BFGS\", control=list((maxit = 1E3)));\r\n\t}\t\r\n\t\r\n\t# fminval = oout$minimum\r\n\t# params = oout$estimate\r\n\tfminval = oout$value\r\n\tparams = oout$par\r\n\t\r\n\tif (onresids){\r\n\t\tyratio_hat <- train.x %*% params\r\n\t\ttrain.yhat <- yratio_hat*dtrain$yhat_prev + yratio_hat - 1\r\n\t\t\r\n\t}\r\n\telse{\r\n\t\ttrain.yhat <- train.x %*% params\r\n\t}\r\n\ttrain.rmsle <- rmsle(dtrain$Y, train.yhat)\r\n\t\r\n\tres = list(params = params, fminval = fminval, train.rmsle = train.rmsle)\r\n\treturn(res)\r\n}\r\nmycortest <- function(X,Y){\r\n\trandind = sample(1:length(Y),length(Y))\r\n\tpY = Y[randind]\r\n\t\r\n\tpar(mfrow=c(2,1))\r\n\t\r\n\tplot(X,Y,main=round(cor(X,Y),2));\r\n\tabline(h=0,lwd=2,col='red')\r\n\t#mod = lm(formula = Y[X>300] ~ X[X>300])\r\n\t#abline(a=mod$coef[1],b=mod$coef[2],col='green',lwd=2)\r\n\t\r\n\tplot(X,pY,main=round(cor(X,pY),2))\r\n\tabline(h=0,lwd=2,col='red')\r\n\t\r\n}\r\n\r\n###################################################################\r\nnfold_jknife <- function(dall,Nf,test_frac,init.param,onresids=F,fullres = F){\r\n\tN = length(dall$Y)\r\n\tNtest = floor(N*test_frac)\r\n\tset.seed(59);\r\n\t\r\n\tparams = matrix(0,Nf,length(init.param))\t\r\n\tfminval = rep(0,Nf)\r\n\ttrain.rmsle = rep(0,Nf)\r\n\ttest.rmsle = rep(0,Nf)\r\n if(fullres==T){\r\n test.inds = matrix(0,Ntest,Nf)\r\n test.pred = matrix(0,Ntest,Nf)\r\n }\r\n\tfor (i in 1:Nf){\r\n\t\ttest_inds = sample(1:N, Ntest);\t\r\n\t\ttest.X = dall$X[test_inds,]\r\n\t\ttest.Y = dall$Y[test_inds]\r\n\t\ttrain.X = dall$X[-test_inds,]\r\n\t\ttrain.Y = dall$Y[-test_inds]\r\n\t\t\r\n\t\tif(onresids){\r\n\t\t\ttest.yhat_prev = dall$yhat_prev[test_inds]\r\n\t\t\ttest.yratio = dall$yratio[test_inds]\r\n\t\t\ttrain.yhat_prev = dall$yhat_prev[-test_inds]\r\n\t\t\ttrain.yratio = dall$yratio[-test_inds]\r\n\t\t\t\r\n\t\t\tdtrain = list(X = train.X, Y = train.Y, yhat_prev = train.yhat_prev, yratio = train.yratio)\r\n\t\t\tdtest = list(X = test.X, Y = test.Y, yhat_prev = test.yhat_prev, yratio = test.yratio)\r\n\t\t}else{\r\n\t\t\tdtrain = list(X = train.X, Y = train.Y)\r\n\t\t\tdtest = list(X = test.X, Y = test.Y)\r\n\t\t}\r\n\t\tr <- single_fit(dtrain,init.param,onresids)\r\n\t\t\r\n\t\t# Store the results\r\n\t\tparams[i,] <- r$params\r\n\t\tfminval[i] <- r$fminval\r\n\t\ttrain.rmsle[i] <- r$train.rmsle\r\n rtest = single_test(dtest,r$params,onresids)\r\n\t\ttest.rmsle[i] <- rtest$rmsle\r\n if(fullres==T){\r\n test.pred[,i] = rtest$yhat\r\n test.inds[,i] = test_inds\r\n }\r\n\t\tcat(sprintf('JK-iter %i, train rmsle %.6f, test rmsle %.6f\\n',i,train.rmsle[i],test.rmsle[i]))\r\n\t\tflush.console()\r\n\t}\r\n if(fullres==T){\r\n res = list(params=params,fminvals = fminval, train.rmsle = train.rmsle, test.rmsle = test.rmsle, test.inds = test.inds, test.pred = test.pred)\r\n }else{\r\n\t res = list(params=params,fminvals = fminval, train.rmsle = train.rmsle, test.rmsle = test.rmsle)\r\n }\r\n cat(sprintf('AggRes:: median(train rmsle) %.6f, median(test rmsle) %.6f\\n',median(train.rmsle),median(test.rmsle)))\r\n flush.console()\r\n\treturn(res)\r\n}\r\n\r\n\r\nrmsle_fun <- function(beta,y,x){\r\nn = length(y);\r\nyhat = x%*%beta;\r\nyhat[yhat <0] =0;\r\nres <- sqrt(mean((log(y+1) - log(yhat+1))^2));\r\n#attr(res, \"gradient\") <- -t((log(y+1) - log(yhat+1))/(yhat+1))%*%x/(n*res); \r\nreturn(res);\r\n}\r\n\r\n###################################################################\r\n\r\nFitValidatePredictAll <- function(y.train, x.train, x.lead, model1, model2, model3, beta1, beta2, beta3){\r\n\r\nn = length(y.train);\r\nloss.train = rep(0,4); ### seg1, seg2, seg3, overall\r\nloss.test = rep(0,4); ### seg1, seg2, seg3, overall\r\n### do a training-test split (80-20)\r\n### fit on training, validate on test and return joint fit coefficients\r\nset.seed(39);\r\nsamp = sample(1:n, floor(0.8*n));\r\nx.tr = x.train[samp,];\r\ny.tr = y.train[samp];\r\nx.te = x.train[-samp,];\r\ny.te = y.train[-samp];\r\n\r\n#####################################################################\r\n### Fit on the training -seg1\r\n#####################################################################\r\nx1 = as.matrix(cbind(1, x.tr[x.tr$seg==1, model1]));\r\ny1 = y.tr[x.tr$seg ==1];\r\np1 = length(model1)+1;\r\nmod1 = optim(beta1, rmsle_fun, gr = NULL, y1, x1 , method = \"BFGS\");\r\n\r\n### Predict on test -seg1\r\nx1.te = as.matrix(cbind(1, x.te[x.te$seg==1, model1]));\r\ny1.te = y.te[x.te$seg ==1];\r\npred1.te = x1.te%*%mod1$par;\r\npred1.te[pred1.te <0] =0;\r\n\r\n### compute loss\r\n#loss.train[1] = mod1$minimum;\r\nloss.test[1] = rmsle(y1.te, pred1.te);\r\n\r\n#################################################################33\r\n### Fit on the training -seg2\r\n###################################################################\r\nx2 = as.matrix(cbind(1, x.tr[x.tr$seg==2, model2]));\r\ny2 = y.tr[x.tr$seg ==2];\r\np2 = length(model2)+1;\r\nmod2 = optim(beta2, rmsle_fun, gr = NULL, y2, x2, method = \"BFGS\");\r\n\r\n### Predict on test -seg2\r\nx2.te = as.matrix(cbind(1, x.te[x.te$seg==2, model2]));\r\ny2.te = y.te[x.te$seg ==2];\r\npred2.te = x2.te%*%mod2$par;\r\npred2.te[pred2.te <0] =0;\r\n\r\n### compute loss\r\n#loss.train[2] = mod2$minimum;\r\nloss.test[2] = rmsle(y2.te, pred2.te);\r\n\r\n#################################################################33\r\n### Fit on the training -seg3\r\n###################################################################\r\nx3 = as.matrix(cbind(1, x.tr[x.tr$seg==3, model3]));\r\ny3 = y.tr[x.tr$seg ==3];\r\np3 = length(model3)+1;\r\nmod3 = optim(beta3, rmsle_fun, gr = NULL, y3, x3, method = \"BFGS\");\r\n\r\n### Predict on test -seg3\r\nx3.te = as.matrix(cbind(1, x.te[x.te$seg ==3, model3]));\r\ny3.te = y.te[x.te$seg ==3];\r\npred3.te = x3.te%*%mod3$par;\r\npred3.te[pred3.te <0] =0;\r\n\r\n### compute loss\r\n#loss.train[3] = mod3$minimum;\r\nloss.test[3] = rmsle(y3.te, pred3.te);\r\n\r\n#######################################################################\r\n### Compute Overall loss\r\n#######################################################################\r\nfit = rep(0,nrow(x.tr));\r\nfit[x.tr$seg ==1] = x1%*%mod1$par;\r\nfit[x.tr$seg ==2] = x2%*%mod2$par;\r\nfit[x.tr$seg ==3] = x3%*%mod3$par;\r\nfit[fit <0] =0;\r\n\r\npred.te = rep(0,nrow(x.te));\r\npred.te[x.te$seg ==1] = x1.te%*%mod1$par;\r\npred.te[x.te$seg ==2] = x2.te%*%mod2$par;\r\npred.te[x.te$seg ==3] = x3.te%*%mod3$par;\r\npred.te[pred.te <0] =0;\r\n\r\nloss.train[1] = rmsle(y.tr[x.tr$seg ==1], fit[x.tr$seg ==1]);\r\nloss.train[2] = rmsle(y.tr[x.tr$seg ==2], fit[x.tr$seg ==2]);\r\nloss.train[3] = rmsle(y.tr[x.tr$seg ==3], fit[x.tr$seg ==3]);\r\nloss.train[4] = rmsle(y.tr, fit);\r\nloss.test[4] = rmsle(y.te, pred.te);\r\n\r\n##########################################################################\r\n### Generate prediction for the leaderboard\r\n##########################################################################\r\nx1.lead = as.matrix(cbind(1, x.lead[x.lead$seg==1, model1]));\r\nx2.lead = as.matrix(cbind(1, x.lead[x.lead$seg==2, model2]));\r\nx3.lead = as.matrix(cbind(1, x.lead[x.lead$seg==3, model3]));\r\n\r\npred.lead = rep(0, nrow(x.lead));\r\npred.lead[x.lead$seg ==1] = x1.lead%*%mod1$par;\r\npred.lead[x.lead$seg ==2] = x2.lead%*%mod2$par;\r\npred.lead[x.lead$seg ==3] = x3.lead%*%mod3$par;\r\npred.lead[pred.lead <0] =0;\r\n\r\n\r\nr = list(loss.train = loss.train, loss.test = loss.test, seg1.beta = mod1$par, seg2.beta = mod2$par,\r\nseg3.beta = mod3$par, pred.lead = pred.lead);\r\nreturn(r);\r\n}\r\n", "meta": {"hexsha": "23b3113f234a3f4efc37df75c0f2d5ef01df3fe0", "size": 8903, "ext": "r", "lang": "R", "max_stars_repo_path": "Models/helper_functions.r", "max_stars_repo_name": "kvdesai/wikipedia-challenge", "max_stars_repo_head_hexsha": "6d558b0b50c67cc37410ccefeba9471c1374ff94", "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": "Models/helper_functions.r", "max_issues_repo_name": "kvdesai/wikipedia-challenge", "max_issues_repo_head_hexsha": "6d558b0b50c67cc37410ccefeba9471c1374ff94", "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": "Models/helper_functions.r", "max_forks_repo_name": "kvdesai/wikipedia-challenge", "max_forks_repo_head_hexsha": "6d558b0b50c67cc37410ccefeba9471c1374ff94", "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.0209059233, "max_line_length": 147, "alphanum_fraction": 0.5385825003, "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6557958785481021}} {"text": "### FIRST PART\n\ncalcCurvature <- function(trip,nlag) {\n\n ib=seq(2,nrow(trip)-1)\n ia=ib-1\n ic=ib+1\n A_x = trip$x[ia]\n B_x = trip$x[ib]\n C_x = trip$x[ic]\n A_y = trip$y[ia]\n B_y = trip$y[ib]\n C_y = trip$y[ic]\n D = 2 * (A_x*(B_y - C_y) + B_x*(C_y - A_y) + C_x*(A_y - B_y) )\n U_x = ((A_x^2 + A_y^2) * (B_y - C_y) + (B_x^2 + B_y^2) * (C_y - A_y) + (C_x^2 + C_y^2) * (A_y - B_y)) / D\n U_y = ((A_x^2 + A_y^2) * (C_x - B_x) + (B_x^2 + B_y^2) * (A_x - C_x) + (C_x^2 + C_y^2) * (B_x - A_x)) / D\n R = sqrt((A_x - U_x)^2 + (A_y - U_y)^2)\n # cur <- data.table(center_x = c(NA, U_x, NA),\n # center_y = c(NA, U_y, NA),\n # radius = c(NA, R, NA))\n mlag <- nlag\n if (nlag %% 2 == 0) {\n mlag <- nlag + 1\n }\n f21 <- rep(1/mlag,mlag)\n smth_x <- filter(U_x, f21, sides=2)\n smth_y <- filter(U_y, f21, sides=2)\n smth_R <- filter(R, f21, sides=2)\n cur_smooth <- data.table(center_x = c(NA, smth_x, NA),\n center_y = c(NA, smth_y, NA),\n radius = c(NA, smth_R, NA))\n return(cur_smooth)\n}\n\nspeedDistribution <- function(trip)\n{\n \n \n vitesse = 3.6*sqrt(diff(trip$x,1,1)^2 + diff(trip$y,1,1)^2)/20\n \n vitesse5 = 3.6*sqrt(diff(trip$x,5,1)^2 + diff(trip$y,5,1)^2)/20\n \n vitesse10 = 3.6*sqrt(diff(trip$x,10,1)^2 + diff(trip$y,10,1)^2)/20\n \n vitesse20 = 3.6*sqrt(diff(trip$x,20,1)^2 + diff(trip$y,20,1)^2)/20 \n \n tangacel = 3.6*sqrt(diff(trip$x,1,2)^2 + diff(trip$y,1,2)^2)/20\n \n tangacel5 = 3.6*sqrt(diff(trip$x,5,2)^2 + diff(trip$y,5,2)^2)/20\n \n tangacel10 = 3.6*sqrt(diff(trip$x,10,2)^2 + diff(trip$y,10,2)^2)/20\n \n tangacel20 = 3.6*sqrt(diff(trip$x,20,2)^2 + diff(trip$y,20,2)^2)/20\n\n cur <- calcCurvature(trip,1)\n cur5 <- calcCurvature(trip,5)\n cur10 <- calcCurvature(trip,10)\n cur20 <- calcCurvature(trip,20)\n \n acelnorm = c(rep(NA,1),vitesse)/cur$radius\n acelnorm5 = c(rep(NA,5),vitesse5)/cur5$radius\n acelnorm10 = c(rep(NA,10),vitesse10)/cur10$radius\n acelnorm20 = c(rep(NA,20),vitesse20)/cur20$radius\n \n aceltotal = acelnorm + c(rep(NA,2),tangacel)\n aceltotal5 = acelnorm5 + c(rep(NA,10),tangacel5)\n aceltotal10 = acelnorm10 + c(rep(NA,20),tangacel10)\n aceltotal20 = acelnorm20 + c(rep(NA,40),tangacel20)\n \n dist = sum(vitesse) \n acel = diff(vitesse,1,1)\n \n features = c( cbind(quantile(vitesse, seq(0.05,1, by = 0.05)), \n quantile(vitesse5, seq(0.05,1, by = 0.05)), \n quantile(vitesse10, seq(0.05,1, by = 0.05)), \n quantile(vitesse20, seq(0.05,1, by = 0.05)), \n quantile(tangacel, seq(0.05,1, by = 0.05)), \n quantile(tangacel5, seq(0.05,1, by = 0.05)), \n quantile(tangacel10, seq(0.05,1, by = 0.05)), \n quantile(tangacel20, seq(0.05,1, by = 0.05)),\n quantile(cur$radius[is.finite(cur$radius) ] , seq(0.05,1, by = 0.05), na.rm = T), \n quantile(cur5$radius[is.finite(cur5$radius) ] , seq(0.05,1, by = 0.05), na.rm = T), \n quantile(cur10$radius[is.finite(cur10$radius) ] , seq(0.05,1, by = 0.05), na.rm = T), \n quantile(cur20$radius[is.finite(cur20$radius) ] , seq(0.05,1, by = 0.05), na.rm = T), \n quantile(acelnorm, seq(0.05,1, by = 0.05), na.rm = T), \n quantile(acelnorm5, seq(0.05,1, by = 0.05), na.rm = T),\n quantile(acelnorm10, seq(0.05,1, by = 0.05), na.rm = T), \n quantile(acelnorm20, seq(0.05,1, by = 0.05), na.rm = T), \n quantile(aceltotal, seq(0.05,1, by = 0.05), na.rm = T), \n quantile(aceltotal5, seq(0.05,1, by = 0.05), na.rm = T),\n quantile(aceltotal10, seq(0.05,1, by = 0.05), na.rm = T), \n quantile(aceltotal20, seq(0.05,1, by = 0.05), na.rm = T),\n quantile(acel, seq(0.05,1, by = 0.05)))\n ,\n length(trip[,1]), var(vitesse), var(vitesse5), var(vitesse10), var(vitesse20),\n var(tangacel), var(tangacel5), var(tangacel10), var(tangacel20),\n var(acelnorm,na.rm = T), var(acelnorm5,na.rm = T), var(acelnorm10,na.rm = T), \n var(acelnorm20,na.rm = T), var(acel,na.rm = T))\n \n return(features)\n}\n\n\n### SECOND PART (BASED ON DEXUAN'S CODE)\n\n\nfeatures2 <- function(trip)\n{\n v = NULL\n angle = NULL\n acceleration = NULL\n deceleration = NULL\n turning_speed = NULL\n distancesum = 0\n shift = -1\n\n for(i in 2:length(trip[,1])){\n dist = sqrt((trip$x[i-1] - trip$x[i])^2 + (trip$y[i-1] - trip$y[i])^2)\n v = rbind(v,dist)\n distancesum = distancesum + dist\n \n flag = 1\n if(i > 2){\n if(v[i-1] >= v[i-2]){\n acceleration = rbind(acceleration, (v[i-1]-v[i-2]))\n \n if(flag == 0){\n shift = shift + 1\n flag = 1\n }\n \n }\n else{\n deceleration = rbind(deceleration, (v[i-2]-v[i-1]))\n if(flag == 1){\n shift = shift + 1\n flag = 0\n }\n \n }\n \n dist_2 = sqrt((trip$x[i-2] - trip$x[i])^2 + (trip$y[i-2] - trip$y[i])^2)\n if(v[i-1]*v[i-2] != 0){\n cosin = (v[i-1]*2+v[i-2]*2-dist_2*2)/(2*v[i-1]*v[i-2])\n } \n else{\n cosin = -1\n }\n angle = rbind(angle,(pi-acos(max(min(cosin, 1), -1))))\n temp = angle[i-2]*(v[i-1]+v[i-2])/2\n #if temp>0:\n turning_speed = rbind(turning_speed,temp)\n } \n \n }\n \n features = c(cbind(quantile(v, seq(0.05,1, by = 0.05)),\n quantile(angle, seq(0.05,1, by = 0.05)),\n quantile(acceleration, seq(0.05,1, by = 0.05)),\n quantile(deceleration, seq(0.05,1, by = 0.05)),\n quantile(turning_speed, seq(0.05,1, by = 0.05))),\n var(v),var(angle),var(acceleration),var(deceleration),\n var(turning_speed),distancesum,shift)\n \n return(features)\n \n}\n", "meta": {"hexsha": "55e4a827af21d6ea7353fe28bf021013909236a6", "size": 5935, "ext": "r", "lang": "R", "max_stars_repo_path": "Randomforest.r", "max_stars_repo_name": "kevinhsu/Use-Telematic-Data-to-Identify-a-Driver-Signature", "max_stars_repo_head_hexsha": "3893a61cdf83dba60aa526a0f8d0972ac459b56f", "max_stars_repo_licenses": ["BSD-2-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": "Randomforest.r", "max_issues_repo_name": "kevinhsu/Use-Telematic-Data-to-Identify-a-Driver-Signature", "max_issues_repo_head_hexsha": "3893a61cdf83dba60aa526a0f8d0972ac459b56f", "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": "Randomforest.r", "max_forks_repo_name": "kevinhsu/Use-Telematic-Data-to-Identify-a-Driver-Signature", "max_forks_repo_head_hexsha": "3893a61cdf83dba60aa526a0f8d0972ac459b56f", "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": 35.3273809524, "max_line_length": 107, "alphanum_fraction": 0.5108677338, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6557921529397419}} {"text": "#' Optimal Rank Beta\n#'\n#' This finds recommends a beta value between two extremes where the rank correlation between the two extremes best agrees.\n#'\n#' @param g An igraph graph object\n#' @param comp.left The beta on the left for comparison\n#' @param comp.right The beta on the right for comparison\n#' @param starting.beta The beta value to start when starting the optimization\n#' @export\n#' @examples\n#' pii(g, pii.beta = optimal.rank.beta(g))\n#'\n\noptimal.rank.beta <- function(g, comp.left = -0.9, comp.right = -0.5, starting.beta = -0.8) {\n rc.diff <- function(b, g, comp.left = comp.left, comp.right = comp.right) {\n p <- pii(g, pii.beta = b)\n pii.left <- pii(g, pii.beta = comp.left)\n pii.right <- pii(g, pii.beta = comp.right)\n rc.left = cor(p, pii.left, method = \"spearman\")\n rc.right = cor(p, pii.right, method = \"spearman\")\n return(abs(rc.left - rc.right))\n }\n\n o <- optim( par = c(starting.beta), fn = rc.diff, gr = NULL,\n g = g, comp.right = comp.right, comp.left = comp.left, method = 'Brent',\n lower = -1, upper = -0.001)\n cross.point <- o$par\n attr(cross.point, 'spearman.correlation') <- cor(pii(g, pii.beta = cross.point), pii(g, pii.beta = cross.point), method = 'spearman')\n attr(cross.point, 'approx') <- o$value\n return(cross.point)\n}\n", "meta": {"hexsha": "01d52098a57a9df88799486ab08152120f1804d2", "size": 1322, "ext": "r", "lang": "R", "max_stars_repo_path": "R/optimal.rank.beta.r", "max_stars_repo_name": "jfaganUK/pii", "max_stars_repo_head_hexsha": "7ad5edddd95d6dcb78ebc4941c13bf2b89f58a7f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-09-05T18:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-05T18:45:42.000Z", "max_issues_repo_path": "R/optimal.rank.beta.r", "max_issues_repo_name": "jfaganUK/pii", "max_issues_repo_head_hexsha": "7ad5edddd95d6dcb78ebc4941c13bf2b89f58a7f", "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/optimal.rank.beta.r", "max_forks_repo_name": "jfaganUK/pii", "max_forks_repo_head_hexsha": "7ad5edddd95d6dcb78ebc4941c13bf2b89f58a7f", "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.3125, "max_line_length": 135, "alphanum_fraction": 0.6346444781, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715777, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6557542958392301}} {"text": "Horner <- function(Coef_Polinomio, x0) {\n # Creación de la función, \n #recibe los coeficientes del polinomio \n #y el punto a evaluar.\n TerminoInd <- Coef_Polinomio[1]\n Coef_Polinomio <- Coef_Polinomio[-1]\n #Guarda el término de independiente en una \n #variable aparte de los coeficientes que \n #acompañan algún valor de \"x\".\n P_x0 <- Coef_Polinomio[length(Coef_Polinomio)]\n P1_x0 <- Coef_Polinomio[length(Coef_Polinomio)]\n j <- length(Coef_Polinomio)-1\n #Guarda los coeficientes no independientes \n #del polinomio en dos variables, \n #y se inicializa la variable iterativa.\n while (j>0) {\n P_x0 <- x0*P_x0 + Coef_Polinomio[j]\n P1_x0 <- x0*P1_x0 + P_x0\n j <- j-1\n }\n #Se aplica el Método de Horner para \n #calcular el valor del polinomio en x0 \n #y el valor de su derivada en x0.\n P_x0 <- (x0*P_x0)+TerminoInd\n #Se suma el término independiente al polinomio, \n #pero no a la derivada, ya que en la \n #derivada este término desaparece.\n cat(paste(\"P(\", x0, \") =\", P_x0,\n \"\\nP'(\", x0, \") =\", P1_x0))\n}\n#Se imprimen los resultados. \n#Siendo P_x0 el valor del polinomio en x0 y \n#P1_x0 el valor de la derivada en x0.\n\n\n\n\nHornerC <- function(Coef_Polinomio, x0) {\n Coef_Polinomio <- as.complex(Coef_Polinomio)\n #Los coeficientes pasan a ser tratados como números complejos.\n TerminoInd <- Coef_Polinomio[1]\n Coef_Polinomio <- Coef_Polinomio[-1]\n P_x0 <- Coef_Polinomio[length(Coef_Polinomio)]\n P1_x0 <- Coef_Polinomio[length(Coef_Polinomio)]\n j <- length(Coef_Polinomio)-1\n while (j>0) {\n P_x0 <- x0*P_x0 + Coef_Polinomio[j]\n P1_x0 <- x0*P1_x0 + P_x0\n j <- j-1\n }\n P_x0 <- (x0*P_x0)+TerminoInd\n cat(paste(\"P(\", x0, \") =\", P_x0,\n \"\\nP'(\", x0, \") =\", P1_x0))\n}\n\n\n\n\ninstall.packages(\"signal\")\nlibrary(signal)\nOperaciones <- 0\n#Se instala un paquete para utilizar \n#la función \"polyval\" más adelante y se \n#inicia el número de operaciones PRINCIPALES en 0.\n\nSeno_Taylor <- function(n){\n Taylor_Pol <- c()\n for(i in 0:n){\n Taylor_Pol <- c(Taylor_Pol,0)\n Taylor_Pol <- c(Taylor_Pol,((-1)^i)/factorial(2*i+1))\n Operaciones <- Operaciones + 1\n }\n return(Taylor_Pol)\n}\n#Esta función recibe un valor de \"n\" \n#y devuelve los coeficientes del polinomio de Taylor \n#de grado \"n\" de la función seno.\n\nNorm <- function(vect1,vect2){\n error_relativo <- 0\n err <- 0\n for(i in 1:length(vect1)){\n error_relativo <- error_relativo + abs(vect1[i]-vect2[i])\n Operaciones <- Operaciones + 1\n err <- err + abs(vect1[i])\n Operaciones <- Operaciones + 1\n }\n return((error_relativo/err)-1)\n}\n#Se define una función que recibe imágenes de dos \n#funciones en los mismos puntos, y devuelve una forma \n#de medir el error que hay entre ellas. \n#En este caso se calcula este error como un ponderado \n#de los valores absolutos de las restas entre valores.\n\nTaylor <- function(error_minimo){\n test_val <- c()\n for(i in seq(from=-pi/64,to=pi/64,by=0.001)){\n test_val <- c(i,test_val)\n }\n #Se generan varios valores en el intervalo de interés \n #y se guardan en la variable \"test_val\".\n iteraciones <- 0\n n <- 0\n e_rel <- 1\n #Se inicializan varias variables. \n #El número de iteraciones en 0, el grado del \n #polinomio de Taylor en 0, y el error relativo en 1.\n cat(\"Iteracion =\",iteraciones,\"\\n\")\n #Se muestra la iteración en la que va el código.\n Aprox_Pol <- Seno_Taylor(n)\n Pol_Ant <- polyval(Aprox_Pol[length(Aprox_Pol):1],test_val)\n #Se inicializa el polinomio de aproximación en grado 0 \n #y se evaluan los datos de prueba en él.\n Operaciones <- Operaciones + 1\n while(e_rel>error_minimo){\n n <- n+1\n Operaciones <- Operaciones + 1\n Aprox_Pol <- Seno_Taylor(n)\n Pol_Act <- polyval(Aprox_Pol[length(Aprox_Pol):1],test_val)\n #La función polyval evalúa el vector de puntos en el \n #polinomio, dados sus coeficientes en orden descendente.\n Operaciones <- Operaciones + 1\n e_rel <- Norm(Pol_Ant,Pol_Act)\n iteraciones <- iteraciones+1\n cat(\"Iteracion =\",iteraciones,\"\\n\")\n cat(\"Error Relativo =\",e_rel,\"\\n\")\n Pol_Ant <- Pol_Act\n }\n #Se lleva a cabo la aproximación de Taylor. \n #A cada iteración se eleva el grado del polinomio de \n #aproximación en 1, se evaluan los datos de prueba en él, \n #y se compara con los valores anteriores bajo la norma \n #definida arriba. Esto se repite hasta que el error sea \n #menor al valor ingresado por el usuario.\n cat(\"Polinomio =\",Aprox_Pol,\"\\n\")\n cat(\"Operaciones =\",Operaciones,\"\\n\")\n #Se imprimen los coeficientes del polinomio \n #que mejor aproxima la función en el intervalo \n #dado y el número de operaciones principales \n #que se realizaron.\n}\n\n\n\n\n\ninstall.packages(\"limSolve\")\ninstall.packages(\"signal\")\nlibrary(signal)\nlibrary(limSolve)\n#Se instalan dos paquetes, uno para poder utilizar la función\n#\"polyval\", y el otro para utilizar la función \"Solve\" más adelante.\n\nNorma_f <- function(p){\n inf <- 0\n ans <- c(0,0)\n for(i in seq(from=-pi/64,to=pi/64,by=0.001)){\n y = abs(sin(i)-polyval(p[length(p):1],i))\n Operaciones <- Operaciones + 1\n if(y3/4)]<- 4\n vertices[which(2/419/20)]<- 20\n vertices[which(18/2019/20)]<- 20\n vertices[which(18/20-1)))\n }\n if (input$shape == \"cube\") {\n return(cube.gen(input$dist.cube*(input$gen>-1)))\n }\n if (input$shape == \"dodec\") {\n return(dodec.gen(input$dist.dodec*(input$gen>-1)))\n }\n }) #CLOSE withProgress\n\n })\n\n output$sctPlot <- renderRglwidget({\n withProgress(message = 'Please wait up to 15 seconds', style = 'notification', value = 1, {\n try(rgl.close())\n withProgress(message = 'Generating Plot', style = 'notification', value = 1, {\n loci <- all.list()[[1]]\n vertices <- all.list()[[2]]\n coords <- all.list()[[3]]\n\n if (max(coords[,4]==4)) {\n set1 <- coords[coords[,4]==1,1:3]\n set2 <- coords[coords[,4]==2,1:3]\n set3 <- coords[coords[,4]==3,1:3]\n set4 <- coords[coords[,4]==4,1:3]\n\n col1 <- brewer.pal(n = 12, name = \"Paired\")[2]\n col2 <- brewer.pal(n = 12, name = \"Paired\")[4]\n col3 <- brewer.pal(n = 12, name = \"Paired\")[8]\n col4 <- brewer.pal(n = 12, name = \"Paired\")[10]\n\n points3d(set1[1:round(nrow(set1)*(input$pts/100),0),1],\n set1[1:round(nrow(set1)*(input$pts/100),0),2],\n set1[1:round(nrow(set1)*(input$pts/100),0),3],\n size = 1.25,col=col1)\n\n points3d(set2[1:round(nrow(set2)*(input$pts/100),0),1],\n set2[1:round(nrow(set2)*(input$pts/100),0),2],\n set2[1:round(nrow(set2)*(input$pts/100),0),3],\n size = 1.25,col=col2)\n\n points3d(set3[1:round(nrow(set3)*(input$pts/100),0),1],\n set3[1:round(nrow(set3)*(input$pts/100),0),2],\n set3[1:round(nrow(set3)*(input$pts/100),0),3],\n size = 1.25,col=col3)\n\n points3d(set4[1:round(nrow(set4)*(input$pts/100),0),1],\n set4[1:round(nrow(set4)*(input$pts/100),0),2],\n set4[1:round(nrow(set4)*(input$pts/100),0),3],\n size = 1.25,col=col4)\n }\n\n if (max(coords[,4]==20)) {\n set1 <- coords[coords[,4]==1,1:3]\n set2 <- coords[coords[,4]==2,1:3]\n set3 <- coords[coords[,4]==3,1:3]\n set4 <- coords[coords[,4]==4,1:3]\n set5 <- coords[coords[,4]==5,1:3]\n set6 <- coords[coords[,4]==6,1:3]\n set7 <- coords[coords[,4]==7,1:3]\n set8 <- coords[coords[,4]==8,1:3]\n set9 <- coords[coords[,4]==9,1:3]\n set10<- coords[coords[,4]==10,1:3]\n set11<- coords[coords[,4]==11,1:3]\n set12<- coords[coords[,4]==12,1:3]\n set13<- coords[coords[,4]==13,1:3]\n set14<- coords[coords[,4]==14,1:3]\n set15<- coords[coords[,4]==15,1:3]\n set16<- coords[coords[,4]==16,1:3]\n set17<- coords[coords[,4]==17,1:3]\n set18<- coords[coords[,4]==18,1:3]\n set19<- coords[coords[,4]==19,1:3]\n set20<- coords[coords[,4]==20,1:3]\n\n col1 <- brewer.pal(n = 12, name = \"Paired\")[2] #dark blue\n col2 <- brewer.pal(n = 12, name = \"Paired\")[4] #dark green\n col3 <- brewer.pal(n = 12, name = \"Paired\")[6] #red\n col4 <- brewer.pal(n = 12, name = \"Paired\")[8] #orange\n col5 <- brewer.pal(n = 11, name = \"RdBu\")[11] #DarkBl\n col6 <- brewer.pal(n = 12, name = \"Paired\")[12] #brown\n col7 <- brewer.pal(n = 8, name = \"Dark2\")[8] #grey\n col8 <- brewer.pal(n = 8, name = \"Accent\")[6] #dark pink\n col20 <- col8\n col19 <- col7\n col18 <- col6\n col17 <- col5\n col16 <- col4\n col15 <- col3\n col14 <- col2\n col13 <- col1\n col12 <- brewer.pal(n = 11, name = \"BrBG\")[9] #SoftBl\n col9 <- brewer.pal(n = 11, name = \"RdBu\")[11] #DarkBl\n col11 <- brewer.pal(n = 11, name = \"PiYG\")[1] #Maroon\n col10 <- brewer.pal(n = 11, name = \"PiYG\")[11] #DarkGrn\n\n points3d(set1[1:round(nrow(set1)*(input$pts/100),0),1],\n set1[1:round(nrow(set1)*(input$pts/100),0),2],\n set1[1:round(nrow(set1)*(input$pts/100),0),3],\n size = 1.25,col=col1)\n\n points3d(set2[1:round(nrow(set2)*(input$pts/100),0),1],\n set2[1:round(nrow(set2)*(input$pts/100),0),2],\n set2[1:round(nrow(set2)*(input$pts/100),0),3],\n size = 1.25,col=col2)\n\n points3d(set3[1:round(nrow(set3)*(input$pts/100),0),1],\n set3[1:round(nrow(set3)*(input$pts/100),0),2],\n set3[1:round(nrow(set3)*(input$pts/100),0),3],\n size = 1.25,col=col3)\n\n points3d(set4[1:round(nrow(set4)*(input$pts/100),0),1],\n set4[1:round(nrow(set4)*(input$pts/100),0),2],\n set4[1:round(nrow(set4)*(input$pts/100),0),3],\n size = 1.25,col=col4)\n\n points3d(set5[1:round(nrow(set5)*(input$pts/100),0),1],\n set5[1:round(nrow(set5)*(input$pts/100),0),2],\n set5[1:round(nrow(set5)*(input$pts/100),0),3],\n size = 1.25,col=col5)\n\n points3d(set6[1:round(nrow(set6)*(input$pts/100),0),1],\n set6[1:round(nrow(set6)*(input$pts/100),0),2],\n set6[1:round(nrow(set6)*(input$pts/100),0),3],\n size = 1.25,col=col6)\n\n points3d(set7[1:round(nrow(set7)*(input$pts/100),0),1],\n set7[1:round(nrow(set7)*(input$pts/100),0),2],\n set7[1:round(nrow(set7)*(input$pts/100),0),3],\n size = 1.25,col=col7)\n\n points3d(set8[1:round(nrow(set8)*(input$pts/100),0),1],\n set8[1:round(nrow(set8)*(input$pts/100),0),2],\n set8[1:round(nrow(set8)*(input$pts/100),0),3],\n size = 1.25,col=col8)\n\n points3d(set9[1:round(nrow(set9)*(input$pts/100),0),1],\n set9[1:round(nrow(set9)*(input$pts/100),0),2],\n set9[1:round(nrow(set9)*(input$pts/100),0),3],\n size = 1.25,col=col9)\n\n points3d(set10[1:round(nrow(set10)*(input$pts/100),0),1],\n set10[1:round(nrow(set10)*(input$pts/100),0),2],\n set10[1:round(nrow(set10)*(input$pts/100),0),3],\n size = 1.25,col=col10)\n\n points3d(set11[1:round(nrow(set11)*(input$pts/100),0),1],\n set11[1:round(nrow(set11)*(input$pts/100),0),2],\n set11[1:round(nrow(set11)*(input$pts/100),0),3],\n size = 1.25,col=col11)\n\n points3d(set12[1:round(nrow(set12)*(input$pts/100),0),1],\n set12[1:round(nrow(set12)*(input$pts/100),0),2],\n set12[1:round(nrow(set12)*(input$pts/100),0),3],\n size = 1.25,col=col12)\n\n points3d(set13[1:round(nrow(set13)*(input$pts/100),0),1],\n set13[1:round(nrow(set13)*(input$pts/100),0),2],\n set13[1:round(nrow(set13)*(input$pts/100),0),3],\n size = 1.25,col=col13)\n\n points3d(set14[1:round(nrow(set14)*(input$pts/100),0),1],\n set14[1:round(nrow(set14)*(input$pts/100),0),2],\n set14[1:round(nrow(set14)*(input$pts/100),0),3],\n size = 1.25,col=col14)\n\n points3d(set15[1:round(nrow(set15)*(input$pts/100),0),1],\n set15[1:round(nrow(set15)*(input$pts/100),0),2],\n set15[1:round(nrow(set15)*(input$pts/100),0),3],\n size = 1.25,col=col15)\n\n points3d(set16[1:round(nrow(set16)*(input$pts/100),0),1],\n set16[1:round(nrow(set16)*(input$pts/100),0),2],\n set16[1:round(nrow(set16)*(input$pts/100),0),3],\n size = 1.25,col=col16)\n\n points3d(set17[1:round(nrow(set17)*(input$pts/100),0),1],\n set17[1:round(nrow(set17)*(input$pts/100),0),2],\n set17[1:round(nrow(set17)*(input$pts/100),0),3],\n size = 1.25,col=col17)\n\n points3d(set18[1:round(nrow(set18)*(input$pts/100),0),1],\n set18[1:round(nrow(set18)*(input$pts/100),0),2],\n set18[1:round(nrow(set18)*(input$pts/100),0),3],\n size = 1.25,col=col18)\n\n points3d(set19[1:round(nrow(set19)*(input$pts/100),0),1],\n set19[1:round(nrow(set19)*(input$pts/100),0),2],\n set19[1:round(nrow(set19)*(input$pts/100),0),3],\n size = 1.25,col=col19)\n\n points3d(set20[1:round(nrow(set20)*(input$pts/100),0),1],\n set20[1:round(nrow(set20)*(input$pts/100),0),2],\n set20[1:round(nrow(set20)*(input$pts/100),0),3],\n size = 1.25,col=col20)\n }\n points3d(loci[,2],loci[,3],loci[,4], size=6,col=\"red\")\n rglwidget()\n }) #Close withProgress\n }) #Close withProgress\n })\n})", "meta": {"hexsha": "bfb526973c809f96897b40305d5c9785ec308333", "size": 24378, "ext": "r", "lang": "R", "max_stars_repo_path": "ChaosGame3D/server.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": "ChaosGame3D/server.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": "ChaosGame3D/server.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": 47.8, "max_line_length": 107, "alphanum_fraction": 0.5404052835, "num_tokens": 10282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6554068081696381}} {"text": "M <- 1\r\nF <- 4\r\n\r\nM_tot <- 4\r\nF_tot <- 6\r\n\r\nEs1 <- choose(M_tot, M) * choose(F_tot, F)\r\nEs2 <- choose(M_tot, M) * choose(F_tot - 1, F - 1)\r\nEs3 <- choose(M_tot - 2, M) * choose(F_tot, F)\r\nprint(Es1)\r\nprint(Es2)\r\nprint(Es3)", "meta": {"hexsha": "2fbb854d989ab7065e0d03ecb3c57bc113847799", "size": 222, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 14.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 14.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 14.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": 18.5, "max_line_length": 51, "alphanum_fraction": 0.5585585586, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6553520433113295}} {"text": "#Helpful equations for ET calculations according to FAO methodology (Allen et al. 1998, FAO Irr Drain Paper 56)\n\n#saturated vapor pressure for a given temperature\ne0=function(temp) 0.6108*exp(17.27*temp/(temp+237.3)) \n\n#this is how FAO suggests one do it for daily esat b/c of nonlinearity of e0 function \nesat=function(tmax,tmin) (e0(tmax)+e0(tmin))/2 \n\n#slope of saturation curve\ns=function(temp) 4098*(0.6108*exp(17.27*temp/(temp+237.3)))/(temp+237.3)^2 \n\n#extraterrestrial (MJ / m^2 / day)\nRa=function(doy,lat){ #lat in decimal degrees #p79 FAO\n psi=(pi/180)*lat\n delta=0.409*sin((2*pi*doy/365)-1.39)\n ws=acos(-tan(psi)*tan(delta))\n dr=1+0.033*cos(2*pi*doy/365)\n Ra=(24*60/pi)*0.082*dr*(ws*sin(psi)*sin(delta)+cos(psi)*cos(delta)*sin(ws))\n Ra\n}\n\n#psychrometric constant [kPa C-1]\npsychro=function(elev){ #elev in m\n press=101.3*((293-0.0065*elev)/293)^5.26\n 0.665e-3*press\n}\n\n#daylength (returns # hours in the day with sunlight. only for areas between 65N-6)\ndaylength=function(lat,doy){\n psi=(pi/180)*lat\n delta=0.409*sin((2*pi*doy/365)-1.39)\n ws=acos(-tan(psi)*tan(delta))\n d=24*ws/pi\n d\n}\n \n#net surface radiation\nRn=function(lat,elev,doy,dew,tmax,tmin,Rs){\n ea=e0(dew)\n Ra=Ra(doy,lat)\n Rso=(0.75+(2e-5)*elev)*Ra #p85\n Rnl=4.903e-9*(((tmax+273)^4+(tmin+273)^4)/2)*(0.34-0.14*sqrt(ea))*(1.35*(Rs/Rso)-0.35) #p86\n Rn=(1-0.23)*Rs-Rnl #(Rns=(1-0.23)Rs) ; Rn=Rns-Rnl p87\n Rn\n}\n", "meta": {"hexsha": "ef30afd46337881ac4af67a06d54e72a9cb5ac27", "size": 1447, "ext": "r", "lang": "R", "max_stars_repo_path": "courses/ess-211/course_material/PET.helper.functions.r", "max_stars_repo_name": "christobal54/aei-grad-school", "max_stars_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "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": "courses/ess-211/course_material/PET.helper.functions.r", "max_issues_repo_name": "christobal54/aei-grad-school", "max_issues_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "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": "courses/ess-211/course_material/PET.helper.functions.r", "max_forks_repo_name": "christobal54/aei-grad-school", "max_forks_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-08T05:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T05:41:45.000Z", "avg_line_length": 31.4565217391, "max_line_length": 111, "alphanum_fraction": 0.6510020733, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6553487859313145}} {"text": "#' @title calcCf\n#'\n#' @description Calculates the frictional resistance coefficient (\\code{Cf})\n#' (dimensionless).\n#'\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param lwl Waterline length (vector of numericals, m) (see \n#' \\code{\\link{calclwl}})\n#' @param seawaterTemp Sea water temperature. Default = 15 (degrees Celsius).\n#' Can supply either a vector of numericals, a single number, or rely on the \n#' default\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#'\n#' @details\n#' Calculates frictional resistance coefficient using the International Tank\n#' Towing Committee (ITTC) 1957 method where:\n#' \\deqn{Cf = \\frac{0.075}{(log(V*Lwl/visc)-2)^2}}{Cf = 0.075/((log(V*Lwl/visc)-2)^2)}\n#'\n#' @return \\code{Cf} (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#'@seealso \\itemize{\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calclwl}}\n#'}\n#'\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcCf(seq(1,5,1), 218.75, 15, 1.025)\n#'\n#' @export\n\n\ncalcCf <- function(shipSpeed, lwl, seawaterTemp=15, seawaterDensity=1.025){\n\n Cf<-0.075/((log10(\n (shipSpeed*lwl)/\n (((43.4233-31.38*seawaterDensity)*\n ((seawaterTemp+20)^(1.72*seawaterDensity-2.202))+\n 4.7478-5.779*seawaterDensity)*(10^(-6)))\n\n )\n -2)^(2))\n\n\n return(Cf)\n}\n\n\n", "meta": {"hexsha": "14fb64f624f2ffb09a8682621e97c50d97ee8022", "size": 1625, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcCf.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/calcCf.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/calcCf.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": 29.0178571429, "max_line_length": 86, "alphanum_fraction": 0.6516923077, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.6553487844471665}} {"text": "# Compare means with Kruskal-Wallis test (nonparametric, because non-normal distribution)\n\ndata <- read.csv('../../results/delay/data_all.csv', sep = ';')\ndata_none <- data[which(data$combination=='combination_0' | data$combination=='combination_1' | data$combination=='combination_2' | data$combination=='combination_3'),]\ndata_triple <- data[which(data$combination=='combination_4' | data$combination=='combination_5' | data$combination=='combination_6' | data$combination=='combination_7'),]\ndata_bgp <- data[which(data$combination=='combination_8' | data$combination=='combination_9' | data$combination=='combination_10' | data$combination=='combination_11'),]\n\n# Means\naggregate(data$time, list(data$combination), median)\n# combination_0 1516.5\n# combination_1 1196.0\n# combination_2 957.0\n# combination_3 935.0\n# combination_4 1479.0\n# combination_5 1193.0\n# combination_6 986.5\n# combination_7 977.5\n# combination_8 1241.0\n# combination_9 679.0\n# combination_10 422.5\n# combination_11 400.5\n\nmedian(data_none$time)\nmedian(data_triple$time)\nmedian(data_bgp$time)\n# None: 1054\n# Triple: 1055.5\n# BGP: 556.5\n\n#boxplot(time ~ combination, data = data, ylab=\"Exec (ms)\", xlab=\"Combination\")\n\n# H0: None == Triple\nkruskal.test(time ~ combination, data = data_none)\nkruskal.test(time ~ combination, data = data_triple)\nkruskal.test(time ~ combination, data = data_bgp)\n# p: 0.2905, 0.2306, 0.002891\n# => Accept H0, equal means => None == Triple", "meta": {"hexsha": "eba093d1b6e5a4bd44a7fbb808bf0caa4aa958f8", "size": 1463, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/delay/tests.r", "max_stars_repo_name": "comunica/Experiments-AMF", "max_stars_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "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/delay/tests.r", "max_issues_repo_name": "comunica/Experiments-AMF", "max_issues_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-04T17:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T11:23:38.000Z", "max_forks_repo_path": "analysis/delay/tests.r", "max_forks_repo_name": "comunica/Experiments-AMF", "max_forks_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "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": 39.5405405405, "max_line_length": 170, "alphanum_fraction": 0.7361585783, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6551558027869658}} {"text": "\r\n\r\n\r\n\r\n\r\n##################################################################\r\n# Calculate Great Circle Distance in m based upon spherical\r\n# trig. \r\n##################################################################\r\n\r\ngreat.circle.distance = function (loc1, loc2, R) {\r\n \r\n names(loc1) = c(\"lon\", \"lat\")\r\n names(loc2) = c(\"lon\", \"lat\")\r\n \r\n if (is.null(R)) R = 6367.436 # radius of earth (geometric mean) km\r\n # if R=1 then distances in radians\r\n if (missing(loc2)) loc2 <- loc1\r\n pi180 = pi/180\r\n coslat1 = cos(loc1$lat * pi180)\r\n sinlat1 = sin(loc1$lat * pi180)\r\n coslon1 = cos(loc1$lon * pi180)\r\n sinlon1 = sin(loc1$lon * pi180)\r\n coslat2 = cos(loc2$lat * pi180)\r\n sinlat2 = sin(loc2$lat * pi180)\r\n coslon2 = cos(loc2$lon * pi180)\r\n sinlon2 = sin(loc2$lon * pi180)\r\n pp = cbind(coslat1 * coslon1, coslat1 * sinlon1, sinlat1) %*%\r\n t(cbind(coslat2 * coslon2, coslat2 * sinlon2, sinlat2))\r\n \r\n d = R * acos(ifelse(pp > 1, 1, pp))\r\n \r\n return(d)\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "4966538a75ace1354adebc344a4069c8f80cd55c", "size": 1028, "ext": "r", "lang": "R", "max_stars_repo_path": "R/great.circle.distance.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/great.circle.distance.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/great.circle.distance.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 27.7837837838, "max_line_length": 70, "alphanum_fraction": 0.4931906615, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6551016716592276}} {"text": "halve <- function(a) floor(a/2)\ndouble <- function(a) a*2\niseven <- function(a) (a%%2)==0\n\nethiopicmult<-function(x,y){\n\tres<-ifelse(iseven(y),0,x)\n\twhile(!y==1){\n\t\tx<-double(x)\n\t\ty<-halve(y)\n\t\tif(!iseven(y)) res<-res+x\n\t}\n\treturn(res)\n}\n\nprint(ethiopicmult(17,34))\n", "meta": {"hexsha": "d105b32b1d17f57101f52179769e2e14da8c0318", "size": 266, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.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/Ethiopian-multiplication/R/ethiopian-multiplication-2.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/Ethiopian-multiplication/R/ethiopian-multiplication-2.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": 16.625, "max_line_length": 31, "alphanum_fraction": 0.6165413534, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6549990086997932}} {"text": "################\n#---PACKAGES---#\n################\nrequire(ggplot2)\nrequire(reshape2)\n\n\n###########################\n#---POISSON SAMPLE PATH---#\n###########################\n# 4 x 12\npaths = 1\nN = 50\n\nrate = 0.1\n\ncolorBeta <- rgb(252, 141, 98, maxColorValue = 255, alpha = 255) \ncolorAlpha <- rgb(141, 160, 203, maxColorValue = 255, alpha = 255) \n\ntheList <- list()\nfor(j in 1 : paths) {\n \n data = data.frame(\n x = rep(NA, 2 * N + 1),\n xend = rep(NA, 2 * N + 1 ),\n y = rep(NA, 2 * N + 1),\n yend = rep(NA, 2 * N + 1),\n path = rep(NA, 2 * N + 1)\n )\n \n data$x[1] = 0\n data$xend[1] = rexp(1, rate = rate)\n \n data$y[1] = sample(c(\"A\", \"C\", \"G\", \"T\"), size = 1)\n data$yend = data$y\n \n ids = seq( from = 1, to = (2 * N - 1), by = 2 )\n \n for(i in ids) {\n \n char = sample(c(\"A\", \"C\", \"G\", \"T\"), size = 1)\n time = rexp(1, rate = rate)\n \n data$x[i + 1] = data$xend[i]\n data$xend[i + 1] = data$x[i + 1]\n \n data$y[i + 1] = data$yend[i]\n data$yend[i + 1] = char\n \n data$x[i + 2] = data$xend[i + 1]\n data$xend[i + 2] = data$x[i + 2] + time\n \n data$y[i + 2] = data$yend[i + 1]\n data$yend[i + 2] = data$y[i + 2]\n \n data$path[i] <- data$path[i + 1] <- data$path[i + 2] <- j\n \n } # END: i\n \n theList[[j]] = data\n} # END: j\n\ndata_melt <- do.call(\"rbind\", theList)\ndata_melt$path <- as.factor(data_melt$path)\n \np <- ggplot(data_melt)\np <- p + geom_segment(aes(x = x, y = y, xend = xend, yend = yend, linetype = path), colour = colorAlpha, size = 1)\n# p <- p + geom_point(aes(x = x, y = y), colour = colorAlpha, fill = colorAlpha, shape = 21, size = 2)\n\ntheme1 <- theme(\n axis.line = element_line(colour = \"black\"),\n axis.text = element_text(colour = \"black\"),\n axis.ticks = element_line(colour = \"black\"),\n legend.position = \"none\",\n panel.background = element_rect(size = 1, fill = \"white\", colour = NA),\n panel.border = element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()\n)\n\nnth = 2\nticks <- unique(round(data_melt$x, 1))\nticks <- ticks[seq(1, length(ticks), nth)]\np <- p + scale_x_continuous(\n breaks = ticks\n )\n\np <- p + theme1\np <- p + xlab(\"Time\") + ylab(\"\")\nprint(p)\n\n\n#########################\n#---JC69 CTMC EXAMPLE---#\n#########################\nJC69 <- function (theta, t) {\n p0 = 1/4 + 3/4 * exp(-4*theta*t)\n p1 = 1/4 - 1/4 * exp(-4*theta*t)\n \n trans_prob = matrix(c(p0, p1, p1, p1,\n p1, p0, p1, p1,\n p1, p1, p0, p1,\n p1, p1, p1, p0\n ), nrow = 4, ncol = 4, byrow = T)\n \n colnames(trans_prob) <- rownames(trans_prob) <- c(\"T\", \"C\", \"A\", \"G\")\n return(trans_prob)\n}\n\nN = 50\ntimes = seq(0, 0.1, length.out = N)\ndata <- data.frame(\n T = rep(NA, N),\n C = rep(NA, N),\n A = rep(NA, N),\n G = rep(NA, N)\n )\n\n# set.seed(123)\nr <- runif(4)\nvect <- r / sum(r)\n\n\ndata[1, ] <- vect\ntheta <- 2\n\nfor (i in 2 : N) {\n probs = as.matrix(data[i - 1, ], nrow = 1, ncol = 4)\n data[i, ] <- probs %*% JC69(theta, t = times[i]) \n}\n\ndata_melt <- melt(cbind(t = times, data), id.vars = \"t\") \n\np <- ggplot(data_melt)\np <- p + geom_line(aes(x = t, y = value, color = variable)) \np <- p + xlab(\"Time\") + ylab(\"Probability\")\ntheme <- theme(\n axis.title = element_text(colour = \"black\"),\n axis.text = element_text(colour = \"black\"),\n axis.line = element_line(colour = \"black\"),\n axis.ticks = element_line(colour = \"black\"),\n panel.background = element_rect(size = 1, fill = \"white\", colour = NA),\n plot.background = element_rect(colour = NA),\n panel.border = element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()\n)\np <- p + theme\nprint(p)\n\n\n###################################\n#---BINOMIAL LIKELIHOOD EXAMPLE---#\n###################################\nmyBlue = rgb(r = 86, g = 110, b = 126, maxColorValue = 250)\n\nlike <- function(theta, k = 8, n = 10) {\n return(dbinom(k, n, theta))\n}\n\n# 900 x 600\ntheta <- seq(from = 0, to = 1, by = 0.01)\nplot(theta, like(theta), type = \"l\", col = myBlue, lwd = 3)\n\n\n\n\npoints(0.8, like(0.8), pch = 19, col = myBlue, cex = 1.5)\n\n\n######################\n#---NEWTON RAPHSON---#\n######################\nmyBlue = rgb(r = 86, g = 110, b = 126, maxColorValue = 250)\n\nf <- function(x) {\n f = exp(x)/(1 + exp(x))^2\n fx = exp(x)/(1 + exp(x))^2 - 2*exp(2*x)/(1 + exp(x))^3\n fxx = 6 * exp(x)/(1 + exp(x))^4 - 6*exp(2*x)/(1 + exp(x))^3 + exp(x)/(1+exp(x))^2\n return( data.frame(f = f, fx = fx, fxx = fxx ) )\n}\n\nx = seq(-10, 10, length.out = 100)\nplot(x, f(x)[,1], type = \"l\", col = myBlue, lwd = 3)\n\nnewtonRaphson <- function(f, x0, tol = 1/10^9, maxIter = 100) {\n \n x = x0\n fx = f(x)\n i = 0\n \n cat(paste(c(\"i\", \"x\", \"f(x)\", \"\\n\"), sep = \"\\t\"))\n while ( (abs(fx[, 2]) > tol) ) {\n \n if(i < maxIter) {\n \n x = x - fx[, 2] / fx[, 3]\n fx = f(x)\n \n points(x, fx[,1], pch = 19, col = myBlue, cex = 1.5)\n cat(paste(c(i, x, fx[,1], \"\\n\"), sep = \"\\t\"))\n Sys.sleep(0.5) \n \n i = i + 1\n \n } else {\n break;\n }#END: maxIter check\n }#END: tolerance loop\n \n return(x)\n}\n\nx.star <- newtonRaphson(f, 5)\n", "meta": {"hexsha": "86ff84dbee077995c710cb0968b69d98f65d1512", "size": 5131, "ext": "r", "lang": "R", "max_stars_repo_path": "Advanced_Evolutionary_Models_and_Likelihood_Methods/plots/plots.r", "max_stars_repo_name": "fbielejec/VEME2016", "max_stars_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-19T15:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T15:57:45.000Z", "max_issues_repo_path": "Advanced_Evolutionary_Models_and_Likelihood_Methods/plots/plots.r", "max_issues_repo_name": "fbielejec/VEME2016", "max_issues_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "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": "Advanced_Evolutionary_Models_and_Likelihood_Methods/plots/plots.r", "max_forks_repo_name": "fbielejec/VEME2016", "max_forks_repo_head_hexsha": "b7a0d19f3335353b80ec3a0c6c67a944add19c4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-19T15:57:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T15:57:47.000Z", "avg_line_length": 23.8651162791, "max_line_length": 114, "alphanum_fraction": 0.4977587215, "num_tokens": 1888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.6549214445169037}} {"text": "Data_<-structure(list(item = c(\"Panacea\", \"Ichor\", \"Gold\"), value = c(3000,\n1800, 2500), weight = c(3, 2, 20), volume = c(25, 15, 2)), .Names = c(\"item\",\n\"value\", \"weight\", \"volume\"), row.names = c(NA, 3L), class = \"data.frame\")\n\nknapsack_volume<-function(Data, W, Volume, full_K)\n{\n\n\t# Data must have the colums with names: item, value, weight and volume.\n\tK<-list() # hightest values\n\tK_item<-list() # itens that reach the hightest value\n\tK<-rep(0,W+1) # The position '0'\n\tK_item<-rep('',W+1) # The position '0'\n\tfor(w in 1:W)\n\t{\n\t\ttemp_w<-0\n\t\ttemp_item<-''\n\t\ttemp_value<-0\n\t\tfor(i in 1:dim(Data)[1]) # each row\n\t\t{\n\t\t\twi<-Data$weight[i] # item i\n\t\t\tvi<- Data$value[i]\n\t\t\titem<-Data$item[i]\n\t\t\tvolume_i<-Data$volume[i]\n\t\t\tif(wi<=w & volume_i <= Volume)\n\t\t\t{\n\t\t\t\tback<- full_K[[Volume-volume_i+1]][w-wi+1]\n\t\t\t\ttemp_wi<-vi + back\n\n\t\t\t\tif(temp_w < temp_wi)\n\t\t\t\t{\n\t\t\t\t\ttemp_value<-temp_wi\n\t\t\t\t\ttemp_w<-temp_wi\n\t\t\t\t\ttemp_item <- item\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\tK[[w+1]]<-temp_value\n\tK_item[[w+1]]<-temp_item\n\t}\nreturn(list(K=K,Item=K_item))\n}\n\n\nUn_knapsack<-function(Data,W,V)\n{\n\tK<-list();K_item<-list()\n\tK[[1]]<-rep(0,W+1) #the line 0\n\tK_item[[1]]<-rep('', W+1) #the line 0\n\tfor(v in 1:V)\n\t{\n\t\tbest_volum_v<-knapsack_volume(Data, W, v, K)\n\t\tK[[v+1]]<-best_volum_v$K\n\t\tK_item[[v+1]]<-best_volum_v$Item\n\t}\n\nreturn(list(K=data.frame(K),Item=data.frame(K_item,stringsAsFactors=F)))\n}\n\nretrieve_info<-function(knapsack, Data)\n{\n\tW<-dim(knapsack$K)[1]\n\titens<-c()\n\tcol<-dim(knapsack$K)[2]\n\tselected_item<-knapsack$Item[W,col]\n\twhile(selected_item!='')\n\t{\n\t\tselected_item<-knapsack$Item[W,col]\n\t\tif(selected_item!='')\n\t\t{\n\t\t\tselected_item_value<-Data[Data$item == selected_item,]\t\t\t\n\t\t\tW <- W - selected_item_value$weight\n\t\t\titens<-c(itens,selected_item)\t\t\t\n\t\t\tcol <- col - selected_item_value$volume\n\t\t}\n\t}\nreturn(itens)\n}\n\nmain_knapsack<-function(Data, W, Volume)\n{\n\tknapsack_result<-Un_knapsack(Data,W,Volume)\n\titems<-table(retrieve_info(knapsack_result, Data))\n\tK<-knapsack_result$K[W+1, Volume+1]\n\tcat(paste('The Total profit is: ', K, '\\n'))\n\tcat(paste('You must carry:', names(items), '(x',items, ') \\n'))\n}\n\nmain_knapsack(Data_, 250, 250)\n", "meta": {"hexsha": "5d087c2a99a3dc80de698334865a190d551fbc96", "size": 2129, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.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/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.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/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.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": 23.9213483146, "max_line_length": 77, "alphanum_fraction": 0.6364490371, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6548464227095894}} {"text": "#!/usr/bin/env R\n#!-*- coding: utf-8 -*-\n\nd = read.csv('./data/10group-100n.csv')\n\nlmm <- function(formula, data, niter = 1000) {\n require(data.table)\n # convert the data to data.table as well\n data = data.table(data)\n\n # process the formula\n f.terms = terms(formula)\n f.vars = attr(f.terms, \"variables\")\n if (attr(f.terms, \"response\") == 1) {\n outcome = as.character(f.vars[[2]])\n }\n intercept = attr(f.terms, \"intercept\")\n fixed = grep(\"[|]\", attr(f.terms, \"term.labels\"), value=T, invert=T)\n\n # create the results matrix for storing samples\n samples = as.data.table(\n matrix(0,\n nrow = niter,\n ncol = intercept + length(fixed))\n )\n if (intercept == 1) {\n fixed = c('Intercept', fixed)\n data[, Intercept := 1]\n }\n setnames(samples, 1:ncol(samples), fixed)\n samples[, \"sigma2\" := 1]\n samples[1, x1 := 0.25]\n\n for (i in 2:niter) {\n inferFixedBeta(samples, data, i, fixed.vars = fixed, outcome = outcome)\n inferSigma2(samples, data, i, fixed.vars = fixed, outcome = outcome)\n }\n samples\n}\n\ninferFixedBetaMH <- function(samples, data, iter, fixed.vars, outcome, proposal.sd = 0.05) {\n sigma2 = as.numeric(samples[iter-1, 'sigma2', with=F])\n outcome.obs = data[, outcome, with=F]\n X = as.matrix(data[, fixed.vars, with=F])\n Beta = samples[iter-1, fixed.vars, with=F]\n logrand = log(runif(n = length(fixed.vars)))\n for (vi in 1:length(fixed.vars)) {\n v = fixed.vars[vi]\n old.beta = as.numeric(Beta[,v,with=F])\n new.beta = rnorm(1, mean = old.beta, sd = proposal.sd)\n\n # calculate the old loglikelihood\n log.g.old = - (1 / (2 * sigma2)) *\n sum((outcome.obs - X %*% t(Beta)) ** 2)\n\n # modify the beta value and calculate the new loglikelihood\n Beta[, eval(v):= new.beta]\n log.g.new = - (1 / (2 * sigma2)) *\n sum((outcome.obs - X %*% t(Beta)) ** 2)\n\n # compute candidate densities q for old and new beta\n # since the proposal distribution is normal this step is not needed\n log.q.old = 0\n log.q.new = 0\n\n # compute the moving probability\n moving.logprob = (log.g.new + log.q.old) - (log.g.old + log.q.new)\n samples[iter, eval(v) := ifelse(logrand[vi] < moving.logprob, new.beta, old.beta)]\n }\n}\n\ninferFixedBeta <- function(samples, data, iter, fixed.vars, outcome, proposal.sd = 0.05) {\n sigma2 = as.numeric(samples[iter-1, 'sigma2', with=F])\n outcome.obs = as.matrix(data[, outcome, with=F])\n X = as.matrix(data[, fixed.vars, with=F])\n Beta = samples[iter-1, fixed.vars, with=F]\n\n Mu = solve(t(X) %*% X) %*% t(X) %*% outcome.obs\n Sigma = sigma2 * solve(t(X) %*% X)\n require(MASS)\n samples[iter, eval(fixed.vars) := as.list(mvrnorm(1, Mu, Sigma))]\n\n}\n\ninferSigma2 <- function(samples, data, iter, fixed.vars, outcome) {\n alpha_0 = 1\n beta_0 = 1\n alpha_n = alpha_0 + nrow(data) / 2\n outcome.obs = as.matrix(data[, outcome, with=F])\n X = as.matrix(data[, fixed.vars, with=F])\n Beta = as.matrix(samples[iter-1, fixed.vars, with=F])\n beta_n = beta_0 + 0.5 * sum((outcome.obs - X %*% t(Beta)) ** 2)\n samples[iter, 'sigma2' := 1 / rgamma(1, shape = alpha_n, scale = 1 / beta_n)]\n}\n", "meta": {"hexsha": "f151aae1c313959043b5445097316abcba1c3767", "size": 3297, "ext": "r", "lang": "R", "max_stars_repo_path": "regression/lmm.r", "max_stars_repo_name": "tqian86/MPBST", "max_stars_repo_head_hexsha": "80b234a3bd5ff8cf46987f7b8097ae3c140662bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-13T17:33:06.000Z", "max_issues_repo_path": "regression/lmm.r", "max_issues_repo_name": "tqian86/MPBST", "max_issues_repo_head_hexsha": "80b234a3bd5ff8cf46987f7b8097ae3c140662bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-07-01T18:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-01T18:41:47.000Z", "max_forks_repo_path": "regression/lmm.r", "max_forks_repo_name": "tqian86/MPBST", "max_forks_repo_head_hexsha": "80b234a3bd5ff8cf46987f7b8097ae3c140662bb", "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.7052631579, "max_line_length": 92, "alphanum_fraction": 0.5829542008, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6547600948615414}} {"text": "## Dexter Barrows\n## dbarrows.github.io\n## McMaster University\n## 2016\n\nlibrary(deSolve)\nlibrary(ggplot2)\nlibrary(reshape2)\nlibrary(gridExtra)\nlibrary(Rcpp)\n\nSIR <- function(Time, State, Pars) {\n \n with(as.list(c(State, Pars)), {\n \n B <- R0*r/N\n BSI <- B*S*I\n rI <- r*I\n \n dS = -BSI\n dI = BSI - rI\n dR = rI\n \n return(list(c(dS, dI, dR)))\n \n })\n \n}\n\nT \t\t<- 100\nN \t\t<- 500\nsigma \t<- 10\ni_infec <- 5\n\n## Generate true trajecory and synthetic data\n##\n\ntrue_init_cond <- c(S = N - i_infec,\n I = i_infec,\n R = 0)\n\ntrue_pars <- c(R0 = 3.0,\n r = 0.1,\n N = 500.0)\n\nodeout <- ode(true_init_cond, 0:T, SIR, true_pars)\ntrueTraj <- odeout[,3]\n\nset.seed(1001)\n\ninfec_counts_raw <- odeout[,3] + rnorm(T+1, 0, sigma)\ninfec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw)\n\ng <- qplot(0:T, odeout[,3], geom = \"line\", xlab = \"Time (weeks)\", ylab = \"Infection Count\") +\n\t\tgeom_point(aes(y = infec_counts)) +\n\t\ttheme_bw()\n\nprint(g)\nggsave(g, filename=\"dataplot.pdf\", height=4, width=6.5)\n\n## Rcpp stuff\n##\n\nsourceCpp(paste(getwd(),\"d_if2.cpp\",sep=\"/\"))\n\nparamdata <- data.frame(if2(infec_counts, T+1, N))\ncolnames(paramdata) <- c(\"R0\", \"r\", \"sigma\", \"Sinit\", \"Iinit\", \"Rinit\")\n\n## Parameter density kernels\n##\n\nR0points <- paramdata$R0\nR0kernel <- qplot(R0points, geom = \"density\", xlab = expression(R[0]), ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=true_pars[[\"R0\"]]), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(R0kernel)\nggsave(R0kernel, filename=\"kernelR0.pdf\", height=3, width=3.25)\n\nrpoints <- paramdata$r\nrkernel <- qplot(rpoints, geom = \"density\", xlab = \"r\", ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=true_pars[[\"r\"]]), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(rkernel)\nggsave(rkernel, filename=\"kernelr.pdf\", height=3, width=3.25)\n\nsigmapoints <- paramdata$sigma\nsigmakernel <- qplot(sigmapoints, geom = \"density\", xlab = expression(sigma), ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=sigma), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(sigmakernel)\nggsave(sigmakernel, filename=\"kernelsigma.pdf\", height=3, width=3.25)\n\ninfecpoints <- paramdata$Iinit\ninfeckernel <- qplot(infecpoints, geom = \"density\", xlab = \"Initial Infected\", ylab = \"frequency\") +\n\t\t\t\tgeom_vline(aes(xintercept=true_init_cond[['I']]), linetype=\"dashed\", size=1, color=\"grey50\") +\n\t\t\t\ttheme_bw()\n\nprint(infeckernel)\nggsave(infeckernel, filename=\"kernelinfec.pdf\", height=3, width=3.25)\n\n# show grid\ngrid.arrange(R0kernel, rkernel, sigmakernel, infeckernel, ncol = 2, nrow = 2)\n\npdf(\"if2kernels.pdf\", height = 6.5, width = 6.5)\ngrid.arrange(R0kernel, rkernel, sigmakernel, infeckernel, ncol = 2, nrow = 2)\ndev.off()", "meta": {"hexsha": "f5801982ac4ce37f0d76917856dd755b6756f5c6", "size": 2847, "ext": "r", "lang": "R", "max_stars_repo_path": "code/if2/d_sir_if2.r", "max_stars_repo_name": "dbarrows/epidemic-forecasting", "max_stars_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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/if2/d_sir_if2.r", "max_issues_repo_name": "dbarrows/epidemic-forecasting", "max_issues_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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/if2/d_sir_if2.r", "max_forks_repo_name": "dbarrows/epidemic-forecasting", "max_forks_repo_head_hexsha": "a0865fa20c992dc4159e79bb332500e3ff2357ae", "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.119266055, "max_line_length": 100, "alphanum_fraction": 0.6297857394, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6547000904213219}} {"text": "library(shiny)\nlibrary(shinythemes)\noptions(scipen = 999999999)\nui <- fluidPage(theme=shinytheme(\"flatly\"),\n titlePanel(\"Likelihood Ratio for Mixed Results\"),\n sidebarLayout(\n sidebarPanel(numericInput(\"n\", \"Number of studies :\", 3, min = 1, max = 100),\n numericInput(\"x\", \"Number of successes:\", 2, min = 0, max = 100),\n sliderInput(\"H0\", \"Type 1 error rate:\", min = 0, max = 1, value = 0.05, step= 0.01),\n sliderInput(\"H1\", \"Assumed Power:\", min = 0, max = 1, value = 0.8, step= 0.01)\n ),\n mainPanel(plotOutput(\"coolplot\"),br(),\n h4(\"Shiny app accompanying: Lakens, D., & Etz, A. J. (2017). Too true to be bad: When sets of studies with significant and non-significant findings are probably true. Social Psychological and Personality Science. https://osf.io/preprints/psyarxiv/nnkg9\"),br(),\n h4(textOutput(\"text1\")), br(),\n h4(textOutput(\"text2\")),br(),\n h4(\"When the observed results are equally likely under H0 and H1, the likelihood ratio is 1. Benchmarks to interpret Likelihood Ratios suggest that when 132, there is strong evidence.\"),br(),\n h4(textOutput(\"text3\")), br(),\n dataTableOutput(\"table\")\n )\n )\n)\nserver <- function(input, output) {\n output$coolplot <- renderPlot({\n n<-input$n\n x<-input$x\n H0<-input$H0\n H1<-input$H1\n LR<-round(max(dbinom(x,n,H0)/dbinom(x,n,H1),dbinom(x,n,H1)/dbinom(x,n,H0)),digits=2) #Calculate LR (H1 over H0 and H0 over H1, pick max)\n H0H1<-ifelse(dbinom(x,n,H0)>dbinom(x,n,H1),\"The data are more likely under the null hypothesis than the alternative hypothesis\",\"The data are more likely under the alternative hypothesis than the null hypothesis\") \n theta<- seq(0,1,len=1000)\n like <- dbinom(x,n,theta)\n plot(theta,like,type='l',xlab=expression(theta), ylab='Likelihood', lwd=2)\n points(H0,dbinom(x,n,H0), lwd=2)\n points(H1,dbinom(x,n,H1), lwd=2)\n segments(H0, dbinom(x,n,H0), x/n, dbinom(x,n,H0), lty=2, lwd=2)\n segments(H1, dbinom(x,n,H1), x/n, dbinom(x,n,H1), lty=2, lwd=2)\n segments(x/n, dbinom(x,n,H0), x/n, dbinom(x,n,H1), lwd=2)\n abline(v=H0, col=\"gray40\", lty=3, lwd=2)\n abline(v=H1, col=\"gray40\", lty=3, lwd=2)\n title(paste('Likelihood Ratio:',LR))\n \n #create Table\n studies<-c(0:n)\n ProbH0<-dbinom(studies,n,H0)\n ProbH1<-dbinom(studies,n,H1)\n table<-cbind(studies,ProbH0,ProbH1)\n colnames(table) <- c(\"Number of significant studies\", \"Probability of observing x out of n significant studies when H0 is true\",\"Probability of observing x out of n significant studies when H1 is true\")\n \n output$text1 <- renderText({ \n paste(\"When H1 is true, in the long run, the probability of observing\", x,\" out of \",n, \" significant studies, given\" ,H1, \"power, is:\", dbinom(x,n,H1),\". If all studies examine true effects with\",100*H1,\"% power,\",100*round(dbinom(x,n,H1),digits=4),\"% of published articles with\",n,\"studies should observe\",x,\"significant results. When power is less than\",100*round(0.5^(1/n), digits=4),\"% observing\",n,\"out of\",n,\"significant results is less likely (i.e., occurs less than 50% of the time) than observing mixed results.\")\n })\n output$text2 <- renderText({ \n paste(\"When H0 is true, in the long run, the probability of observing\", x,\" out of \",n, \" significant studies, given a\" ,H0, \"Type 1 error rate, is:\", round(dbinom(x,n,H0),digits=10),\". When all studies examine null-effects with a\",100*H0,\"% Type 1 error rate,\",100*round(dbinom(x,n,H0),digits=4),\"% of published articles with\",n,\"studies should observe\",x,\"significant results.\")\n })\n output$text3 <- renderText({ \n paste(H0H1, \"with a likelihood ratio of\",LR,\".\")\n })\n output$table = renderDataTable(\n table,\n options = list(paging = FALSE, searching = FALSE)\n )\n })\n}\nshinyApp(ui = ui, server = server)", "meta": {"hexsha": "1e998018c54fba13df67ef826ec30588fe482044", "size": 3996, "ext": "r", "lang": "R", "max_stars_repo_path": "mixed_results_likelihood/app.r", "max_stars_repo_name": "Lakens/shiny_apps", "max_stars_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-01-31T17:07:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T12:13:38.000Z", "max_issues_repo_path": "mixed_results_likelihood/app.r", "max_issues_repo_name": "Lakens/shiny_apps", "max_issues_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-21T00:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-20T12:35:30.000Z", "max_forks_repo_path": "mixed_results_likelihood/app.r", "max_forks_repo_name": "Lakens/shiny_apps", "max_forks_repo_head_hexsha": "c6845987fa9cd57550c7be1027a0f7c605684fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-12-08T06:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T04:50:02.000Z", "avg_line_length": 62.4375, "max_line_length": 529, "alphanum_fraction": 0.6498998999, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6545382908039902}} {"text": "#' radtheoricR\n#'\n#' @description R function to assess raw solar irradiance parameter.\n#' \n#' @param timenow time \"POSIXct\" or \"POSIXt\" object.\n#' @param lat numeric latitude in decimal degrees.\n#' @param lon numeric longitude in decimal degrees.\n#' @param albedo numeric albedo of surface.\n#' @return Theoretical radiation in W/mq\n#' \n#' @author Istituto per la Bioeconomia CNR Firenze Italy Alfonso Crisci \\email{alfonso.crisci@@ibe.cnr.it}\n#' \n#' \n#' \n#' @export\n\nradtheoricR <- function(timenow,lat,lon,albedo){\n rho=albedo\n sunpar=sunposition(timenow,lat, lon)\n elev=sunpar$elevation\n timeday=as.POSIXlt(timenow, \"GMT\")\n nday=format(timeday,\"%j\")\n # Solar constant\n SC = 1.361 # kW/m2\n # ET solar radition I0 kW/m2\n I0 <- SC*(1+0.034*cos((nday)*2*pi/365)) \n # atmospheric effect\n A <- 1.160 + 0.075 * sin((nday-274)*2*pi/365)\n opt.depth <- 0.174 + 0.035 * sin((nday-100)*2*pi/365)\n air.mass <- 1/sin(elev*2*pi/360)\n # Direct\n IB <- I0*exp(-opt.depth*air.mass)\n # diffuse\n IDH <- IB*(0.095 + 0.04*sin((nday-100)*2*pi/365))\n ID <- IDH*(1+cos(pi-elev*2*pi/360))/2\n # reflected\n IBH <- IB*sin(elev*2*pi/360)\n IR <- rho*(IBH+IDH)*(1+cos(pi-elev*2*pi/360))/2\n # total\n IT <- IB+ID+IR\n I <- cbind(IB,ID,IR,IT)\n return(list(I0=I0,A=A,opt.depth=opt.depth, air.mass=air.mass,I=I,jd=nday,elev=elev,azimuth=sunpar$azimuth))\n}\n", "meta": {"hexsha": "44f64c12ca4908fd978adc76033f444cb2e84f67", "size": 1326, "ext": "r", "lang": "R", "max_stars_repo_path": "R/radtheoricR.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/radtheoricR.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/radtheoricR.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": 30.1363636364, "max_line_length": 108, "alphanum_fraction": 0.6681749623, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6544524328988098}} {"text": "#Using data from insideairbnb.com - data from the Santa Cruz, CA area, last updated October 2015\nsantacruz = read.csv(\"documents/airbnb_santacruz.csv\")\nattach(santacruz)\n\n#thanks to http://www.geodatasource.com/developers/javascript for ideas behind this function\n#Note that \"West\" and \"South\" need negative signs for lat/lon\ndistance <- function(lat1, lon1, lat2, lon2) {\n #lat2 <- 36.9643, lon2 <- -122.0189 for Santa Cruz Beach Boardwalk\n radlat1 = pi * lat1/180\n radlat2 = pi * lat2/180\n theta = lon1-lon2\n radtheta = pi * theta/180\n dist = (sin(radlat1) * sin(radlat2) + cos(radlat1) * cos(radlat2) * cos(radtheta))\n dist = acos(dist)\n dist = dist * 180/pi\n dist = dist * 60 * 1.1515\n return(dist)\n}\n\n#use distance to regress price on distance, split by type of room (maybe focus on home first)\nsantacruz$distance<- distance(santacruz$latitude, santacruz$longitude,36.9643,-122.0189)\n\nsantacruz$room_type <- factor(santacruz$room_type)\nlm <- lm(santacruz$price ~ santacruz$distance + santacruz$room_type)\nsummary(lm)\n\n#These two regressions indicate somewhat odd findings. \n#For one, the farther a house is away from the Santa Cruz Beach Boardwalk, \n#the more expensive it is to stay per night. \n#For another, you have very big negative coefficients for Private Room or Shared Room categories. \n#The latter is easily explained upon realizing that the third category, renting a full house, \n#should logically be more expensive per night. The former (positive distance variable) may be explained \n#by physically looking through the data, where a lot of houses \n#in the \"Santa Cruz\" area are actually closer to Capitola Beach.\n\nsantacruz$capitola<- distance(santacruz$latitude, santacruz$longitude,36.9716, -121.9516)\nlmcap <- lm(santacruz$price ~ santacruz$capitola + santacruz$room_type)\nsummary(lmcap)\n\nmean(santacruz$latitude)\nmean(santacruz$longitude)\n\n#I tried using Capitola Beach as another distance measure, but again the further away a house was from the beach, \n#the more my model predicted it would cost. \n#Upon checking the average location for latitude and longitude, I figured out the reason why: \n#this dataset ranges from Santa Cruz Beach Boardwalk to Capitola Beach, \n#making both anchor points the extremes of their datasets: \n#https://www.google.com/maps/place/36%C2%B059'12.2%22N+121%C2%B059'13.0%22W/@36.9792869,-122.0092925,13.42z/data=!4m5!3m4!1s0x0:0x0!8m2!3d36.9867106!4d-121.9869506\n\n#Separate Capitola from Santa Cruz Beach houses (focus on Santa Cruz Boardwalk first)\n#first, see what neighborhoods are in there\nunique(neighbourhood)\n\nsconly <- subset(santacruz, santacruz$neighbourhood == \"City of Santa Cruz\")\nsconly$distance<- distance(sconly$latitude, sconly$longitude,36.9643,-122.0189)\nlmsconly <- lm(sconly$price ~ sconly$distance + sconly$room_type)\nsummary(lmsconly)\n\ncaponly <- subset(santacruz, santacruz$neighbourhood == \"City of Capitola\")\ncaponly$capitola<- distance(caponly$latitude, caponly$longitude,36.9716, -121.9516)\nlmcaponly <- lm(caponly$price ~ caponly$capitola + caponly$room_type)\nsummary(lmcaponly)\n\n#Now the adage of \"location, location, location\" is correctly displayed in the regression for Capitola\n#the further away a house is from Capitola Beach, the less a person should be willing to pay to stay in an Airbnb), \n#and is significant at the 5% level. The sign on the Santa Cruz coefficient is still positive, \n#but it's not significant for the regression. \n", "meta": {"hexsha": "7869033f64839f88379abc9decf58fe522dce838", "size": 3452, "ext": "r", "lang": "R", "max_stars_repo_path": "regression.r", "max_stars_repo_name": "andrewjabara/airbnb_santa_cruz", "max_stars_repo_head_hexsha": "aa0c74f062b984a29e5098d89dcad010a5cee95a", "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": "regression.r", "max_issues_repo_name": "andrewjabara/airbnb_santa_cruz", "max_issues_repo_head_hexsha": "aa0c74f062b984a29e5098d89dcad010a5cee95a", "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": "regression.r", "max_forks_repo_name": "andrewjabara/airbnb_santa_cruz", "max_forks_repo_head_hexsha": "aa0c74f062b984a29e5098d89dcad010a5cee95a", "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.7647058824, "max_line_length": 163, "alphanum_fraction": 0.7639049826, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6542732868663121}} {"text": "# This code computes minimum detectable odds ratio\n# for the Vaccine effectiveness against referral\n# to hospital and severe lung injury associated with COVID-19\n# study\nlibrary(epiR)\n\n# Declare working directory beforehand in an environment variable\n# SPB_COVID_STUDY_PATH = \"path_to_your_folder\"\n# with the aid of usethis::edit_r_environ()\n# Restart R session for the changes to make effect\nsetwd(Sys.getenv('SPB_COVID_STUDY_PATH'))\n\n# Load data to extract characteristics\nload(\"data/ve_ct_paper/trc_dt.Rdata\")\n\n# Study characteristics\ntotal_patients <- trc_dt[, .N] # 13893\ncompletely_vaccinated_patients <- trc_dt[vac_status3 == \"full_vac\", .N] # 1291\npartially_vaccinated_patients <- trc_dt[vac_status3 == \"part_vac\", .N] # 448\n\n# Outcomes\nhospitalized_patients <- trc_dt[hospitalization == 1, .N] # 495\nany_lung_injury_patients <- trc_dt[ct_score != 0, .N] # 9368\nsaturation_less_than_96 <- trc_dt[saturation < 96 | is.na(saturation), .N] # 385\n\n# MDE for hospitalization, complete vaccination\nepi.sscc(OR = NA, \n\t\t\t\t p0 = completely_vaccinated_patients/total_patients, \n\t\t\t\t n = total_patients, \n\t\t\t\t conf.level = 0.95, \n\t\t\t\t power = 0.8, \n\t\t\t\t method = \"unmatched\", \n\t\t\t\t r = (total_patients-hospitalized_patients)/hospitalized_patients)\n\n# MDE for any lung injury, complete vaccination\nepi.sscc(OR = NA, \n\t\t\t\t p0 = completely_vaccinated_patients/total_patients, \n\t\t\t\t n = total_patients, \n\t\t\t\t conf.level = 0.95, \n\t\t\t\t power = 0.8, \n\t\t\t\t method = \"unmatched\", \n\t\t\t\t r = (total_patients-any_lung_injury_patients)/any_lung_injury_patients)\n\n# MDE for oxygen saturation, complete vaccination\nepi.sscc(OR = NA, \n\t\t\t\t p0 = completely_vaccinated_patients/total_patients, \n\t\t\t\t n = total_patients, \n\t\t\t\t conf.level = 0.95, \n\t\t\t\t power = 0.8, \n\t\t\t\t method = \"unmatched\", \n\t\t\t\t r = (total_patients-saturation_less_than_96)/saturation_less_than_96)\n\n# MDE for hospitalization, partial vaccination\nepi.sscc(OR = NA, \n\t\t\t\t p0 = partially_vaccinated_patients/total_patients, \n\t\t\t\t n = total_patients, \n\t\t\t\t conf.level = 0.95, \n\t\t\t\t power = 0.8, \n\t\t\t\t method = \"unmatched\", \n\t\t\t\t r = (total_patients-hospitalized_patients)/hospitalized_patients)\n", "meta": {"hexsha": "b84db18d29fd970742bdc9abd1a87e38fbe750c0", "size": 2141, "ext": "r", "lang": "R", "max_stars_repo_path": "code/analysis/ve_covid_paper/minimum_detectable_ve.r", "max_stars_repo_name": "eusporg/spb_covid_study20", "max_stars_repo_head_hexsha": "dee672cb2c6a4f96ddcea4a2e997ba12b6bc89b8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-03-16T06:07:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T08:50:12.000Z", "max_issues_repo_path": "code/analysis/ve_covid_paper/minimum_detectable_ve.r", "max_issues_repo_name": "eusporg/spb_covid_study20", "max_issues_repo_head_hexsha": "dee672cb2c6a4f96ddcea4a2e997ba12b6bc89b8", "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": "code/analysis/ve_covid_paper/minimum_detectable_ve.r", "max_forks_repo_name": "eusporg/spb_covid_study20", "max_forks_repo_head_hexsha": "dee672cb2c6a4f96ddcea4a2e997ba12b6bc89b8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-20T08:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T11:04:07.000Z", "avg_line_length": 35.0983606557, "max_line_length": 80, "alphanum_fraction": 0.7258290518, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6538920032590492}} {"text": "bilinear.interp<-function(x,f){\n\t#interpolate a 2d point for fn f\n\tindx<-trunc(x[1]*(res-1)+1)\n\tindy<-trunc(x[2]*(res-1)+1)\n\tseq.Out<-seq(0,1,length.out=res)\n\tfr1<- (seq.Out[indx+1]-x[1])/(seq.Out[indx+1]-seq.Out[indx]) * f[indx,indy] + (x[1]-seq.Out[indx])/(seq.Out[indx+1]-seq.Out[indx]) * f[indx+1,indy]\n\tfr2<- (seq.Out[indx+1]-x[1])/(seq.Out[indx+1]-seq.Out[indx]) * f[indx,indy+1] + (x[1]-seq.Out[indx])/(seq.Out[indx+1]-seq.Out[indx]) * f[indx+1,indy+1] \n\tfp<- (seq.Out[indy+1]-x[2])/(seq.Out[indy+1]-seq.Out[indy]) * fr1 + (x[2]-seq.Out[indy])/(seq.Out[indy+1]-seq.Out[indy]) * fr2\n\treturn(fp)\n}\n\nbilinear.interp(c(.4,.5),matrix(rnorm(res^2),res,res))\n\nuniv.interp<-function(x,f){\n\tseq.Out<-seq(0,1,length.out=res)\n\tindx<-trunc(x*(res-1)+1)\n\t(seq.Out[indx+1]-x)/(seq.Out[indx+1]-seq.Out[indx]) * f[indx] + (x-seq.Out[indx])/(seq.Out[indx+1]-seq.Out[indx]) * f[indx+1]\n}\n\nuniv.interp(.4,1:res)\n\n\ntree.mix.lik<-function(x,edge_den,beliefs,edgelist,tree.list,weights,part_fn){\n\te<- dim(edgelist)[1]\n\td<-dim(beliefs)[1]\n\tuni.prod<-mapply(function(u){\n\t\tlog(univ.interp(x[u],beliefs[u,]))\n\t},1:d)\n\tif(e==0){\n\t\treturn(sum(uni.prod))\n\t}\n\t\tif(any(is.na(uni.prod))) print(\"help!\")\n\n\tbiv.prod<-mapply(\n\t\t\t\tfunction(l){\n\t\t\t\t\ts<- edgelist[l,1]\n\t\t\t\t\tt<- edgelist[l,2]\n\t\t\t\t\tlog(bilinear.interp(c(x[s],x[t]) , edge_den[,,l])) - (uni.prod[s]) - (uni.prod[t])\n\t\t\t\t},\n\t\t\t\t1:e\n\t\t\t)\n\ttree.prod<- lapply(tree.list,\n\t\t\t\t\tfunction(t){\n\t\t\t\t\t\ttree<- graph.adjacency(t,mode=\"undirected\")\n\t\t\t\t\t\tel1<-apply(get.edgelist(tree), 1, paste, collapse=\"-\")\n\t\t\t\t\t\tel2<-apply(get.edgelist(tree), 1, function(x)paste(rev(x),collapse=\"-\"))\n\t\t\t\t\t\tel<-apply(edgelist, 1, paste, collapse=\"-\")\n\t\t\t\t\t\tekeep<- (el %in% el1) | (el %in% el2)\n\t\t\t\t\t\tsum( biv.prod[ekeep] )\n\t\t\t\t\t})\n\t\ttree.prod<- unlist(tree.prod)\n\t\ttmax<- max(tree.prod)\t\t\n\t\t#tmax<-0\n\t\t#tree.weight<- exp(tree.prod-tmax)*weights\n\t\t#out<- sum( uni.prod ) + tmax + log( sum( tree.weight ) )\n\t\tout<- sum( uni.prod ) + weights * tree.prod\n\treturn(out)\n\t}\n\n# risk_path_tree<-lapply(path,function(x){\n# outvec<-lapply(1:dim(test)[1],\n# \tfunction(i){\n# \t tree.mix.lik(test[i,],\n# \t\tx$edge_den,\n# \t\tx$beliefs,\n# \t\tx$edgelist,\n# \t\tx$tree_obj$tree.list,\n# \t\tx$tree_obj$weight.list)\n# \t})\n# \toutvec<- unlist(outvec)\n# \treturn(- mean(outvec))\n# })\n# #risk_path_tree\n# \n# # \n# # lik<-tree.mix.lik(test[1,],\n# # \tfit$edge_den,\n# # \tfit$beliefs,\n# # \tedgelist,\n# # \ttree_obj$tree.list,\n# # \ttree_obj$weight.list\n# # )", "meta": {"hexsha": "67fc94a48f0bd4fd31ff751c4c5cc95b7c866ec4", "size": 2439, "ext": "r", "lang": "R", "max_stars_repo_path": "tree_mix_lik.r", "max_stars_repo_name": "geb5101h/trw", "max_stars_repo_head_hexsha": "2037bdedb1c6c38151abdcbcb44b2b18c2906a6c", "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": "tree_mix_lik.r", "max_issues_repo_name": "geb5101h/trw", "max_issues_repo_head_hexsha": "2037bdedb1c6c38151abdcbcb44b2b18c2906a6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-28T00:31:07.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-28T00:31:24.000Z", "max_forks_repo_path": "tree_mix_lik.r", "max_forks_repo_name": "geb5101h/trw", "max_forks_repo_head_hexsha": "2037bdedb1c6c38151abdcbcb44b2b18c2906a6c", "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.743902439, "max_line_length": 153, "alphanum_fraction": 0.5965559656, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6538540740554629}} {"text": "# Normal Approximation to the Binomial\r\n# number of trails\r\nn<-100\r\n# probability of success of single event\r\nz<-0.2\r\nMean<-n*z\r\ns<-sqrt(n*z*(1-z))\r\n# e probability that at least 15 of the 100 drugs are eventually licensed (>14.5)\r\npnorm(14.5, mean=Mean, sd=s, lower.tail=FALSE)\r\n", "meta": {"hexsha": "bb3a93c85f933de9b1cb96f7e6b59f31cd78b997", "size": 281, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.26/Ex4_26.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.26/Ex4_26.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.26/Ex4_26.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 28.1, "max_line_length": 83, "alphanum_fraction": 0.6975088968, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6536602211820461}} {"text": "# Clearing the environment\r\nrm(list=ls())\r\n\r\n# libraries\r\nlibrary(readr)\r\nlibrary(dplyr)\r\nlibrary(tidyr)\r\nlibrary(TSA)\r\nlibrary(tseries)\r\nlibrary(forecast)\r\nlibrary(fUnitRoots)\r\nlibrary(lmtest)\r\nlibrary(fGarch)\r\nlibrary(CombMSC)\r\nlibrary(stats)\r\nlibrary(FitAR)\r\n\r\n# data preparation\r\nwaste <- read_csv(\"Waste_collected_per_month.csv\")\r\n\r\nwaste <- waste %>% separate(date, into = c(\"month\", \"day\",\"year\"), sep = \"/\") %>% \r\n separate(year, into = c(\"year\", \"time\"), sep = \" \") %>% \r\n arrange(year, month, day) %>% select(month, year, residential)\r\n\r\nView(head(waste))\r\nView(tail(waste))\r\n\r\n\r\n# converting dataframe into time series\r\nwasteTS = ts(waste$residential, start = c(2009,4), end = c(2020,3), frequency = 12)\r\nwasteTS\r\n\r\n#----------------------------------------------------------------------\r\n\r\n# Functions for Time Series\r\nplot_ts <- function(ts, transformation)\r\n{\r\n win.graph(width = 45,\r\n height = 30,\r\n pointsize = 15)\r\n plot(ts,\r\n ylab = \"Waste\",\r\n main = c(paste0(toString(transformation),\r\n \" plot of Waste\")),\r\n type=\"o\")\r\n points(y=ts,x=time(ts), pch=as.vector(season(ts)))\r\n}\r\n\r\n\r\n# Function for ACF and PACF\r\nautoCorrelation <- function(ts, time_series)\r\n{\r\n win.graph(width = 20, \r\n height = 15,\r\n pointsize = 15)\r\n \r\n par(mfrow=c(2,1))\r\n acf(ts,\r\n lag.max = 48,\r\n main = c(paste0(\"ACF plot of \",toString(time_series))))\r\n \r\n pacf(ts, \r\n lag.max = 48,\r\n main = c(paste0(\"PACF plot of \",toString(time_series))))\r\n par(mfrow=c(1,1))\r\n}\r\n\r\n\r\n# Functions for its Residual Analysis\r\nresidual_model <- function(model, modelname)\r\n{\r\n res.model = rstandard(model)\r\n win.graph(width = 20,\r\n height = 15,\r\n pointsize=15)\r\n \r\n par(mfrow=c(3,2))\r\n \r\n plot(y = res.model, \r\n x = as.vector(time(wasteTS)),\r\n main = c(paste0(\"Time Series plot of Standardised residuals of \r\n fitted \", toString(modelname))),\r\n xlab = 'Time', \r\n ylab = 'Standardized Residuals',\r\n type = 'o')\r\n \r\n hist(res.model,\r\n main = c(paste0(\"Histogram of Standardised residuals of \r\n fitted \", toString(modelname))),\r\n xlab='Standardized Residuals') \r\n \r\n qqnorm(y=res.model, \r\n main = c(paste0(\"QQ plot of standardised residuals of \r\n fitted \", toString(modelname))))\r\n \r\n qqline(y=res.model, \r\n col = 2, \r\n lwd = 1, \r\n lty = 2)\r\n \r\n print(shapiro.test(res.model))\r\n \r\n acf(res.model,\r\n lag.max = 48,\r\n main = c(paste0(\"ACF plot of standardised residuals of \r\n fitted \", toString(modelname))))\r\n \r\n pacf(res.model,\r\n lag.max = 48,\r\n main = c(paste0(\"PACF plot of standardised residuals of \r\n fitted \", toString(modelname)))) \r\n \r\n \r\n k=0\r\n LBQPlot(res.model,lag.max = 30, StartLag = k + 1, k = 0, SquaredQ = FALSE)\r\n par(mfrow=c(1,1))\r\n}\r\n\r\n\r\n# Function for SARIMA model\r\nSARIMA <- function(p,d,q, modelname)\r\n{\r\n ml = arima(wasteTSBC,order=c(p,d,q),\r\n seasonal = list(order = c(2,1,1), period = 12),\r\n method = \"ML\")\r\n \r\n print(coeftest(ml))\r\n residual_model(ml,toString(modelname))\r\n \r\n Model <- modelname\r\n \r\n AIC <- AIC(ml)\r\n aic <- cbind.data.frame(Model,AIC)\r\n AIC_SCORE <- rbind(AIC_SCORE, aic)\r\n AIC_SCORE <<- AIC_SCORE\r\n \r\n BIC <- AIC(ml,k=(log(length(wasteTS))))\r\n bic <- cbind.data.frame(Model,BIC)\r\n BIC_SCORE <- rbind(BIC_SCORE, bic)\r\n BIC_SCORE <<- BIC_SCORE\r\n}\r\n\r\n#----------------------------------------------------------------------\r\n# Descriptive Analysis\r\n#----------------------------------------------------------------------\r\n\r\n# Original Time Series\r\n\r\npar(mar=c(1,1,1,1))\r\nplot_ts(wasteTS, \"Time Series\")\r\n\r\n\r\n# ACF and PACF of original Time Series\r\nautoCorrelation(wasteTS, \"Time Series\")\r\n\r\n\r\nwin.graph(width = 20, \r\n height = 15, \r\n pointsize=15)\r\n# Scatter Plot of Consecutive Years\r\nplot(y=wasteTS,\r\n x=zlag(wasteTS),\r\n ylab='Residential Waste (Tonnes)', \r\n xlab='Previous Month Residential Waste (Tonnes)', \r\n main = \"Scatter plot of Residential Waste (Tonnes) in consequtive months\")\r\n\r\n\r\n# Correlation of Consecutive Years\r\ny = wasteTS \r\nx = zlag(wasteTS) \r\nindex = 2:length(x) \r\ncor(y[index],x[index]) %>% round(3)\r\n\r\n# -----------------------------------------------------------------------\r\n# Box-cox Transformation\r\n# -----------------------------------------------------------------------\r\n\r\nwin.graph(width = 20, \r\n height = 15, \r\n pointsize=15)\r\nBC <- BoxCox.ar(wasteTS)\r\n\r\n# box-cox confidence Interval\r\nBC$ci\r\n\r\n# maximum likelihood\r\nlambda <- BC$lambda[which(max(BC$loglike) == BC$loglike)]\r\nlambda\r\n\r\n# box-cox transformation\r\nwasteTSBC = ((wasteTS^lambda)-1)/lambda\r\n\r\nplot_ts(wasteTSBC, \"Box-Cox Transformation Time Series\")\r\n\r\nautoCorrelation(wasteTSBC, \"Box-Cox Transformation Time Series\")\r\n\r\n# -----------------------------------------------------------------------\r\n# Residual Approach SARIMA Models\r\n# -----------------------------------------------------------------------\r\n\r\nm1.temp = arima(wasteTSBC,order=c(0,0,0),\r\n seasonal = list(order = c(0,1,0), period = 12))\r\nres.m1 = residuals(m1.temp) \r\nplot_ts(res.m1,\"Residuals SARIMA(0,0,0)x(0,1,0)\")\r\nautoCorrelation(res.m1,\"Residuals SARIMA(0,0,0)x(0,1,0)\")\r\n\r\n\r\nm2.temp = arima(wasteTSBC,order=c(0,0,0),\r\n seasonal = list(order = c(2,1,1), period = 12))\r\nres.m2 = residuals(m2.temp)\r\nplot_ts(res.m2,\"Residuals SARIMA(0,0,0)x(2,1,1)\")\r\nautoCorrelation(res.m2,\"Residuals SARIMA(0,0,0)x(2,1,1)\")\r\n\r\n# P = 2, D = 1, Q = 1\r\n\r\n# p = (1,2)\r\n# q = (1,2,3)\r\n\r\n# SARIMA(1,0,1)x(2,1,1), \r\n# SARIMA(1,0,2)x(2,1,1), \r\n# SARIMA(1,0,3)x(2,1,1),\r\n# SARIMA(2,0,1)x(2,1,1),\r\n# SARIMA(2,0,2)x(2,1,1), \r\n# SARIMA(2,0,3)x(2,1,1),\r\n\r\nm3.temp = arima(wasteTSBC,order=c(2,0,2),\r\n seasonal = list(order = c(2,1,1), period = 12))\r\nres.m3 = residuals(m3.temp) \r\nplot_ts(res.m3,\"Residuals SARIMA(2,0,2)x(2,1,1)\")\r\nautoCorrelation(res.m3,\"Residuals SARIMA(2,0,2)x(2,1,1)\")\r\n\r\n# -----------------------------------------------------------------------\r\n# EACF\r\n# -----------------------------------------------------------------------\r\neacf(res.m2)\r\n# SARIMA(0,0,0)x(2,1,1),\r\n# SARIMA(0,0,1)x(2,1,1),\r\n\r\n# -----------------------------------------------------------------------\r\n# BIC\r\n# -----------------------------------------------------------------------\r\nwin.graph(width = 10, \r\n height = 10,\r\n pointsize = 15)\r\nres = armasubsets(y=res.m2,\r\n nar=8,\r\n nma=8,\r\n y.name='test',\r\n ar.method='ols')\r\nplot(res)\r\n# SARIMA(1,0,3)x(2,1,1),\r\n# SARIMA(3,0,3)x(2,1,1),\r\n\r\n# -----------------------------------------------------------------------\r\n# set of possible SARIMA models;\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(0,0,0)x(2,1,1),\r\n# SARIMA(0,0,1)x(2,1,1),\r\n# SARIMA(1,0,1)x(2,1,1), \r\n# SARIMA(1,0,2)x(2,1,1), \r\n# SARIMA(1,0,3)x(2,1,1),\r\n# SARIMA(2,0,1)x(2,1,1),\r\n# SARIMA(2,0,2)x(2,1,1), \r\n# SARIMA(2,0,3)x(2,1,1),\r\n# SARIMA(3,0,3)x(2,1,1)\r\n\r\n# -----------------------------------------------------------------------\r\n# creating null data frame for AIC and BIC\r\n# -----------------------------------------------------------------------\r\n\r\nAIC_SCORE <- data.frame(Model = c(),\r\n AIC = c())\r\n\r\nBIC_SCORE <- data.frame(Model = c(),\r\n BIC = c())\r\n\r\n# -----------------------------------------------------------------------\r\n# Model Fitting\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(0,0,0)x(2,1,1),\r\nSARIMA(0,0,0,\"SARIMA(0,0,0) X (2,1,1)\")\r\n\r\n# SARIMA(0,0,1)x(2,1,1)\r\nSARIMA(0,0,1,\"SARIMA(0,0,1) X (2,1,1)\")\r\n\r\n# SARIMA(1,0,1)x(2,1,1)\r\nSARIMA(1,0,1,\"SARIMA(1,0,1) X (2,1,1)\")\r\n\r\n# SARIMA(1,0,2)x(2,1,1)\r\nSARIMA(1,0,2,\"SARIMA(1,0,2) X (2,1,1)\")\r\n\r\n# SARIMA(1,0,3)x(2,1,1)\r\nSARIMA(1,0,3,\"SARIMA(1,0,3) X (2,1,1)\")\r\n\r\n# SARIMA(2,0,1)x(2,1,1)\r\nSARIMA(2,0,1,\"SARIMA(2,0,1) X (2,1,1)\")\r\n\r\n# SARIMA(2,0,2)x(2,1,1)\r\nSARIMA(2,0,2,\"SARIMA(2,0,2) X (2,1,1)\")\r\n\r\n# SARIMA(2,0,3)x(2,1,1)\r\nSARIMA(2,0,3,\"SARIMA(2,0,3) X (2,1,1)\")\r\n\r\n# SARIMA(3,0,3)x(2,1,1)\r\nSARIMA(3,0,3,\"SARIMA(3,0,3) X (2,1,1)\")\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# Finding Best Model\r\n# -----------------------------------------------------------------------\r\nAIC_SCORE %>% unique() %>% arrange(AIC)\r\nBIC_SCORE %>% unique() %>% arrange(BIC)\r\n\r\n# -----------------------------------------------------------------------\r\n# SARIMA(3,0,3)x(2,1,1) is best model, now, let's try overfit\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(4,0,3)x(2,1,1)\r\nSARIMA(4,0,3,\"SARIMA(4,0,3) X (2,1,1)\")\r\n\r\n# SARIMA(3,0,4)x(2,1,1)\r\nSARIMA(3,0,4,\"SARIMA(3,0,4) X (2,1,1)\")\r\n\r\n# -----------------------------------------------------------------------\r\n# SARIMA(3,0,4)x(2,1,1) is best model, now, let's try overfit\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(3,0,5)x(2,1,1)\r\nSARIMA(3,0,5,\"SARIMA(3,0,5) X (2,1,1)\")\r\n\r\n# SARIMA(4,0,4)x(2,1,1)\r\nSARIMA(4,0,4,\"SARIMA(4,0,4) X (2,1,1)\")\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# SARIMA(3,0,5)x(2,1,1) is best model, now, let's try overfit\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(3,0,6)x(2,1,1)\r\nSARIMA(3,0,6,\"SARIMA(3,0,6) X (2,1,1)\")\r\n\r\n# SARIMA(4,0,5)x(2,1,1)\r\nSARIMA(4,0,5,\"SARIMA(4,0,5) X (2,1,1)\")\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# SARIMA(4,0,5)x(2,1,1) is best model, now, let's try overfit\r\n# -----------------------------------------------------------------------\r\n\r\n# SARIMA(4,0,6)x(2,1,1)\r\nSARIMA(4,0,6,\"SARIMA(4,0,6) X (2,1,1)\")\r\n\r\n# SARIMA(5,0,5)x(2,1,1)\r\nSARIMA(5,0,5,\"SARIMA(5,0,5) X (2,1,1)\")\r\n\r\n# -----------------------------------------------------------------------\r\n# Forecasting\r\n# -----------------------------------------------------------------------\r\nforecasting = Arima(wasteTS,order=c(4,0,5),\r\n seasonal=list(order=c(2,1,1), period=12), \r\n lambda = -0.1,\r\n method = \"ML\")\r\nprediction = forecast(forecasting, h = 10)\r\n\r\nwin.graph(width = 10, \r\n height = 10,\r\n pointsize = 15)\r\nplot(prediction)\r\n\r\nprediction\r\n", "meta": {"hexsha": "a81800e476e33197e9a755122eb9114b82d3f033", "size": 10560, "ext": "r", "lang": "R", "max_stars_repo_path": "final_project.r", "max_stars_repo_name": "modihill/time_series_project_predicting_waste", "max_stars_repo_head_hexsha": "875619b952fe84b980744dcfa2d2ead861932564", "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": "final_project.r", "max_issues_repo_name": "modihill/time_series_project_predicting_waste", "max_issues_repo_head_hexsha": "875619b952fe84b980744dcfa2d2ead861932564", "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": "final_project.r", "max_forks_repo_name": "modihill/time_series_project_predicting_waste", "max_forks_repo_head_hexsha": "875619b952fe84b980744dcfa2d2ead861932564", "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": 28.3109919571, "max_line_length": 84, "alphanum_fraction": 0.4455492424, "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6535823718089107}} {"text": "#' Compute trace of a square matrix, that is, the sum\n#' of its diagonal elements.\n#'\n#' @param m a square matrix\n#'\n#' @return trace of input matrix\ntr <- function(m) {\n sum(diag(m))\n}", "meta": {"hexsha": "0b8772d369f7fd252b14158520c187528589669e", "size": 188, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helpers.r", "max_stars_repo_name": "Express50/omgee", "max_stars_repo_head_hexsha": "5022dd6dc268ecfd6042124b19772717cab75412", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-27T21:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T21:05:42.000Z", "max_issues_repo_path": "R/helpers.r", "max_issues_repo_name": "Express50/omgee", "max_issues_repo_head_hexsha": "5022dd6dc268ecfd6042124b19772717cab75412", "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/helpers.r", "max_forks_repo_name": "Express50/omgee", "max_forks_repo_head_hexsha": "5022dd6dc268ecfd6042124b19772717cab75412", "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.8888888889, "max_line_length": 53, "alphanum_fraction": 0.6489361702, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118068790619, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6535407481400873}} {"text": "#'@title calcHMBulbousBowRes\n#'\n#'@description Calculate bulbous bow resistance (\\code{Rb}) (kN) from the\n#'Holtrop & Mennen method.\n#'\n#'@param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'@param forwardDraft Forward draft (deviation from actual draft indicates trim) \n#' (vector of numericals, m)\n#'@param shipSpeed Ship actual speed (vector of numericals, m/s) (see \n#' \\code{\\link{calcSpeedUnitConversion}})\n#'@param Abt Traverse bulb area (vector of numericals, m^2) (see \n#' \\code{\\link{calcAbt}})\n#'@param hb Center of bulb area above keel line (vector of numericals, m) \n#' (see \\code{\\link{calchb}})\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#'\n#'@return \\code{Rb} (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#'@seealso \\itemize{\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calcAbt}}\n#'\\item \\code{\\link{calchb}}\n#'}\n#'\n#'@family Holtrop-Mennen Calculations\n#'@family Resistance Calculations\n#'\n#'@examples\n#' calcHMBulbousBowRes(seq(1,5,1),13.57,13.57,25.09,5.43,seawaterDensity=1.025)\n#'\n#'@export\n\ncalcHMBulbousBowRes<-function(shipSpeed,maxDraft,forwardDraft,\n Abt,hb,seawaterDensity=1.025){\nRb<-\n 0.11*exp(-3*((\n (0.56*sqrt(Abt)/(forwardDraft-1.5*hb))\n)^-2))*((\n (shipSpeed)/sqrt(9.81*(forwardDraft-hb-0.25*sqrt(Abt))+0.15*((shipSpeed)^2))\n)^3)*(Abt^1.5)*seawaterDensity*9.81/(1+((\n (shipSpeed)/sqrt(9.81*(forwardDraft-hb-0.25*sqrt(Abt))+0.15*((shipSpeed)^2))\n)^2))\n\n\nreturn(Rb)\n}\n\n\n\n", "meta": {"hexsha": "7ddba8dbcfc1b6b58f73a62a2e9bac9826c3010c", "size": 1716, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMBulbousBowRes.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/calcHMBulbousBowRes.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/calcHMBulbousBowRes.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": 31.2, "max_line_length": 81, "alphanum_fraction": 0.6888111888, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.653522137931144}} {"text": "'\nАналогично заданию 2, проверить работу арифметических операторов для векторов. Последовательно использовать векторы:\n1) одного типа, одного размера\n2) одного типа, разных размеров\n3) разных типов, одного размера\n4) разных типов, разного размера\nОбобщить результаты расчетов в виде правил вычисления результирующего вектора.\n'\n\n#Одного типа, одного размера\nvector1 <- c(1,2,3,4)\nvector2 <- c(4,6,3,6)\nvector1 + vector2\nvector1 - vector2\nvector1 * vector2\nvector1 / vector2\n\n\n#Одного типа, разных размеров\nvector1 <- c(1,2,3,4, 4,5,2)\nvector2 <- c(4,6,3,6)\nvector1 + vector2\nvector1 - vector2\nvector1 * vector2\nvector1 / vector2\n\n#Разных типов, одного размера\nvector1 <- c(TRUE, FALSE, TRUE, TRUE)\nvector2 <- c(4,6,3,6)\nvector1 + vector2\nvector1 - vector2\nvector1 * vector2\nvector1 / vector2\n\n#Разных типов, разного размера\nvector1 <- c(TRUE, FALSE, TRUE, TRUE)\nvector2 <- c(4,6,3,6,6,2,6,2,5)\nvector1 + vector2\nvector1 - vector2\nvector1 * vector2\nvector1 / vector2\n", "meta": {"hexsha": "94e10784c4af6c6fb89842fe15aa123cc0b9fb9f", "size": 966, "ext": "r", "lang": "R", "max_stars_repo_path": "Course II/R/pract/pract4/task4.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course II/R/pract/pract4/task4.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course II/R/pract/pract4/task4.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 23.0, "max_line_length": 116, "alphanum_fraction": 0.7463768116, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6534642539927197}} {"text": "boltzmann <- 3.167e-6 #hartree/K\n\ncalcul.partition <- function(valeurs, temperature){\n\texpo <- exp(-valeurs/(temperature * boltzmann))\n\treturn(sum(expo))\n}\n\ncalcul.energie <- function(valeurs, temperature){\n\tderivee <- (calcul.partition(valeurs, temperature + 1) - calcul.partition(valeurs, temperature - 1)) / 2 #Premier ordre, dT = 1\n\tenergie <- 2 * boltzmann * temperature^2 * derivee\n\tenergie <- energie + min(valeurs) #Energie de point 0\n\treturn(energie)\n}", "meta": {"hexsha": "5c3db84ceb4937ca933085b0fd5e7f2f01a82c15", "size": 461, "ext": "r", "lang": "R", "max_stars_repo_path": "code/fonctionsThermo.r", "max_stars_repo_name": "mbla1/TwoPartBox", "max_stars_repo_head_hexsha": "0285f62a58cf6f324a62a6379c907d14e901778a", "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/fonctionsThermo.r", "max_issues_repo_name": "mbla1/TwoPartBox", "max_issues_repo_head_hexsha": "0285f62a58cf6f324a62a6379c907d14e901778a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-29T19:47:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T19:51:30.000Z", "max_forks_repo_path": "code/fonctionsThermo.r", "max_forks_repo_name": "mbla1/TwoPartBox", "max_forks_repo_head_hexsha": "0285f62a58cf6f324a62a6379c907d14e901778a", "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.4615384615, "max_line_length": 128, "alphanum_fraction": 0.7136659436, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6533799542788531}} {"text": "mean_men<-177 #mean\nsd_men<-10 #standard deviation\nval_men<-200 #target value\nz_mean<-(val_men - mean_men)/sd_men # calculating z-score\np_men<-pnorm(z_mean) #area under the curve from -infinity till the taget value\np_target<-1 - p_men #area under the curve is 1. So substracting from 1 toget the target area\nProb_target<-p_target*100\n", "meta": {"hexsha": "68daf0b0e589454ffd5d5f6d7545a67feeee0e5e", "size": 334, "ext": "r", "lang": "R", "max_stars_repo_path": "R Community/R Stats_Basics Part 1/Assignment4.r", "max_stars_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_stars_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "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 Community/R Stats_Basics Part 1/Assignment4.r", "max_issues_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_issues_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "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 Community/R Stats_Basics Part 1/Assignment4.r", "max_forks_repo_name": "vaibhavkrishna-bhosle/Trendnxt-Projects", "max_forks_repo_head_hexsha": "6c8a31be2f05ec79cfc5086ee09adff161b836ad", "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.75, "max_line_length": 92, "alphanum_fraction": 0.7784431138, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.653035065624119}} {"text": "Groesse <- c(176, 166, 172, 184, 179, 170, 176)\nGewicht <- c(65, 55, 67, 82, 75, 65, 75)\n\ncor(Gewicht, Groesse, method=\"pearson\")\nreg <- lm(Gewicht~Groesse)\nsummary(reg)\n\nplot(Gewicht~Groesse)\nabline(reg)\n", "meta": {"hexsha": "96730199173530104f99accc96d7035be7e8d360", "size": 205, "ext": "r", "lang": "R", "max_stars_repo_path": "testdata/source_r.r", "max_stars_repo_name": "mxr/babi-grammars", "max_stars_repo_head_hexsha": "802dd556079752c74b5b5315bf48ea1ee720bc5d", "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": "testdata/source_r.r", "max_issues_repo_name": "mxr/babi-grammars", "max_issues_repo_head_hexsha": "802dd556079752c74b5b5315bf48ea1ee720bc5d", "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": "testdata/source_r.r", "max_forks_repo_name": "mxr/babi-grammars", "max_forks_repo_head_hexsha": "802dd556079752c74b5b5315bf48ea1ee720bc5d", "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.5, "max_line_length": 47, "alphanum_fraction": 0.6682926829, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6530134509271577}} {"text": "#' Random PCA\n#' \n#' @param x\n#' The input data matrix.\n#' @param k\n#' The number of singular values and/or left/right singular vectors\n#' to estimate.\n#' @param q\n#' An integer exponent, say 1, 2, or 3. See the paper for details.\n#' @param retx\n#' Logical; determines if the rotated data should be returned.\n#' @param center,scale\n#' Logical; determines if the data should be centered/scaled first.\n#' \n#' @return\n#' An object of class \\code{prcomp}.\n#' \n#' @references\n#' Halko, Martinsson, and Tropp. 2011. Finding structure with \n#' randomness: probabilistic algorithms for constructing approximate\n#' matrix decompositions. SIAM Review 53 217-288.\n#' \n#' Duda, R. O., Hart, P. E., & Stork, D. G. (2012). Pattern classification,\n#' chapter 10. John Wiley & Sons.\n#' \n#' @author\n#' Drew Schmidt\n#' \n#' @examples\n#' \\dontrun{\n#' x <- matrix(rnorm(30), 10)\n#' \n#' rpca(x)\n#' }\n#' \n#' @keywords SVD PCA\n#' @name rpca\n#' @rdname rpca\n#' @export\nrpca <- function(x, k=1, q=3, retx=TRUE, center=TRUE, scale=FALSE)\n{\n if (class(x) != \"ddmatrix\")\n x <- as.matrix(x)\n \n assert.type(retx, \"logical\")\n assert.type(center, \"logical\")\n assert.type(scale, \"logical\")\n \n # Check needs to be here so we don't do anything demanding before possibly needing to error out\n rsvd.checkargs(x=x, k=k, q=q, retu=FALSE, retvt=TRUE)\n \n assert.type(x, \"numeric\")\n \n if (center || scale)\n x <- scale(x, center=center, scale=scale)\n \n svd <- rsvd(x=x, k=k, q=q, retu=FALSE, retvt=TRUE)\n svd$d <- svd$d / sqrt(nrow(x) - 1L)\n \n if (center)\n center <- attr(x, \"scaled:center\")[1:k]\n if (scale)\n scale <- attr(x, \"scaled:scale\")[1:k]\n \n pca <- list(sdev=svd$d, rotation=t(svd$vt), center=center, scale=scale)\n \n if (is.matrix(x))\n colnames(pca$rotation) <- paste0(\"PC\", 1:ncol(pca$rotation))\n# else #FIXME\n \n if (retx)\n pca$x <- x %*% pca$rotation\n class(pca) <- \"prcomp\"\n \n return(pca)\n}\n\n", "meta": {"hexsha": "528fd93524cc2540408266bcf5dccd93477cc181", "size": 1908, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rpca.r", "max_stars_repo_name": "wrathematics/pbdML", "max_stars_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "max_stars_repo_licenses": ["BSD-2-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": "R/rpca.r", "max_issues_repo_name": "wrathematics/pbdML", "max_issues_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-22T22:36:57.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-22T22:45:14.000Z", "max_forks_repo_path": "R/rpca.r", "max_forks_repo_name": "wrathematics/pbdML", "max_forks_repo_head_hexsha": "cac079480be8622b8ac781def5f81fe9932614bb", "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": 24.4615384615, "max_line_length": 97, "alphanum_fraction": 0.6320754717, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6529351653430222}} {"text": "#' Updates the weight matrix of an ART network.\n#' \n#' This function returns a new weight matrix that has \"learned\" the input\n#' in the given category, as well as a value correspoding to whether or \n#' not the weight matrix was changed (0 = no change; 1 = change).\n#' @title ART_Update_Weights\n#' @param input Vector of size NumFeatures that contains the input signal into the network.\n#' @param weight Matrix of size NumFeatures-by-NumCategories which holds the weights of the network.\n#' @param categoryNumer Number of the category that codes the current input.\n#' @param learningRate Rate at which the network should learn new inputs.\n#' @return List containing the UPDATEDWEIGHT and WEIGHTCHANGE. The UPDATEDWEIGHT is a matrix of size NumFeatures-by-NumCategories\n#' that holds the new weights of the network after the input has been successfully learned.\n#' The WEIGHTCHANGE is a value (0 or 1) which relays whether or not\n#' the weight matrix was changed during this updating. Here, 0 represents\n#' no change and 1 represents a change.\n#' @details The length of the INPUT vector must equal the number of rows in the WEIGHT matrix, the CATEGORYNUMBER must\n#' be in the range [1, NumCategories], and the LEARNINGRATE must be in the range [0, 1].\nART_Update_Weights = function(input, weight, categoryNumber, learningRate)\n{\n # Get the number of features from the weight matrix.\n numFeatures = ncol(weight);\n numCategories = nrow(weight);\n # Check the input parameters for correct ranges.\n if(length(input) != numFeatures)\n {\n stop('The length of the input and rows of the weights do not match.');\n }\n if((categoryNumber < 1) | (categoryNumber > numCategories))\n {\n stop('The category number must be in the range [1, NumCategories].');\n }\n if((learningRate < 0) | (learningRate > 1))\n {\n stop('The learning rate must be within the range [0, 1].');\n }\n \n weightChange = 0;\n for (i in 1:numFeatures)\n {\n if(input[i] < weight[categoryNumber,i])\n {\n weight[categoryNumber,i] = (learningRate * input[i]) + ((1 - learningRate) * weight[categoryNumber,i]);\n weightChange = 1;\n }\n }\n \n # Return the updated weight matrix.\n updatedWeight = weight;\n return (list(updatedWeight, weightChange));\n}", "meta": {"hexsha": "79d3c516130f2776e6a0644c6585df1d3bed7baf", "size": 2237, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ART_Update_Weights.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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/ART_Update_Weights.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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/ART_Update_Weights.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "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.74, "max_line_length": 129, "alphanum_fraction": 0.7228430934, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6528737390819457}} {"text": "## Kenshu 2018.12.26\r\n## 岡村\r\n## 必要なRパッケージなど:MuMIn,TMB,Rtools\r\n##\r\n\r\n## データの読み込みと下調べ\r\n\r\ndat1 <- read.csv(\"dat1.csv\") # データの読み込み\r\n\r\nhead(dat1) # 最初の6行を表示\r\n\r\ntable(dat1$count) # countデータの内訳を見る\r\n\r\nplot(count~year, data=dat1) # 年トレンドのプロット\r\n\r\ntapply(dat1$count,dat1$year,mean) # countデータの年平均\r\n\r\ntapply(dat1$count,list(dat1$plant,dat1$year), mean) # countデータの年/植生別の平均\r\n\r\nplot(count~year, data=subset(dat1,plant==\"tree\")) # plant=\"tree\"に対する年トレンド\r\nplot(count~year, data=subset(dat1,plant==\"shrub\")) # plant=\"shrub\"に対する年トレンド\r\n\r\n## 正規線形回帰モデル\r\n\r\nb <- cov(dat1$count, dat1$year)/var(dat1$year) #  線形回帰の傾きの最小二乗推定値\r\na <- mean(dat1$count)-b*mean(dat1$year) #  線形回帰の切片の最小二乗推定値\r\nc(a,b) #  最小二乗推定値の表示\r\n\r\nlm(count~year, data=dat1) # countの年変化の線形回帰 \r\n\r\nlm(count~year*plant, data=dat1) # count~year+plant+year:plantの線形回帰 \r\n\r\n# AICのシミュレーション\r\n\r\nRes.aic <- NULL # 結果の入れ物を作る\r\nSim <- 10000 # シミュレーション回数(10000回ぐらいしないと良い結果にならない)\r\nset.seed(1234) # 乱数の初期値を設定\r\nfor (n in c(10,100,500,1000)){ # サンプルサイズを10, 100, 500, 1000と変化させる\r\n z <- matrix(rnorm(n*Sim, 0, 1),nrow=Sim,ncol=n) # シミュレーション回数分データを発生(applyを使うため行列形式にしている)\r\n TL <- apply(z,1,function(z) integrate(function(x) dnorm(x,0,1)*dnorm(x,mean(z),sqrt(var(z)*(n-1)/n),log=TRUE),-Inf,Inf)$value)\r\n # 平均対数尤度 \\int Q(x) P(x|\\theta).分散に(n-1)/nを掛けているのは,不偏分散を最尤推定量にするため(研修ではここ間違ってました.失礼しました).dnormは正規分布の確率密度関数 dnorm(x, 平均, 標準偏差) \r\n EL <- apply(z,1,function(z) mean(dnorm(z,mean(z),sqrt(var(z)*(n-1)/n),log=TRUE)))\r\n # 標本に対する対数尤度の平均.\r\n Res.aic <- cbind(Res.aic, n*(EL-TL))\r\n # 2つの差はパラメータ数(この場合,平均と分散の2個)になることが期待される\r\n}\r\ncolnames(Res.aic) <- c(10,100,500,1000) # 列の名前をサンプルサイズにする\r\ncolMeans(Res.aic) # Res.aicはSim × 4の行列になっていて,列平均をとっている.これの値が2になっていれば,AICの-2*(対数尤度-パラメータ数)のパラメータ数を引くというところが正しいというのが確かめられたことになる\r\n\r\nres.n0 <- lm(count~year,data=dat1) # count~yearの線形回帰の結果をres.n0の中に格納\r\nres.n1 <- lm(count~year*plant,data=dat1) # count~year*plantの線形回帰の結果をres.n1という変数の中に格納\r\nlogLik(res.n0);logLik(res.n1) # res.n0とres.n1の対数尤度を表示\r\nAIC(res.n0,res.n1) # res.n0とres.n1のAICを表示\r\n\r\nplot(count~year,data=dat1,pch=as.numeric(plant)+1,col=as.numeric(plant)+1)     # 散布図を描く.データ点の形や色をplantで変える\r\nyear <- 0:9 # 年 0~9を変数として定義しておく\r\nlines(year,res.n1$coef[1]+res.n1$coef[2]*year,col=\"red\") # linesでモデルから得られた線を散布図に上書きする(plant=\"shrub\"のとき)\r\nlines(year,res.n1$coef[1]+res.n1$coef[3]+(res.n1$coef[2]+res.n1$coef[4])*year,col=\"green\",lty=2) # linesでモデルから得られた線を散布図に上書きする(plant=\"tree\"のとき)\r\n\r\nlibrary(MuMIn) # モデル選択を行うためのパッケージ.installしてない人は事前にinstall.packages(\"MuMIn\")としてください.\r\noptions(na.action = \"na.fail\") # 欠測値の取り扱いに関する設定(これをしないとdredgeが動かない).欠測値があったときに,欠測値を無視しない.\r\ndredge(res.n1,rank=\"AIC\") # フルモデルから変数を除いたすべての組み合わせでモデルを比較.rank=\"AIC\"でAICを使う(defaultはAICc)\r\n\r\n## ポアソン回帰\r\n\r\n# ポアソン回帰の尤度関数\r\nPoisson.reg <- function(p,dat){\r\n lambda <- exp(p[1]+p[2]*dat$year) # ポアソンの平均ラムダはいつも正なので,線形モデルを指数変換する.log(lambda)=a+b*yearとなるので,log link関数という.\r\n -sum(dat$count*log(lambda)-lambda) # optimなど最適化関数は最小値を求めるので,対数尤度にマイナス符号をつける\r\n}\r\n\r\noptim(c(log(6),-0.07),Poisson.reg,dat=dat1,method=\"BFGS\") # optim(パラメータの初期値, 最適化する関数, データ, method=最適化の方法) \r\n\r\nglm(count~year,family=poisson,data=dat1) # count~yearのポアソン回帰 family=poissonでポアソン分布を指定\r\n\r\nglm(count~year*plant,family=poisson,data=dat1) # count~year+plant+year:plantのポアソン回帰\r\n\r\nres.p1 <- glm(count~year*plant,family=poisson,data=dat1) # フルモデルをres.p1に格納\r\ndredge(res.p1,rank=\"AIC\") # AICでモデル選択\r\n\r\n# 正規線形回帰の場合と同様,ポアソン回帰のあてはまりの図を作成\r\nplot(count~year,data=dat1,pch=as.numeric(plant)+1,col=as.numeric(plant)+1)\r\nyear <- 0:9\r\nlines(year,exp(res.p1$coef[1]+res.p1$coef[2]*year),col=\"red\")\r\nlines(year,exp(res.p1$coef[1]+res.p1$coef[3]+(res.p1$coef[2]+res.p1$coef[4])*year),col=\"green\",lty=2)\r\n\r\n## ロジスティック回帰\r\n\r\n# ロジスティック回帰の対数尤度関数\r\nLogit.reg <- function(p,dat){\r\n prob <- 1/(1+exp(-(p[1]+p[2]*dat$year))) # 確率は0~1の間の数字なので,こういう変換をしてやる.逆関数はlogit=log(p/(1-p))\r\n -sum(dat$count*log(prob)+(10-dat$count)*log(1-prob)) # 二項分布の式から\r\n}\r\n\r\noptim(c(0,0),Logit.reg,dat=dat1,method=\"BFGS\") # optimで最適化\r\n\r\nglm(cbind(count,10-count)~year,family=binomial,data=dat1) # glmだと cbind(成功回数,失敗回数) ~ yearのような書き方にする.他に,0と1だけの結果ならz ~ yearのような書き方も可.\r\n\r\nres.l1 <- glm(cbind(count,10-count)~year*plant,family=binomial,data=dat1) # ロジスティック回帰のフルモデル\r\ndredge(res.l1,rank=\"AIC\") # AICでモデル選択\r\n\r\n## N-混合モデル\r\n\r\n# N混合モデルの発見関数の部分(二項分布モデル)\r\ndetect.f <- function(p, dat, N, n=10){\r\n y <- dat$count # 応答変数\r\n X <- cbind(1,as.numeric(dat$plant)-1) # plantはカテゴリーなので,0 (shrub) か1 (tree)に変換してやる.model.matrix関数を使うこともできる\r\n r <- c(1/(1+exp(-X%*%p))) # 1匹あたりの発見確率をplantとリンクする.X%*%pは行列とベクトルの掛算\r\n \r\n dbinom(y,n,1-(1-r)^N) # 二項確率モデル.個体はNいるので,少なくとも1回発見する確率は1-(1-r)^Nとなる.\r\n}\r\n\r\nlog(detect.f(c(1,1),dat1,2*dat1$count))[1:5] # 発見モデルがちゃんと動くかテスト\r\n\r\n# N混合モデルの個体数変動の部分(ポアソン分布モデル)\r\npop.f <- function(p, dat, N){\r\n X <- cbind(1,dat$year) # 説明変数の行列\r\n lambda <- c(exp(X%*%p)) # 平均個体数(年で変化する)\r\n \r\n dpois(N,lambda) # ポアソン尤度\r\n}\r\n\r\n# N混合モデルの尤度関数\r\npopdet.f <- function(p, dat, max.N=100, n=10){\r\n Pop <- function(i) {\r\n pop1 <- pop.f(p[3:4],dat[i,],0:max.N) # 個々のデータに対して,ポアソン確率を0からmax.Nまで計算する\r\n pop1 <- pop1/sum(pop1) # max.N=100で打ち切ったので,確率にするため全部の和で割ってやる\r\n pop1\r\n }\r\n like <- sapply(1:nrow(dat), function(i) sum(detect.f(p[1:2],dat[i,],0:max.N,n)*Pop(i))) # 0~max.Nを足し合わせた周辺尤度関数を各データ(行)に対して計算\r\n -sum(log(like)) # 対数尤度にして足し合わせる\r\n}\r\n\r\n(res.nm <- optim(c(0,0,0,0),popdet.f,dat=dat1,max.N=100,method=\"BFGS\")) # optimで最適化 ()でくくると結果が表示される\r\n\r\ntable(dat1$plant,dat1$year) # plantのyearによる変化を見てやって,個体数変化の解釈をする\r\n\r\n# N混合モデルの曲線をプロットしてやる\r\nplot(count~year,data=dat1) \r\nlines(year,exp(res.nm$par[3]+res.nm$par[4]*year))\r\n\r\n## 精度計算と信頼区間(対数正規モデル) \r\n\r\n# 精度計算のため,hessian=TRUEとしてヘッセ行列を取り出す\r\n(res.nm <- optim(c(0,0,0,0),popdet.f,dat=dat1,max.N=100,method=\"BFGS\",hessian=TRUE))\r\n\r\n# ヘッセ行列の逆行列はパラメータ推定値の分散共分散行列になっている\r\n(var.nm <- solve(res.nm$hessian))\r\n\r\n# パラメータは個体数をlog scaleで見たものなので元のスケールに戻してやる\r\npred.N <- function(p,year) exp(p[3]+p[4]*year)\r\n(E.N <- pred.N(res.nm$par,year))\r\n\r\n# 個体数推定値をパラメータで微分したもの(数値微分)を計算して,デルタ法で個体数の分散や標準誤差,CVを計算 \r\nDN <- function(p,year,d=0.0001){\r\n dp <- diag(d,length(p))\r\n apply(dp,1,function(x) (pred.N(p+x,year)-pred.N(p-x,year))/(2*d))\r\n}\r\ndN <- DN(res.nm$par,0:9)\r\n(var.N <- apply(dN, 1, function(x) x%*%var.nm%*%x))\r\n(se.N <- sqrt(var.N))\r\n\r\n(CV.N <- se.N/E.N)\r\n\r\n# 上のCVを使って対数正規の95%信頼区間をプロットしてやる \r\nplot(count~year,data=dat1)\r\nlines(year,E.N)\r\nalpha <- 0.05\r\nC.ci <- exp(qnorm(1-alpha/2)*sqrt(log(1+CV.N^2)))\r\nLo.lim <- E.N/C.ci\r\nUp.lim <- E.N*C.ci\r\narrows(year,Lo.lim,year,Up.lim,angle=90,code=3,length=0.03,col=\"blue\") \r\n\r\n## ブートストラップ信頼区間\r\n# 上では対数正規を使ったが,個体数に対数正規の仮定をおかないで信頼区間を作りたい\r\n\r\n# ノンパラメトリックブートストラップ\r\nB <- 1000\r\nb.boot <- NULL\r\nfor (i in 1:B){\r\n res.n0.b <- lm(count~year, data=dat1[sample(100,replace=TRUE),]) # リサンプリングしたデータに線形回帰をフィット\r\n b.boot <- c(b.boot, res.n0.b$coef[2]) # 傾きの推定値をとっておく\r\n}\r\nquantile(b.boot,probs=c(0.025,0.975)) # quantile関数で95%信頼区間を出す\r\n\r\n# 残差ブートストラップ\r\n# 上のノンパラブートストラップでは,説明変数の出現頻度も変わってしまう,それが望ましくない場合もある.そこで残差をブートストラップする.\r\nresid.n0 <- residuals(res.n0) # 残差を計算\r\nb.rb <- NULL\r\nfor (i in 1:B){\r\n count.rb <- predict(res.n0)+resid.n0[sample(100,replace=TRUE)] # リサンプリングした残差を予測値に足して,新たなデータを作る(ここも研修のとき間違ったコードでした.すいません)\r\n res.n0.rb <- lm(count.rb~year, data=dat1) # 新たなデータに線形回帰モデルをフィット\r\n b.rb <- c(b.rb, res.n0.rb$coef[2]) # 傾きをとっておく\r\n}\r\nquantile(b.rb,probs=c(0.025,0.975)) # 95%信頼区間\r\n\r\n# パラメトリックブートストラップ\r\n# ポアソンの場合,カウントデータが応答変数になるので残差ブートストラップは望ましくない\r\nres.p0 <- glm(count~year,family=poisson,data=dat1) # ポアソン回帰の結果\r\npred.p0 <- predict(res.p0,type=\"response\") # 予測値を計算してやる.predictはdefaultで線形予測子を返すので,type=\"response\"として元のスケールに戻してやる(正規分布の場合はidentity linkなのでこの操作必要なかった)\r\nb.pb <- NULL\r\nfor (i in 1:B){\r\n count.pb <- rpois(100,pred.p0) # 予測値を使ってポアソン乱数を発生\r\n res.p0.pb <- glm(count.pb~year,family=poisson,data=dat1) # 生成したデータにポアソン回帰を実行\r\n b.pb <- c(b.pb, res.p0.pb$coef[2]) # 傾きを記録する\r\n}\r\nquantile(b.pb,probs=c(0.025,0.975)) # 95%信頼区間\r\n\r\n# N混合モデルの確率を計算する関数\r\ndnm <- function(x, p, year, plant, max.N=100, n=10){\r\n lambda <- exp(p[3]+p[4]*year)\r\n pop1 <- dpois(0:max.N,lambda)\r\n pop1 <- pop1/sum(pop1)\r\n pop1\r\n r <- 1/(1+exp(-(p[1]+p[2]*plant)))\r\n sum(dbinom(x,n,1-(1-r)^(0:max.N))*pop1)\r\n}\r\n\r\n# 各データに対して,発見数が0から10までの場合の確率を計算してやる \r\nprob.nm <- sapply(1:100, function(i) sapply(0:10,function(x) dnm(x,res.nm$par,as.numeric(dat1$year[i]),as.numeric(dat1$plant[i])-1)))\r\ncprob.nm <- apply(prob.nm,2,cumsum) # 累積確率分布を計算\r\n\r\ndat1.cb <- dat1\r\nd <- 10^(-10) # 数値計算の精度の調整のために必要\r\nb.nm <- NULL\r\nfor (i in 1:B){\r\n z.cb <- runif(100,0,1) # 一様乱数を発生\r\n count.nm <- sapply(1:100, function(x) which(cprob.nm[,x] >= z.cb[x]-d)[1]-1) # 上で計算した累積確率との比較で,データ(0~10)を作り出してやる\r\n dat1.cb$count <- count.nm # できたデータを応答変数にする\r\n res.nm.cb <- optim(c(0,0,0,0),popdet.f,dat=dat1.cb,max.N=100,method=\"BFGS\") # N混合モデルによるパラメータ推定\r\n b.nm <- rbind(b.nm, exp(res.nm.cb$par[3]+res.nm.cb$par[4]*year)) # 0~9年の個体数推定値を計算\r\n}\r\nCI.cb <- apply(b.nm,2,quantile,probs=c(0.025,0.975)) # 信頼区間を計算\r\n\r\n# N混合モデルのブートストラップ信頼区間をプロット \r\nplot(count~year,data=dat1)\r\nlines(year,E.N)\r\narrows(year,CI.cb[1,],year,CI.cb[2,],angle=90,code=3,length=0.03,col=\"blue\")\r\n\r\n## Template Model Builder実例\r\n# 上のN混合モデルのbooststrap計算は結構時間がかかる.そこでTMBを使って高速化してやる.\r\n \r\nsink(\"nm.cpp\") # nm.cppというcppファイルを作ってやる.\r\n# nm.cppにTMBのための関数を書いてやる.\r\ncat(\"// N-mixture model \r\n\r\n#include \r\n\r\n/* Parameter estimation */\r\ntemplate\r\nType objective_function::operator() ()\r\n{\r\n // Data Section //\r\n DATA_INTEGER(Nmax);\r\n DATA_SCALAR(n);\r\n DATA_MATRIX(DAT);\r\n\r\n // Parameter Section //\r\n PARAMETER_VECTOR(P);\r\n \r\n int N=DAT.rows();\r\n \r\n matrix Pois(Nmax+1,N);\r\n vector D(N);\r\n vector Log_Lambda(N);\r\n vector R(N);\r\n vector BP(N);\r\n \r\n Type d=1e-15;\r\n \r\n Type f=0;\r\n \r\n for (int j=0;j= z.cb.tmb[x]-d)[1]-1)\r\n dat2[,1] <- count.nm.tmb\r\n dat <- list(Nmax=100, n=10, DAT=as.matrix(dat2))\r\n parms <- list(P=c(0,0,0,0))\r\n obj <- MakeADFun(data=dat,parameters=parms,DLL=\"nm\")\r\n res.nm.cb.tmb <- optim(obj$par,obj$fn,obj$gr,method=\"BFGS\")\r\n b.nm.tmb <- rbind(b.nm.tmb, exp(res.nm.cb.tmb$par[3]+res.nm.cb.tmb$par[4]*year))\r\n}\r\nCI.cb.tmb <- apply(b.nm.tmb,2,quantile,probs=c(0.025,0.975))\r\n\r\n# TMBで作ったブートストラップ信頼区間を描画する \r\nplot(count~year,data=dat1)\r\nlines(year,E.N)\r\narrows(year,CI.cb.tmb[1,],year,CI.cb.tmb[2,],angle=90,code=3,length=0.03,col=\"blue\")\r\n", "meta": {"hexsha": "04384881309069998065c287c525d556d52cd142", "size": 11919, "ext": "r", "lang": "R", "max_stars_repo_path": "2-okamura/kenshu_okamura.r", "max_stars_repo_name": "ichimomo/Shigen-kensyu-2018", "max_stars_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T07:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T04:22:43.000Z", "max_issues_repo_path": "2-okamura/kenshu_okamura.r", "max_issues_repo_name": "ichimomo/Shigen-kensyu-2018", "max_issues_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "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": "2-okamura/kenshu_okamura.r", "max_forks_repo_name": "ichimomo/Shigen-kensyu-2018", "max_forks_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-20T02:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T09:09:31.000Z", "avg_line_length": 36.9009287926, "max_line_length": 169, "alphanum_fraction": 0.6334424029, "num_tokens": 6455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.6528575040599948}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\n\r\nrm(list=ls(all=TRUE))\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\ncat(\"Stan version:\", stan_version(), \"\\n\")\r\nstanmodelcode <- \"\r\n\r\n\r\n#### define GP function\r\nfunctions {\r\n\r\nreal normal_generalized_poisson_log(int y, real theta, real lambda, real sigob) { \r\n return (log(theta) \r\n + (y - 1) * log(theta + y * lambda) \r\n - lgamma(y + 1) \r\n - y * lambda \r\n - theta)*(y<=200)\r\n +(normal_lpdf(y|theta,sigob))*(y>200);\r\n\r\n } \r\n\r\n}\r\n\r\n\r\n#### define our data, integer value\r\ndata {\r\nint N;\r\nint y[N];\r\nreal E[N];\r\n}\r\n\r\n\r\n#### define parameters \r\nparameters {\r\n\r\nreal lambda;\r\nreal u;\r\nreal b8;\r\nreal b9;\r\nreal b10;\r\nreal sig2;\r\nvector[N] e;\r\nreal sigob;\r\n}\r\n\r\n\r\n#### define some parameters which is the function of other parameters \r\ntransformed parameters {\r\nvector[N] mu;\r\n\r\n### define the mean function\r\n\r\n\r\nmu[1] <- y[1]; ## not tested\r\n\r\n for (n in 2:N) {\r\n\t\r\n mu[n] <- mu[n-1]*exp(u+b8*((1-exp(-mu[n-1]/b10))/(mu[n-1]/b10))+b9*((1-exp(-mu[n-1]/b10))/(mu[n-1]/b10)-exp(-mu[n-1]/b10))+e[n]); \r\n\t \r\n\t \r\n\t }\r\n\r\n}\r\n\r\n\r\n\r\n##### define piror and likelihood function\r\nmodel {\r\nlambda~uniform(-1,1);\r\nu ~ normal(0.028,0.01);\r\nb8 ~ normal(0.05,0.01);\r\nb9 ~ normal(0.05,0.01);\r\nb10 ~ normal(0.05,0.01);\r\nsig2 ~ gamma(1,1); \r\ne~normal(0,sig2);\r\nsigob ~ uniform(100,1100);\r\n\r\nfor (j in 1:N) {\r\n\r\ny[j] ~ normal_generalized_poisson( mu[j]*E[j], lambda, sigob);\r\n}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n#### calculate DIC\r\ngenerated quantities {\r\nvector[N] log_lik;\r\nreal dev; // deviance\r\n\r\n\r\n for (n in 1:N){\r\n log_lik[n] <- normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n dev <- 0;\r\n for ( n in 1:N ) {\r\n dev <- dev + (-2) * normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\"\r\n\r\n\r\n###### \r\n\r\n\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covid19modelrisk/data/covid19_infected/\")\r\n\r\n## y=read.csv(\"COVID-19_confirmed__Germany.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Italy.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Japan.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Spain.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__US.csv\")\r\n y=read.csv(\"COVID-19_confirmed_Australia.csv\")\r\n\r\ny=y[,2]\r\n\r\n\r\n\r\n\r\nE=rep(1,length(y))\r\n\r\nN=length(y)\r\ndat <- list(N = N, y = y,E=E)\r\n\r\n\r\n#### initial values\r\ninits =list(list(lambda=0,u=0.028,b8=0.05,b9=0.05,b10=0.05,sig2=0.0005,e=rep(0.01,N),sigob=1000)) ### 134\r\n\r\n\r\nfit <- stan(model_code = stanmodelcode, model_name = \"example\",init =inits,\r\ndata = dat, warmup=10000,iter = 100000, chains = 1, seed=999,thin=1)\r\nprint(fit,digits = 4)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################### trace plot\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nk=6\r\n\r\npdf(paste(\"M10_\",abn[k],\"_p1.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"u\",\"b8\",\"b9\",\"b10\"), inc_warmup = T, nrow = 4, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\npdf(paste(\"M10_\",abn[k],\"_p2.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"sigob\",\"sig2\",\"lambda\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n################## plot 30/45/60/ length(y)\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M10_\",abn[k],\"_30.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=30\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M10_\",abn[k],\"_45.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=45\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M10_\",abn[k],\"_60.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=60\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M10_\",abn[k],\"_all.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n######## log plot ####################################################\r\n\r\nk=1\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\n\r\ny=log(y)\r\nEpars_m=log(Epars_m)\r\nEpars_9=log(Epars_9)\r\nEpars_5=log(Epars_5)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/forecast\")\r\n\r\npdf(paste(\"M10_\",abn[k],\"_log.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M10 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#####################################################################################################################################################\r\n###################################### forecast ###################################\r\n\r\nGP.r <- function(L, s)\r\n{\r\n\r\nv=0\r\nLp=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nsLp=Lp\r\n\r\n# calculate the vector of cum pmf\r\nv=1\r\nwhile((sLp<0.9999999) & ((L + v * s )> 0)) \r\n{Lp1=exp(log(L)+ (v - 1) * log(L + v * s) - v * s - L - lgamma(v + 1))\r\nLp=c(Lp,Lp1)\r\nsLp=sLp+Lp1\r\nv=v+1\r\n}\r\n\r\ncsLp=c(cumsum(Lp),1) ##### add a max for it \r\nx=length(Lp)\r\n\r\n# first check if you are in the first interval\r\n\r\nU = runif(1)\r\nB = FALSE\r\ni = 1\r\n \r\nwhile(B == FALSE) { \r\n \r\n if(U > csLp[i]) ### U may greater than max of csLp if do not set 1\r\n { i=i+1}\r\n else\r\n {X=i-1\r\n B=TRUE} \r\n\r\n}\r\n\r\nreturn(X)\r\n\r\n}\r\n\r\n################################################ as.data.frame(fit@sim[[1]][[1]])[1,]\r\n\r\nP=20\r\nMu=matrix(,nrow=90000,ncol=P)\r\nX=matrix(,nrow=90000,ncol=P)\r\n\r\n\r\nlambda_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,1]\r\nu_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,2]\r\nb8_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,3]\r\nb9_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,4]\r\nb10_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,5]\r\nsig2_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,6]\r\n\r\n\r\nset.seed(999)\r\n\r\nfor (r in 1:90000){\r\n\r\n\r\n\r\nMu[r,1]=y[length(y)]\r\nfor (s in 1:(P-1) ){\r\n\r\ne=rnorm(1,0,sig2_p[r])\r\n\r\nMu[r,s+1]=Mu[r,s]*exp(u_p[r]+b8_p[r]*((1-exp(-Mu[r,s]/b10_p[r]))/(Mu[r,s]/b10_p[r]))+b9_p[r]*((1-exp(-Mu[r,s]/b10_p[r]))/(Mu[r,s]/b10_p[r])-exp(-Mu[r,s]/b10_p[r]))+e)\r\n\r\n\r\n\r\n}}\r\n\r\n\r\n\r\n\r\nfor (r in 1:90000){\r\nfor (s in 1:(P-1) ){\r\n\r\nX[r,s]=GP.r(Mu[r,s]*(1-lambda_p[r]), lambda_p[r])\r\n\r\n\r\n}}\r\n\r\n\r\n#X=Mu\r\n\r\n\r\nXm=apply(X,2,mean)\r\n\r\nX5 <- apply( X , 2 , quantile, probs=0.05 )\r\n\r\nX9 <- apply( X , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\nZm=c(y,Xm)\r\nZ5=c(y,X5)\r\nZ9=c(y,X9)\r\n\r\n\r\nk=1\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nm=length(Zm)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Z9[1:m]), Z5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Z9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Z5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M2 model for \",name[k],sep=\"\"),pch=19)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n########################################################################################################################\r\n\r\nn=length(y)\r\n\r\n\r\n\r\nu=0.028\r\nb8=0.05\r\nb9=0.05\r\nb10=0.05\r\n\r\n\r\nx=c()\r\nx[1]=100\r\nfor (i in 1:(n-1) ){\r\n\r\nx[i+1]=x[i]*exp(u+b8*((1-exp(-x[i]/b10))/(x[i]/b10))+b9*((1-exp(-x[i]/b10))/(x[i]/b10)-exp(-x[i]/b10)))\r\n}\r\nx=round(x)\r\nx\r\n\r\n\r\n\r\nplot(y,ylim=c(min(y,x),max(y,x)))\r\npar(new=TRUE)\r\nplot(x,col=\"red\",ylim=c(min(y,x),max(y,x)))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0f97066e7ba2560e0f650e590e14f08d70b99773", "size": 12852, "ext": "r", "lang": "R", "max_stars_repo_path": "R/M10 run.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M10 run.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/M10 run.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 22.6267605634, "max_line_length": 179, "alphanum_fraction": 0.5413943355, "num_tokens": 4771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6524827671745409}} {"text": "# Impact factor vs rejection rate\n# Written by Jon Tennant, ScienceOpen\n\n# Input data from Figshare (https://figshare.com/s/d81dcba0b9c5400a9c46) after saving as a .csv file\nsetwd(\"file pathway\")\n\ndata<-read.csv(\"filename.csv\",header=TRUE)\n\n# Create two new vectors\nIF<-data[,2]\nRej.rate<-data[,1]\n\n# Perform a simple linear regression\nFit.IF<-lm(Rej.rate~IF)\nsummary(Fit.IF)\nplot(Fit.IF)\n\n# Perform bivariate correlation tests\ncor.test(Rej.rate,IF,method=\"pearson\")\ncor.test(Rej.rate,IF,method=\"spearman\")\ncor.test(Rej.rate,IF,method=\"kendall\")\n\n# Results\n# Pearson's: cor=0.0453, p=0.0005\n# Spearman's: cor=0.0344, p=0.412\n# Kendall's: cor=0.0204, p=0.4706\n\n# Plot the results up and export the plot as a PDF\npdf(file='If vs Rej Rate.pdf', width=14, height=8)\nplot(Rej.rate,IF,type=\"p\",pch=1,ylab=\"Journal impact factor (2014)\",xlab=\"Journal rejection rate\")\nabline(lm(IF~Rej.rate),lwd=2,col=\"red\",lty=2)\nlegend(\"topleft\",c(\"Pearson's: cor=0.453, p=0.0005\",\"Spearman's: cor=0.0344, p=0.412\",\"Kendall's: cor=0.0204, p=0.4706\"),border=\"NA\")\ndev.off()\n\n# Repeat but with a rejection rate threshold of 0.6\n# Note that you can input data with any threshold range you like\ndata2<-read.csv(\"modified filename.csv\",header=TRUE)\n\nIF.2<-data2[,2]\nRej.rate.2<-data2[,1]\n\nFit.IF.2<-lm(Rej.rate.2~IF.2)\nsummary(Fit.IF.2)\nplot(Fit.IF.2)\n\ncor.test(Rej.rate.2,IF.2,method=\"pearson\") #cor=0.343, p=1.745^-11\ncor.test(Rej.rate.2,IF.2,method=\"spearman\") #cor=0.189, p=0.0003\ncor.test(Rej.rate.2,IF.2,method=\"kendall\") #cor=0.131, p=0.0003\n\npdf(file='If vs Rej Rate, reduced.pdf', width=14, height=8)\nplot(Rej.rate.2,IF.2,type=\"p\",pch=1,ylab=\"Journal impact factor (2014)\",xlab=\"Journal rejection rate\")\nabline(lm(IF.2~Rej.rate.2),lwd=2,col=\"red\",lty=2)\nlegend(\"topleft\",c(\"cor=0.343, p=1.745^-11\",\"cor=0.189, p=0.0003\",\"cor=0.131, p=0.0003\"))\ndev.off()\n\n# Repeat but with a modified rejection rate threshold of 0.9\ndata3<-read.csv(\"modified filename_2.csv\",header=TRUE)\n\nIF.3<-data3[,2]\nRej.rate.3<-data3[,1]\n\nFit.IF.3<-lm(Rej.rate.3~IF.3)\nsummary(Fit.IF.3)\nplot(Fit.IF.3)\n\ncor.test(Rej.rate.3,IF.3,method=\"pearson\") #cor=0.09, p=0.732\ncor.test(Rej.rate.3,IF.3,method=\"spearman\") #cor=0.094, p=0.72\ncor.test(Rej.rate.3,IF.3,method=\"kendall\") #cor=0.096, p=0.612\n\npdf(file='If vs Rej Rate, reduced2.pdf', width=14, height=8)\nplot(Rej.rate.3,IF.3,type=\"p\",pch=1,ylab=\"Journal impact factor (2014)\",xlab=\"Journal rejection rate\")\nabline(lm(IF.3~Rej.rate.3),lwd=2,col=\"red\",lty=2)\nlegend(\"topleft\",c(\"cor=0.09, p=0.732\",\"cor=0.094, p=0.72\",\"cor=0.096, p=0.612\"))\ndev.off()\n", "meta": {"hexsha": "0e530f5cc41a54ba5fbfeb28c8350737580fadcf", "size": 2552, "ext": "r", "lang": "R", "max_stars_repo_path": "Analysis.r", "max_stars_repo_name": "Protohedgehog/Rejected", "max_stars_repo_head_hexsha": "e214a35950a2fbffb9f7a67b7951532e58211237", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-02T18:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-02T18:28:34.000Z", "max_issues_repo_path": "Analysis.r", "max_issues_repo_name": "Protohedgehog/Rejected", "max_issues_repo_head_hexsha": "e214a35950a2fbffb9f7a67b7951532e58211237", "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": "Analysis.r", "max_forks_repo_name": "Protohedgehog/Rejected", "max_forks_repo_head_hexsha": "e214a35950a2fbffb9f7a67b7951532e58211237", "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": 34.0266666667, "max_line_length": 133, "alphanum_fraction": 0.6982758621, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6524551871701098}} {"text": "# 4. faza: Analiza podatkov\n\n#NAPOVED RASTI NETO POVPREČNE PLAČE V SLOVENIJI\n#linearna regresija\n\n\n\n\nmodel <- lm(POVPRECNA.MESECNA.PLACA.SLO ~ MESEC, data=mesecne.place.slo)\n\n#napoved za vsak prvi mesec v letu\n\nprihodnja.leta <- data.frame(MESEC = c(\"2014-01-01\", \"2015-01-01\", \"2015-01-01\", \"2016-01-01\", \"2017-01-01\", \"2018-01-01\", \"2019-01-01\",\n \n \"2020-01-01\", \"2021-01-01\", \"2022-01-01\", \"2023-01-01\", \"2024-01-01\", \"2025-01-01\"))\n\nprihodnja.leta$MESEC <- as.Date(prihodnja.leta$MESEC)\n\nnapoved.slo <- mutate(prihodnja.leta, POVPRECNA.MESECNA.PLACA.SLO = predict(model,prihodnja.leta))\n\nnapoved.graf <- ggplot(mesecne.place.slo, aes( x = MESEC, y = POVPRECNA.MESECNA.PLACA.SLO)) + geom_point() +\n \n geom_smooth(method = 'lm', fullrange = TRUE, formula = y~x) + \n \n geom_point(data = napoved.slo, aes( x = MESEC, y = POVPRECNA.MESECNA.PLACA.SLO),color='red') +\n xlab(\"Leto\") + ylab(\"Mesečna plača (€)\") + ggtitle('Napoved mesečnih januarskih plač')\n\n\n", "meta": {"hexsha": "1e418d40568b56aa065a73c92d8fef02a473c008", "size": 1036, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "piaklemenc/APPR-2020-21", "max_stars_repo_head_hexsha": "d8d295b92ab07eeec4e68e022b5c5007684b2c85", "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": "piaklemenc/APPR-2020-21", "max_issues_repo_head_hexsha": "d8d295b92ab07eeec4e68e022b5c5007684b2c85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-12-06T09:32:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T10:17:05.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "piaklemenc/APPR-2020-21", "max_forks_repo_head_hexsha": "d8d295b92ab07eeec4e68e022b5c5007684b2c85", "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.724137931, "max_line_length": 136, "alphanum_fraction": 0.6312741313, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.6522350978974836}} {"text": "gauss <- function(a, b) {\n n <- nrow(a)\n det <- 1\n\n for (i in seq_len(n - 1)) {\n j <- which.max(a[i:n, i]) + i - 1\n if (j != i) {\n a[c(i, j), i:n] <- a[c(j, i), i:n]\n b[c(i, j), ] <- b[c(j, i), ]\n det <- -det\n }\n\n k <- seq(i + 1, n)\n for (j in k) {\n s <- a[[j, i]] / a[[i, i]]\n a[j, k] <- a[j, k] - s * a[i, k]\n b[j, ] <- b[j, ] - s * b[i, ]\n }\n }\n\n for (i in seq(n, 1)) {\n if (i < n) {\n for (j in seq(i + 1, n)) {\n b[i, ] <- b[i, ] - a[[i, j]] * b[j, ]\n }\n }\n b[i, ] <- b[i, ] / a[[i, i]]\n det <- det * a[[i, i]]\n }\n\n list(x=b, det=det)\n}\n\na <- matrix(c(2, 9, 4, 7, 5, 3, 6, 1, 8), 3, 3, byrow=T)\ngauss(a, diag(3))\n", "meta": {"hexsha": "9148959371107600b440e2f8166825a0b4703369", "size": 700, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Gaussian-elimination/R/gaussian-elimination.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Gaussian-elimination/R/gaussian-elimination.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/Gaussian-elimination/R/gaussian-elimination.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4444444444, "max_line_length": 56, "alphanum_fraction": 0.3185714286, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.6522292021175516}} {"text": "\r\n# Functia care genereaza repartitia comuna incompleta\r\n\r\nfrepcomgen = function(m, n) {\r\n m=2\r\n n=3\r\n \r\n # Generam m valori pentru x in intervalul [0, m * 10] si\r\n # n valori pentru y in [0, n * 10]\r\n xValues <- sample.int(m * 10, m);\r\n yValues <- sample.int(n * 10, n);\r\n \r\n # Adaugam in acesti vectori Qi si Pi pentru capetele de tabel\r\n xValues <- c(xValues, 'Qi')\r\n yValues <- c(yValues, 'Pi')\r\n \r\n # Construim tabelul de repartitie, reprezentat ca o matrice, unde valoarea -1\r\n # semnifica faptul ca probabilitatea pentru (X = xi si Y=yi) nu este cunoscuta\r\n repart <- matrix(-1, nrow=m+1, ncol=n+1)\r\n rownames(repart) <- xValues\r\n colnames(repart) <- yValues\r\n repart[m+1, n+1] = 1\r\n \r\n \r\n # Completam repartitia cu valori aleatoare, dar care vor respecta totusi conditia ca\r\n # suma pe linii/coloane sa fie mai mica ca 1 (sau egala)\r\n repart[1, 4] <- runif(1, 0, 1)\r\n repart[1, 1] <- runif(1, 0, repart[1, 4])\r\n \r\n repart[3, 1] <- runif(1, repart[1, 1], 1)\r\n \r\n repart[2, 2] <- runif(1, 0, 1 - repart[3, 1])\r\n while(repart[3, 2] - repart[2, 2] + repart[1, 1] > repart[1, 4] || \r\n repart[3, 1] - repart[1, 1] + repart[2, 2] > 1 - repart[1, 4])\r\n repart[2, 2] <- runif(1, 0, 1 - repart[3, 1])\r\n \r\n repart[3, 2] <- runif(1, min(repart[2, 2], repart[3, 1]), 1 - max(repart[2, 2], repart[3, 1]))\r\n while(repart[3, 2] + repart[3, 1] > 1 || repart[2, 2] > repart[3, 2])\r\n repart[3, 2] <- runif(1, min(repart[2, 2], repart[3, 1]), 1 - max(repart[2, 2], repart[3, 1]))\r\n \r\n return(repart)\r\n}\r\n\r\n# Functia fcomplrepcom efectueaza operatii pe linii si coloane pentru a determina valorile\r\n# necunoscute din repartitia comuna\r\nfcomplrepcom <- function(repart) {\r\n repart[2, 4] = 1 - repart[1, 4]\r\n repart[1, 2] = repart[3, 2] - repart[2, 2]\r\n repart[1, 3] = repart[1, 4] - repart[1, 1] - repart[1, 2]\r\n repart[2, 1] = repart[3, 1] - repart[1, 1]\r\n repart[2, 3] = repart[2, 4] - repart[2, 2] - repart[2, 1]\r\n repart[3, 3] = 1 - repart[3, 1] - repart[3, 2]\r\n \r\n data.frame(repart)\r\n}\r\n\r\nrepart <- frepcomgen(2, 3)\r\n#repart\r\nfcomplrepcom(repart)\r\n\r\n", "meta": {"hexsha": "125a9a992e7d34d878d3aca4da6e8d0390fa12aa", "size": 2101, "ext": "r", "lang": "R", "max_stars_repo_path": "Proiect PS Ex3.r", "max_stars_repo_name": "IosifGabriel/Probability-Project", "max_stars_repo_head_hexsha": "cd59ca17e5601eed62d1247564561e5c2f759201", "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": "Proiect PS Ex3.r", "max_issues_repo_name": "IosifGabriel/Probability-Project", "max_issues_repo_head_hexsha": "cd59ca17e5601eed62d1247564561e5c2f759201", "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": "Proiect PS Ex3.r", "max_forks_repo_name": "IosifGabriel/Probability-Project", "max_forks_repo_head_hexsha": "cd59ca17e5601eed62d1247564561e5c2f759201", "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.4426229508, "max_line_length": 99, "alphanum_fraction": 0.5916230366, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6521831080378432}} {"text": "# condPvalue: This is the conditional p-value integral described in Andrews, Moreira, and Stock (2007, Journal of Econometrics)\n# P(m,qT) = 1 - Pr(LR > m |QT = qT)\n# m: test stat value\n# qT: conditional value of Qt\n# k: number of moment conditions (i.e. number of instruments)\n# \n# eps: epsilon (for numerical stability, default set based on Andrews, Moreira, and Stock's 2007 recommendation (0.02)\n# OUTPUT: a p-value\n# NOTE: mimics condivreg.ado's new_try function in Mikusheva and Poi (2006)'s STATA function\ncondPvalue <- function(m,qT,k,df2,eps = 0.02) {\n if(k == 1) { # Eqivalent to AR #\n return(1 - pf(m,k,df2))\n }\n K = gamma(k/2) / (sqrt(pi) * gamma((k-1)/2)) \n if(k == 2) {\n return(1 - 2 * K * integrate(function(x){pchisq( (qT + m)/(1 + qT * sin(x)^2/m),k)},lower=0,upper=pi/2)$value) \n } else if(k == 3) {\n return(1 - 2 * K * integrate(function(x){pchisq( (qT + m)/(1 + qT * x^2/m),k)},lower=0,upper=1)$value)\n } else if(k == 4) {\n nonapproxRegion = 2 * K * integrate(function(x){pchisq( (qT + m)/(1 + qT * x^2/m),k) * (1 - x^2)^((k-3)/2)},lower=0,upper=1-eps)$value\n approxRegion = 2 * K * pchisq( (qT + m) / (1 + qT *(1 - eps/2)^2 /m),k) * (1/2 * (pi/2 - asin(1 - eps)) - (1 - eps)/2 * sqrt( 1- (1 - eps)^2)) \n return(1 - nonapproxRegion - approxRegion)\n } else {\n return(1 - 2*K * integrate(function(x){pchisq( (qT + m)/(1 + qT * x^2/m),k) * (1 - x^2)^((k-3)/2)},lower=0,upper=1)$value)\n }\n}\n\n### CLR: Generates the CLR confidnece interval\n### Must run ivmodel before you run this code\n### INPUT: ivmodel, an object from ivmodel() function\n### alpha, significance level for confidence intervals\n### OUTPUT: a list of point estimate, standard error, test statistic, and p-value\nCLR = function(ivmodel,beta0=0,alpha=0.05) {\n # Error checking\n if(class(ivmodel) != \"ivmodel\") {\n print(\"CLR: You must supply an ivmodel class. See ivmodel function for details\")\n\treturn(NULL)\n }\n # Extract objects from ivmodel\n Yadj = ivmodel$Yadj; Dadj = ivmodel$Dadj; ZadjQR = ivmodel$ZadjQR\n Y = ivmodel$Y; D = ivmodel$D\n \n # Qs, Qst, Qst, Qt #\n YadjANDDadj = cbind(Yadj,Dadj) #You can also use the original Y and D\n PZYadjANDDadj = qr.fitted(ZadjQR,YadjANDDadj); \n RZYadjANDDadj = qr.resid(ZadjQR,YadjANDDadj); \n \n sigmaHat = (t(RZYadjANDDadj) %*% RZYadjANDDadj) / (ivmodel$n - ivmodel$p - ivmodel$L)\n sigmaHatInv = invTwobyTwoSymMatrix(sigmaHat) \n \n a0 = c(beta0,1); b0 = c(1,-beta0)\n denomS = t(b0) %*% sigmaHat %*% b0; denomT = t(a0) %*% sigmaHatInv %*% a0\n numT = PZYadjANDDadj %*% sigmaHatInv \n QS = sum( (PZYadjANDDadj %*% b0)^2) / denomS\n QT = sum( (PZYadjANDDadj %*% sigmaHatInv %*% a0)^2) / denomT\n QTS = sum( (PZYadjANDDadj %*% b0) * (PZYadjANDDadj %*% sigmaHatInv %*% a0)) / (sqrt(denomS) * sqrt(denomT))\n \n LRtest = 1/2 * (QS - QT + sqrt((QS + QT)^2 - 4*(QS *QT - QTS^2)))\n \n test.stat = matrix(LRtest,1,1)\n QT = as.numeric(QT); LRtest = as.numeric(LRtest)\n p.value = tryCatch({condPvalue(LRtest,QT,ivmodel$L,ivmodel$n - ivmodel$p- ivmodel$L)},error=function(e){0})\n p.value = matrix(p.value,1,1) \n maxEigen = max(quadSolver(a=1,b=-1*(QS + QT),c=QS *QT - QTS^2)) #of Q matrix\n C = tryCatch({uniroot(function(y){condPvalue(m=maxEigen - y,qT = y,k = ivmodel$L,df2=ivmodel$n - ivmodel$p- ivmodel$L) - alpha},\n \t lower=10*.Machine$double.eps,upper=maxEigen - 5*.Machine$double.eps,maxiter=5000)$root},error=function(e){0})\n quadMatrix.CLR = sigmaHatInv %*% t(YadjANDDadj) %*% PZYadjANDDadj %*% sigmaHatInv - C * sigmaHatInv\n ci.CLR = quadSolver(a=quadMatrix.CLR[1,1],b=2*quadMatrix.CLR[1,2],c=quadMatrix.CLR[2,2])\n if(quadMatrix.CLR[1,1] > 0) {\n if(is.na(ci.CLR[1])) {\n ci.CLR = matrix(c(-Inf,Inf),1,2)\n\t info = c(\"Whole Real Line\")\n } else {\n\t ci.CLR = matrix(c(-Inf,ci.CLR[1],ci.CLR[2],Inf),2,2,byrow=TRUE)\n\t\tinfo = c(paste(\"(-Infinity, \",ci.CLR[1,2],\"] union [\",ci.CLR[2,1],\", Infinity)\",sep=\"\"))\n\t }\n } else {\n ci.CLR = matrix(c(ci.CLR[1],ci.CLR[2]),1,2)\n\tinfo = paste(\"[\",ci.CLR[1,1],\", \",ci.CLR[1,2],\"]\",sep=\"\")\n }\n \n # Package output \n colnames(p.value) = colnames(test.stat) = beta0\n colnames(ci.CLR) = c(paste(as.character(round(alpha/2 * 100,1)),\"%\"),paste(as.character( round((1-alpha/2) * 100,1)),\"%\"))\n \n return(list(test.stat = test.stat,p.value = p.value,ci = ci.CLR,ci.info = info))\n}\n", "meta": {"hexsha": "508fe29680a717635b45dadde8bf4781669805b0", "size": 4383, "ext": "r", "lang": "R", "max_stars_repo_path": "R/CLR.r", "max_stars_repo_name": "qingyuanzhao/ivmodel", "max_stars_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-22T13:38:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T02:04:23.000Z", "max_issues_repo_path": "R/CLR.r", "max_issues_repo_name": "qingyuanzhao/ivmodel", "max_issues_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-09T19:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T13:44:24.000Z", "max_forks_repo_path": "R/CLR.r", "max_forks_repo_name": "qingyuanzhao/ivmodel", "max_forks_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-01T16:33:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T16:33:38.000Z", "avg_line_length": 49.8068181818, "max_line_length": 148, "alphanum_fraction": 0.6125941136, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6521830982869897}} {"text": "#more general function, v is assumed to be a vector\nspiralv<-function(v){\n n<-sqrt(length(v))\n if(n!=floor(n)) stop(simpleError(\"length of v should be a square of an integer\"))\n if(n==0) stop(simpleError(\"v should be of positive length\"))\n if(n==1) M<-matrix(v,1,1)\n else M<-rbind(v[1:n],cbind(spiralv(v[(2*n):(n^2)])[(n-1):1,(n-1):1],v[(n+1):(2*n-1)]))\n M\n}\n#wrapper\nspiral<-function(n){spiralv(0:(n^2-1))}\n#check:\nspiral(5)\n", "meta": {"hexsha": "68574c2a759f2f2c3d29df81513d566267a8c100", "size": 432, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Spiral-matrix/R/spiral-matrix-2.r", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Spiral-matrix/R/spiral-matrix-2.r", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "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/Spiral-matrix/R/spiral-matrix-2.r", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8571428571, "max_line_length": 88, "alphanum_fraction": 0.6319444444, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6521552431083147}} {"text": "#############################################################################3\n#\n# File: fitgumbeldist.r\n# Author: Alex Stivala\n# Created: July 2010\n#\n# fitgumbeldist.r - compute Gumbest dist. parameters and build plots\n#\n# R script for fitting Gumbel distribution (finding parameters location\n# and scale) and plotting histograms and fit over them.\n# Also, compute the z-score and p-values using this, then\n# compute coverage-vs-EPQ graph as used in Ortiz et al 2002 (and earlier\n# Levitt and Gerstein (1998) to compare the analytic and observed p-values)\n#\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# (score and label)\n# is obtained from --args.\n#\n# label is used to separate same fold (1) and different fold (0) scores,\n# different distributinos fitted to each\n#\n# outputs stuff on stdout (including the parameter values) and\n# creates PostScript file with histograms and curves, with filename\n# derived form input filename: basename_gumbel.eps\n# \n# R --vanilla -f plotssehistogram.r --args query200.slrtab\n#\n# creates query200_gumbel.eps\n# and query200_epq_gumbel.eps\n#\n# Uses the evir R package for gumbel fitting and the evd package for dbumbel()\n#\n# $Id: fitgumbeldist.r 3955 2010-07-21 05:52:47Z alexs $\n#############################################################################3\n\nlibrary(evir)\nlibrary(evd)\n\n\n#############################################################################3\n#\n# constants\n#\n#############################################################################3\n\ncolorvec=c('deepskyblue4','brown','red','turquoise','blue','purple','green','cyan','gray20','magenta','darkolivegreen2','midnightblue','magenta3','darkseagreen','violetred3','darkslategray3')\nltyvec=c(1,2,4,5,6,1,2,1,5,6,1,2,4,5,6,1,2)\npchvec=c(20,21,22,23,24,25,19,21,22)\n\neulergamma <- 0.5772156649015328606\n\n#############################################################################3\n#\n# functions\n#\n#############################################################################3\n\n\n# \n# z_gumbel() - compute Z-score from Gumbel distribution\n#\n# Parameters:\n# x - score to compute Z-score for\n# gumbel - evd object for Gumbel distribution from gumbel()\n#\n# Return value:\n# Z-score computed for x according to gum distribution\n#\nz_gumbel <- function(x, gum )\n{\n a<- gum0$par.ests[2]\n b <- gum0$par.ests[1]\n mu <- a + b * eulergamma\n sigma <- ( (pi / sqrt(6)) * b )\n z <- (x - mu)/sigma\n return (z)\n}\n\n#\n# pv_gumbel() - compute P-value for Z-score from Gumbel distribution\n#\n# Parameters: \n# z - Z-score from z_gumbel()\n#\n# Return value:\n# P-value for the Z-score\n#\npv_gumbel <- function(z)\n{\n return ( 1 - exp(-exp(-( (pi/sqrt(6)*z + eulergamma) ) ) ) )\n}\n\n#############################################################################3\n#\n# main\n#\n#############################################################################3\n\n\nfilename <- commandArgs(trailingOnly=TRUE)\n\n# EPS suitable for inserting into LaTeX\npostscript(sub('[.]slrtab$','_gumbel.eps',filename),\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\n\nslrtab <- read.table(filename, header=T)\nslrtab <- subset(slrtab, score >= 0) # one or two -ve scores sometimes\n\n#\n# Fit Gumbel distribution to same fold scores and different fold scores\n#\n\ngum0 <- gumbel(subset(slrtab, label == 0)$score)\ngum1 <- gumbel(subset(slrtab, label == 1)$score)\n\ncat('different folds: a = ', format(gum0$par.ests[2], digits=16), ' ' )\ncat('b = ', format(gum0$par.ests[1], digits=16), '\\n')\ncat('same fold: a = ', format(gum1$par.ests[2], digits=16), ' ' )\ncat('b = ', format(gum1$par.ests[1], digits=16), '\\n')\n\n#\n# Plot histograms and Gumbel distributions fitted to them\n#\n\nh0 <- hist(subset(slrtab, label == 0)$score, breaks=20, plot=F)\nh1 <- hist(subset(slrtab, label == 1)$score, breaks=20, plot=F)\nxh0 <- c(min(h0$breaks), h0$breaks)\nyh0 <- c(0, h0$density, 0)\nxh1 <- c(min(h1$breaks), h1$breaks)\nyh1 <- c(0, h1$density, 0)\n\nplot(xh0, yh0, type='s', lty=ltyvec[1], col=colorvec[1], xlab='score',ylab='frequency', ylim=c(0,1.0)) # ylim=c(0, max(yh0, yh1)) )\nlines(xh1, yh1, type='s', lty=ltyvec[2], col=colorvec[2])\n\ncurve(dgumbel(x, gum0$par.ests[2], gum0$par.ests[1]), col=colorvec[3], lty=ltyvec[3], add=T)\ncurve(dgumbel(x, gum1$par.ests[2], gum1$par.ests[1]), col=colorvec[4], lty=ltyvec[4], add=T)\n\nlegend(\"topright\", lty=ltyvec, col=colorvec, bty='n',\n legend=c(\"Different folds, histogram\",\n \"Same fold, histogram\",\n \"Different folds, fitted Gumbel distribution\",\n \"Same fold, fitted Gumbel distribution\") )\n \n\ndev.off()\n\n#\n# compute P-values for all scores\n#\n\npvslrtab <- slrtab\npvslrtab$pvalue <- pv_gumbel(z_gumbel(slrtab$score, gum0))\n\n#\n# compute coverage-vs-EPQ graph as used in Ortiz et al 2002 (and earlier\n# Levitt and Gerstein (1998) to compare the analytic and observed p-values)\n#\n\n# sort by ascending P-value so 'best' are at start of list\npvslrtab <- pvslrtab[sort.list(pvslrtab$pvalue),]\n\ntptotal <- length(subset(pvslrtab, label == 1)$label)\ntpcount <- 0\nfpcount <- 0\n\ncoverage_vec <- c()\nobs_pv_vec <- c()\nanalytic_pv_vec <- c()\n\nfor (i in 1:length(pvslrtab$label))\n{\n if (pvslrtab$label[i] == 0)\n {\n fpcount <- fpcount + 1\n }\n else\n {\n tpcount <- tpcount + 1\n }\n observed_pvalue <- fpcount / (length(pvslrtab$label) - tptotal)\n coverage <- tpcount / tptotal\n\n coverage_vec <- c(coverage_vec, coverage)\n obs_pv_vec <- c(obs_pv_vec, observed_pvalue)\n analytic_pv_vec <- c(analytic_pv_vec, pvslrtab$pvalue[i])\n\n #cat (sprintf(\"%d\\t%f\\t%f\\t%f\\n\", i, pvslrtab$pvalue[i], observed_pvalue, coverage) )\n\n if (observed_pvalue > 0.05)\n {\n break\n }\n}\n\n# EPS suitable for inserting into LaTeX\npostscript(sub('[.]slrtab$','_epq_gumbel.eps',filename),\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\n\nplot(analytic_pv_vec*100, coverage_vec*100, type='n', xlab='Errors per query (%)',\n ylab='Coverage (%)')\n\nlines(analytic_pv_vec*100, coverage_vec*100, col=colorvec[1], lty=ltyvec[1])\nlines(obs_pv_vec*100, coverage_vec*100, col=colorvec[2], lty=ltyvec[2])\n\nlegend('topleft', col=colorvec, lty=ltyvec, legend=c('Analytic','Observed'),\n bty='n')\n\ndev.off()\n\n\n", "meta": {"hexsha": "f9f13c09fc223f841c8c987a9cc2cfb879fcb0ed", "size": 6321, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/fitgumbeldist.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/fitgumbeldist.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/fitgumbeldist.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": 29.4, "max_line_length": 191, "alphanum_fraction": 0.6090808416, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6521126888914729}} {"text": "model_snowdepth <- function (Snowmelt = 0.0,\n Sdepth_t1 = 0.0,\n Snowaccu = 0.0,\n E = 0.0,\n rho = 100.0){\n #'- Name: SnowDepth -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: snow cover depth Calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: snow cover depth Calculation\n #'- inputs:\n #' * name: Snowmelt\n #' ** description : snow melt \n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : m\n #' ** uri : \n #' * name: Sdepth_t1\n #' ** description : snow cover depth Calculation in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : m\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: E\n #' ** description : snow compaction parameter\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mm/mm/d\n #' ** uri : \n #' * name: rho\n #' ** description : The density of the new snow fixed by the user\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 100\n #' ** min : \n #' ** max : \n #' ** unit : kg/m**3\n #' ** uri : \n #'- outputs:\n #' * name: Sdepth\n #' ** description : snow cover depth Calculation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : m\n #' ** uri : \n Sdepth <- 0.0\n if (Snowmelt <= Sdepth_t1 + (Snowaccu / rho))\n {\n Sdepth <- Snowaccu / rho + Sdepth_t1 - Snowmelt - (Sdepth_t1 * E)\n }\n return (list('Sdepth' = Sdepth))\n}", "meta": {"hexsha": "5d1a889acb2639b3c8965280d4bb9b3e76a88af7", "size": 3651, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Snowdepth.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/Snowdepth.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/Snowdepth.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": 46.2151898734, "max_line_length": 94, "alphanum_fraction": 0.301013421, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6520218084243631}} {"text": "get_expected = function(beta, N0, tau1, tau2) {\r\n \"\r\n Returns\r\n -------\r\n expected_NN : numeric vector\r\n Daily expected number of new infectious cases\r\n expected_N : numeric vector\r\n Daily expected number of infectious cases.\r\n \"\r\n daysUntilFirstSintoms=0\r\n daysUntilFirstSintoms=ceiling(1/tau1)-1\r\n beta=c(rep(beta[1],daysUntilFirstSintoms),beta)\r\n moments = length(beta)\r\n expected_NN = rep(0, moments)\r\n expected_N = rep(0, moments)\r\n expected_XN = rep(0, moments)\r\n expected_X = rep(0, moments)\r\n X_previous = N0\r\n N_previous = 0\r\n \r\n for(t in 1:moments){\r\n expected_N[t] = N_previous * pexp(1, rate=tau2, lower.tail=FALSE) + X_previous * pexp(1, rate=tau1, lower.tail=TRUE)\r\n expected_X[t] = N_previous * beta[t] + X_previous * pexp(1, rate=tau1, lower.tail=FALSE)\r\n expected_NN[t] = + X_previous * pexp(1, rate=tau1, lower.tail=TRUE)\r\n expected_XN[t] = N_previous * beta[t]\r\n N_previous = expected_N[t]\r\n X_previous = expected_X[t]\r\n }\r\n expected = list(\"NN\"=expected_NN[(daysUntilFirstSintoms+1):moments], \"N\"=expected_N[(daysUntilFirstSintoms+1):moments],\"XN\"=expected_XN[(daysUntilFirstSintoms+1):moments], \"X\"=expected_X[(daysUntilFirstSintoms+1):moments])\r\n return(expected)\r\n}\r\n", "meta": {"hexsha": "235418c294917d7805d333c846ea0667e2121123", "size": 1235, "ext": "r", "lang": "R", "max_stars_repo_path": "fit_confidence_intervals/f_get_expected.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "fit_confidence_intervals/f_get_expected.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "fit_confidence_intervals/f_get_expected.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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.59375, "max_line_length": 225, "alphanum_fraction": 0.6890688259, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6520217832843191}} {"text": "\n\n\n\n\n#' Compute pressure (in hPa) from elevation\n#' @param elev Vector of elevations\n#' @return Pressure for given elevations in hPa\n#' @export\npressureFromElevation <- function(elev) {\n\t# barometric eqn\n\tg <- 9.80665 # acceleration of gravity\n\tM <- 0.0289644 # molar mass of air\n\tLb <- -0.0065 # temperature lapse rate\n\tPb <- 101325 # static pressure\n\tTb <- 288.15 # standard temperature\n\tRs <- 8.31432 # gas constant\n\tpresPascals <- Pb * (Tb / (Tb + Lb * elev))^(g * M / (Rs * Lb))\n\tpresPascals / 100\n}\n\n#' Convert hPa to atmospheres\n#' @param P Vector of pressures (in hPa)\n#' @return Pressure in atm\n#' @export\nhPaToAtm <- function(P) {\n\tP * 9.86923266e-4\n}\n\n\n", "meta": {"hexsha": "5bd37fb2d313e8b9b7ab8a88b9cd2e867c789b5c", "size": 664, "ext": "r", "lang": "R", "max_stars_repo_path": "R/metabolism_functions.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/metabolism_functions.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/metabolism_functions.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": 21.4193548387, "max_line_length": 64, "alphanum_fraction": 0.6656626506, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6519894673767604}} {"text": "#' @title\n#' Reduced-rank regression with a given rank\n#'\n#' @description\n#' This function provides the reduced-rank regression estimator with a given rank.\n#'\n#' @usage\n#' RRR(Y, X, nrank = 1, weight = FALSE, Gamma = diag(ncol(Y)),\n#' ypy.svd = TRUE, c.svd = FALSE)\n#'\n#' @param Y response matrix.\n#' @param X design matrix.\n#' @param nrank a user-specified rank. Default is 1.\n#' @param weight a logical value. If TRUE, then the weighted criterion is employed.\n#' Default is FALSE.\n#' @param Gamma a weight matrix. Default is an identity matrix.\n#' @param ypy.svd a logical value. If TRUE (default), then the singular value decomposition\n#' method is used. If FALSE, then the eigenvalue decomposition method is used.\n#' @param c.svd a logical value. If TRUE, then output the singular value\n#' decomposition of the estimated coefficient\n#' matrix. Default is FALSE.\n#'\n#' @return The function returns a list:\n#' \\item{C}{the reduced-rank estimator.}\n#' \\item{C_ls}{the least square estimator.}\n#' \\item{rank}{the rank value.}\n#'\n#' @references\n#' Velu, R., & Reinsel, G. C. (2013). Multivariate reduced-rank regression:\n#' theory and applications (Vol. 136). Springer Science & Business Media.\n#' @importFrom MASS ginv\n#' @export\nRRR <- function(Y, X, nrank = 1, weight = FALSE, Gamma = diag(ncol(Y)),\n ypy.svd = TRUE, c.svd = FALSE){\n q <- ncol(Y)\n n <- nrow(Y)\n p <- ncol(X)\n S_yx <- t(Y) %*% X\n S_xx <- t(X) %*% X\n S_xx_inv <- tryCatch(MASS::ginv(S_xx), error = function(e) solve(S_xx +\n 0.1 * diag(p)))\n if (sum(is.na(S_xx_inv)) > 0) {\n S_xx_inv <- solve(S_xx + 0.1 * diag(p))\n }\n C_ls <- S_xx_inv %*% t(S_yx)\n if (weight == TRUE) {\n eigenGm <- eigen(Gamma)\n sqrtGm <- eigenGm$vectors %*% diag(sqrt(eigenGm$values)) %*%\n t(eigenGm$vectors)\n sqrtinvGm <- eigenGm$vectors %*% diag(sqrt(eigenGm$values^(-1))) %*%\n t(eigenGm$vectors)\n if (ypy.svd) {\n XC <- X %*% C_ls %*% sqrtGm\n svdXC <- tryCatch(svd(XC, nu = nrank, nv = nrank),\n error = function(e) 2)\n if (tryCatch(svdXC == 2, error = function(e) 3) ==\n 3) {\n A <- svdXC$v[, 1:nrank]\n Ad <- (svdXC$d[1:nrank])^2\n }\n else {\n ypy.svd <- FALSE\n }\n }\n if (!ypy.svd) {\n SS <- sqrtGm %*% S_yx %*% C_ls %*% sqrtGm\n SS <- (SS + t(SS))/2\n eigenSS <- eigen(SS, symmetric = TRUE)\n A <- as.matrix(eigenSS$vectors[, 1:nrank])\n Ad <- eigenSS$values[1:nrank]\n }\n AA <- A %*% t(A)\n C_rr <- C_ls %*% sqrtGm %*% AA %*% sqrtinvGm\n }\n else {\n if (ypy.svd) {\n XC <- X %*% C_ls\n svdXC <- tryCatch(svd(XC, nu = nrank, nv = nrank),\n error = function(e) 2)\n if (tryCatch(svdXC == 2, error = function(e) 3) ==\n 3) {\n A <- svdXC$v[, 1:nrank]\n Ad <- (svdXC$d[1:nrank])^2\n }\n else {\n ypy.svd <- FALSE\n }\n }\n if (!ypy.svd) {\n SS <- S_yx %*% C_ls\n SS <- (SS + t(SS))/2\n eigenSS <- eigen(SS, symmetric = TRUE)\n A <- as.matrix(eigenSS$vectors[, 1:nrank])\n Ad <- eigenSS$values[1:nrank]\n }\n AA <- A %*% t(A)\n C_rr <- C_ls %*% AA\n }\n if (c.svd) {\n svd_C <- svd(C_rr, nv = nrank, nu = nrank)\n U <- as.matrix(svd_C$u[, 1:nrank])\n V <- as.matrix(svd_C$v[, 1:nrank])\n D <- diag(svd_C$d[1:nrank], nrow = nrank)\n list(A = A, Ad = Ad, C_ls = C_ls, C_rr = C_rr, U = U,\n V = V, D = D, C = C_rr, rank = nrank)\n }\n else {\n list(A = A, Ad = Ad, C_ls = C_ls, C_rr = C_rr, C = C_rr,\n rank = nrank)\n }\n}\n", "meta": {"hexsha": "b85261a2a19dfe67bfbe8dfd62097fc12851ddda", "size": 3677, "ext": "r", "lang": "R", "max_stars_repo_path": "R/RRR.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/RRR.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/RRR.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": 32.8303571429, "max_line_length": 93, "alphanum_fraction": 0.534403046, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6519661268163192}} {"text": "#Author: Leyton Taylor\r\n\r\n##alphaN(t) = planar curve s.t. alphaN(t)=[x(t),y(t),-1]\r\n##Notation: calcIterate(alphaN(t))=[curvatureIAlphaN(t), torsionIAlphaN(t)] where IAlpha(t) = Image of alpha(t) when stereographically projected to\r\n##the unit sphere\r\n##betaMap(alpha(t))=projection map of alpha to unit sphere i.e. alphaI(t)\r\n##gammaMap(alpha(t))=osculating circle of alphaI(t)\r\n##dataSet=matrix(alphaN(t)=(x(t),y(t),z=-1), nrow=N, ncol=3)\r\n#dataSet= matrix(c(expression(1+.5*cos(t)),expression(1+.1*sin(t)),expression(-1)), nrow=1,ncol=3,byrow=TRUE)\r\n#dataSet= matrix(c(expression(-.5 + sin(t)*cos(t)),expression(-1 + sin(t)),expression(-1)), nrow=1,ncol=3,byrow=TRUE)\r\n#alphaN=dataSet[1,]\r\n#alphaNP= c(expression(D(alphaN[1],'t')), expression(D(alphaN[2],'t')),expression(0))\r\n#alphaNDP = c(expression(D(alphaNP[1],'t')), expression(D(alphaNP[2],'t')),expression(0))\r\n#alphaNPrimeVec = matrix(\r\n#+ c(),\r\n#+ nrow=3,\r\n#+ ncol=3\r\n#+ )\r\n# alphaNPrimeVec = matrix(\r\n# + c(alphaN,alphaNP,alphaNDP),\r\n# + nrow=3,\r\n# + ncol=3\r\n# + )\r\n\r\n\r\n# main <- function(dataSet){\r\n# tRange <- data.frame(t=seq(0,2*pi,.1))\r\n# nIterates=10\r\n# for(i in 0:nrow(dataSet)){\r\n# ##Output matrix of nIterate rows and 2 columns = corresponding to [curvature(Ialpha(t)),torsion(Ialpha(t))]\r\n# output=calcOrbit(c(dataSet[i,1],dataSet[i,2],dataSet[i,3]),nIterates,tRange)\r\n# print(output)\r\n# }\r\n# }\r\n\r\n\r\n##Output matrix of corresponding iterates of alphaN\r\n# calcOrbit <- function(alphaN,nIterates,tRange){\r\n# tRange<-seq_along(tRange)\r\n# orbitMatrix = matrix(c(),nrow = nIterates, ncol=3,dimnames = list(, c(\"x(t)\",\"y(t)\",\"z=-1\")))\r\n# outputOrbit = matrix(c(),nrow = length(tRange), ncol=3,dimnames = list(, c(\"x(t)\",\"y(t)\",\"z=-1\")))\r\n# rbind(orbitMatrix, calcIterate(alphaN))\r\n# orbitPlot <- matrix(c(),nrow=nI)\r\n# #k=order of orbit\r\n# for (k in 1:nIterates){\r\n# ktVectorFunction=calcIterate(orbitMatrix[c(k-1)])\r\n# #Binds each consecutive iterate to orbitMartix\r\n# rbind(orbitMatrix,ktVectorFunction)\r\n# for(t in tRange){\r\n# rbind(outputOrbit,c(ktVectorFunction[1](t),ktVectorFunction[2](t),-1))\r\n# }\r\n# \r\n# }\r\n# }\r\n\r\noptions(digits = 15)\r\n\r\n#parameter t and returns a parametric function that corresponds\r\n#to the projection of Curvature and Torsion for each t\r\ncalcIterate <- function(alphaN){\r\n return(projectionKT(alphaN, pi/8))\r\n}\r\n\r\n\r\n#Returns corresponding curvature(t) and torsion(t)\r\n#of the projected Parametric function passed to it\r\nprojectionKT <- function(alphaN,t){\r\n t=t\r\n #First deriveative of curve [k(t),T(t)]\r\n alphaNP <- c(D(alphaN[1],'t'), D(alphaN[2],'t'),0)\r\n #Second derivative of curve [k(t),T(t)]\r\n alphaNDP <- c(D(D(alphaN[1],'t'),'t'),D(D(alphaN[2],'t'),'t'),0)\r\n alphaNTP <- c(D(D(D(alphaN[1],'t'),'t'),'t'),D(D(D(alphaN[2],'t'),'t'),'t'),0)\r\n \r\n #vector containing ktVec,ktVecP, ktVecDP\r\n alphaNPrimeVec <-matrix(\r\n c(alphaN,alphaNP,alphaNDP,alphaNTP),\r\n nrow=4,\r\n ncol=3,\r\n byrow=TRUE\r\n )\r\n \r\n \r\n dimnames(alphaNPrimeVec)=list(c(\"alphaN\",\"alphaNP\",\"alphaNDP\",\"alphaNTP\"),c(\"X\",\"Y\",\"Z\"))\r\n print(\"alphaN\")\r\n print(alphaNPrimeVec[\"alphaN\",])\r\n print(\"AlphaNp\")\r\n print(alphaNPrimeVec[\"alphaNP\",])\r\n print(\"alphaNDP\")\r\n print(alphaNPrimeVec[\"alphaNDP\",])\r\n print(\"alphaNTP\")\r\n print(alphaNPrimeVec[\"alphaNTP\",])\r\n print(\"done\")\r\n return(c(ktCalculation(alphaNPrimeVec,t)))\r\n \r\n}\r\n\r\nktCalculation <- function(alphaNPrimeVec, t){\r\n \r\n A <- curvatureI(alphaNPrimeVec,t)\r\n curvature <- A$curvature\r\n torsion <- A$torsion\r\n \r\n return(c(curvature,torsion))\r\n \r\n}\r\n\r\narcLengthGamma <- function(gammaMatrix, Xo, Yo, kAlpha, t){\r\n gammaEnv <- new.env(hash=TRUE,size=4)\r\n assign(\"Xo\",value=Xo,envir=gammaEnv)\r\n assign(\"Yo\",value=Yo,envir=gammaEnv)\r\n assign(\"kAlpha\",value=kAlpha,envir=gammaEnv)\r\n t <- t\r\n Xo <- Xo\r\n Yo <- Yo\r\n kAlpha <- kAlpha\r\n xfunc <- function(u){eval(gammaMatrix[1,1], gammaEnv)}\r\n yfunc <- function(u){eval(gammaMatrix[1,2], gammaEnv)}\r\n zfunc <- function(u){eval(gammaMatrix[1,3], gammaEnv)}\r\n f <- function(u) c(xfunc(u),yfunc(u),zfunc(u))\r\n \r\n return(arclength(f, t, (t)+2*pi))\r\n \r\n \r\n}\r\n\r\narcLengthBeta <- function(betaMatrix, a, alphaNPrimeVec){\r\n betaEnv <- new.env(hash=TRUE,size=2)\r\n assign(\"X\",value<-deparse(alphaNPrimeVec[1,1]),envir=betaEnv)\r\n assign(\"Y\",value<-deparse(alphaNPrimeVec[1,2]),envir=betaEnv)\r\n b <- deparse(betaMatrix[1])\r\n print(\"tt\")\r\n print(alphaNPrimeVec)\r\n b1 <- substitute(b, list(X = deparse(alphaNPrimeVec[1,1])))\r\n print(eval(b1))\r\n t<-t\r\n xfunc <- function(t){substitute(betaMatrix[1], betaEnv)}\r\n yfunc <- function(t){substitute(betaMatrix[2], betaEnv)}\r\n zfunc <- function(t){substitute(betaMatrix[3], betaEnv)}\r\n f <- function(t) c(xfunc(t),yfunc(t),zfunc(t))\r\n\r\n return(arclength(f, 0, a))\r\n \r\n \r\n}\r\n\r\n#parameter ktVecDeriv=[alpha(t),alpha'(t),alpha''(t)]\r\n#Returns curvature of projected image of alpha on the unit sphere\r\n#at point t\r\ncurvatureI <- function(alphaNPrimeVec, t){\r\n print(alphaNPrimeVec)\r\n print(alphaNPrimeVec[1,1])\r\n print(alphaNPrimeVec[1,2])\r\n print(alphaNPrimeVec[2,1])\r\n print(alphaNPrimeVec[2,2])\r\n print(alphaNPrimeVec[3,1])\r\n print(alphaNPrimeVec[3,2])\r\n print(alphaNPrimeVec)\r\n betaEnv <- new.env(hash=TRUE,size=2)\r\n print(\"blah\")\r\n print(deparse(alphaNPrimeVec[1,1]))\r\n assign(\"X\",value<-deparse(alphaNPrimeVec[1,1]),envir=betaEnv)\r\n assign(\"Y\",value<-deparse(alphaNPrimeVec[1,2]),envir=betaEnv)\r\n \r\n alpha <-c(eval(alphaNPrimeVec[1,1]),eval(alphaNPrimeVec[1,2],-1))\r\n alphaP <- c(eval(alphaNPrimeVec[2,1]),eval(alphaNPrimeVec[2,2]),0)\r\n alphaDP <- c(eval(alphaNPrimeVec[3,1]),eval(alphaNPrimeVec[3,2]),0)\r\n betaMatrix <- betaAlpha()\r\n print(substitute(deparse(betaMatrix[2,1]), list(X=10)))\r\n print(\"beta\")\r\n \r\n substitute_q <- function(x, env) {\r\n call <- substitute(substitute(y, env), list(y = x))\r\n eval(call)\r\n }\r\n \r\n print(substitute_q(betaMatrix[2,1], betaEnv))\r\n arcLengthBet <- arcLengthBeta(betaMatrix[2,], 2*pi, alphaNPrimeVec)\r\n print(\"Arc Length Beta\")\r\n print(arcLengthBet)\r\n #X value corresponding to alpha(t)\r\n xAlpha= alpha[1]\r\n #Y value corresponding to alpha(t)\r\n yAlpha= alpha[2]\r\n\r\n #X value corresponding to alpha(t)\r\n xpAlpha= alphaP[1]\r\n #Y value corresponding to alpha(t)\r\n ypAlpha= alphaP[2]\r\n \r\n normX<-norm(as.matrix(alphaDP[1]),\"F\")\r\n normY<-norm(as.matrix(alphaDP[2]),\"F\")\r\n #Curvature of planar curve alpha(t)\r\n kAlpha<-curvaturePlaneCurve(alphaP,alphaDP,t)\r\n #Tprime x direction\r\n Tprime = c(-alphaP[2], alphaP[1])\r\n magTprime <- norm(as.matrix(Tprime),\"F\")\r\n TprimeUnit <- c(Tprime / magTprime)\r\n xyNot = c(TprimeUnit / kAlpha)\r\n Xo = xyNot[1]+xAlpha\r\n Yo = xyNot[2]+yAlpha\r\n\r\n #Returns matrix containing the projected osculating circle of alpha\r\n #at some t\r\n\r\n gammaMatrix <-gammaAlphaF()\r\n betaAlphaTP <- betaAlpha()\r\n print(\"Gamma Matrix\")\r\n print(gammaMatrix)\r\n\r\n \r\n print(kAlpha)\r\n \r\n print(\"XoYo\")\r\n print(alphaP[1])\r\n print(alphaP[2])\r\n print(Tprime)\r\n print(TprimeUnit)\r\n print(Xo)\r\n print(Yo)\r\n print(magTprime)\r\n\r\n \r\n print(\"t\")\r\n print(t)\r\n print(\"Arc Length\")\r\n arcLengthA = arcLengthGamma(gammaMatrix, Xo, Yo, kAlpha, t)\r\n arcLength = arcLengthA$length\r\n print(arcLength)\r\n \r\n #Environment\r\n gammaEnv1 <- new.env(hash=TRUE,size=4)\r\n assign(\"Xo\",value=Xo,envir=gammaEnv1)\r\n assign(\"Yo\",value=Yo,envir=gammaEnv1)\r\n assign(\"kAlpha\",value=kAlpha,envir=gammaEnv1)\r\n assign(\"u\",value=t,envir=gammaEnv1)\r\n\r\n gammaEnv2 <- new.env(hash=TRUE,size=4)\r\n assign(\"Xo\",value=Xo,envir=gammaEnv2)\r\n assign(\"Yo\",value=Yo,envir=gammaEnv2)\r\n assign(\"kAlpha\",value=kAlpha,envir=gammaEnv2)\r\n assign(\"u\",value=t+.01,envir=gammaEnv2)\r\n\r\n gammaEnv3 <- new.env(hash=TRUE,size=4)\r\n assign(\"Xo\",value=Xo,envir=gammaEnv3)\r\n assign(\"Yo\",value=Yo,envir=gammaEnv3)\r\n assign(\"kAlpha\",value=kAlpha,envir=gammaEnv3)\r\n assign(\"u\",value=t+.02,envir=gammaEnv3)\r\n\r\n #Environment\r\n betaEnv <- new.env(hash=TRUE,size=4)\r\n assign(\"X\",value=xAlpha,envir=betaEnv)\r\n assign(\"Y\",value=yAlpha,envir=betaEnv)\r\n assign(\"Xp\",value=xpAlpha,envir=betaEnv)\r\n assign(\"Yp\",value=ypAlpha,envir=betaEnv)\r\n\r\n #Projection point P on Alpha\r\n Pprime<- c(eval(gammaMatrix[1,1],gammaEnv1),eval(gammaMatrix[1,2],gammaEnv1),eval(gammaMatrix[1,3],gammaEnv1))\r\n #Arbitrary point on Gamma curve\r\n Aprime<- c(eval(gammaMatrix[1,1],gammaEnv2),eval(gammaMatrix[1,2],gammaEnv2),eval(gammaMatrix[1,3],gammaEnv2))\r\n #Arbitrary point on Gamma curve\r\n Bprime<- c(eval(gammaMatrix[1,1],gammaEnv3),eval(gammaMatrix[1,2],gammaEnv3),eval(gammaMatrix[1,3],gammaEnv3))\r\n\r\n betaPrimeN <-c(eval(betaAlphaTP[1,1],betaEnv),eval(betaAlphaTP[1,2],betaEnv),eval(betaAlphaTP[1,3],betaEnv))\r\n GammaPrimeA <-c(eval(gammaMatrix[2,1],gammaEnv2),eval(gammaMatrix[2,2],gammaEnv2),eval(gammaMatrix[2,3],gammaEnv2))\r\n GammaPrimeB <-c(eval(gammaMatrix[2,1],gammaEnv3),eval(gammaMatrix[2,2],gammaEnv1),eval(gammaMatrix[2,3],gammaEnv3))\r\n\r\n gammaPAlphaA <- c(GammaPrimeA * alphaP)\r\n gammaPAlphaB <- c(GammaPrimeB * alphaP)\r\n\r\n print(betaPrimeN)\r\n\r\n betaPrimeAlpha <- c(betaPrimeN * alphaP)\r\n\r\n\r\n ##P'-A'\r\n v1 <-c(Aprime-Pprime)\r\n ##P'-B'\r\n v2 <-c(Bprime-Pprime)\r\n\r\n v1Prime <-c(betaPrimeAlpha - gammaPAlphaA)\r\n v2Prime <- c(betaPrimeAlpha - gammaPAlphaB)\r\n\r\n normVec <- xprod(v1, v2)\r\n magNorm <- norm(as.matrix(normVec),\"F\")\r\n\r\n v1PCrossv2 <- xprod(v1Prime,v2)\r\n v2PCrossv1 <- xprod(v2Prime,v1)\r\n\r\n Nprime <- c(v1PCrossv2 + v2PCrossv1)\r\n\r\n pPrimeDn <- c(-Pprime * Nprime)\r\n #-P'*N'\r\n pPrimedotDn <- sum(pPrimeDn)\r\n\r\n nbetaPrime <- c(normVec * betaPrimeAlpha)\r\n #N*-P''\r\n ndotbetaPrime <- sum(nbetaPrime)\r\n #N*-P''+ -P'*N'\r\n const1 <- -pPrimedotDn + ndotbetaPrime\r\n #mag(N)*(N*-P''+ -P'*N')\r\n magNdotConst<- magNorm * const1\r\n #mag(N)*(N*-P''+ -P'*N')/mag(N)^2\r\n finalCons <- magNdotConst / (magNorm^2)\r\n\r\n #-P'*N/(magNorm)= p == signed distance from center of sphere to c\r\n p4 <- c(-Pprime*normVec)\r\n p4dotn <- sum(p4)\r\n p <- p4dotn / magNorm\r\n\r\n #sqrt(R^2-p^2)\r\n p7 <- p^2\r\n r1 = 1 - p7\r\n\r\n #r== 1/k(BetaAlpha(t))\r\n\r\n\r\n #Curvature of Image of Alpha at t\r\n kIAlpha= (2*pi)/arcLength\r\n r = 1/kIAlpha\r\n\r\n cI <- c(p * normVec)\r\n c <- c(cI/ magNorm)\r\n\r\n N <- c(c-Pprime)\r\n \r\n nNorm <- norm(as.matrix(N),\"F\")\r\n #.5/(sqrt(1-p^2))\r\n Rprimecons1 <- .5 / sqrt(1-p7)\r\n rPrime <- Rprimecons1 *(-2*p*(finalCons))\r\n \r\n\r\n #1-r(t)\r\n torsionI1 = 1-r\r\n torsionI2 =torsionI1/(rPrime^2)\r\n torsion <- -1*(1 / sqrt(torsionI2))\r\n\r\n print(\"R\")\r\n print(r)\r\n \r\n uN <- c(N / nNorm)\r\n B<- normVec / magNorm\r\n\r\n Tv <- xprod(uN,B)\r\n uT <- Tv\r\n print(\"BTN\")\r\n print(B)\r\n print(uT)\r\n print(uN)\r\n\r\n Tv<- Tv*-kIAlpha\r\n Ntp <- c(Nprime-Tv)\r\n\r\n return(list(\"curvature\"=kIAlpha,\"normVec\"=normVec,\"center\"= c,\"torsion\"=torsion))\r\n}\r\n\r\n# curvatureI <- function(alphaNPrimeVec, t){\r\n# print(alphaNPrimeVec)\r\n# print(alphaNPrimeVec[1,1])\r\n# print(alphaNPrimeVec[1,2])\r\n# print(alphaNPrimeVec[2,1])\r\n# print(alphaNPrimeVec[2,2])\r\n# print(alphaNPrimeVec[3,1])\r\n# print(alphaNPrimeVec[3,2])\r\n# print(alphaNPrimeVec)\r\n# alpha <-c(eval(alphaNPrimeVec[1,1]),eval(alphaNPrimeVec[1,2],-1))\r\n# alphaP <- c(eval(alphaNPrimeVec[2,1]),eval(alphaNPrimeVec[2,2]),0)\r\n# alphaDP <- c(eval(alphaNPrimeVec[3,1]),eval(alphaNPrimeVec[3,2]),0)\r\n# \r\n# #X value corresponding to alpha(t)\r\n# xAlpha= alpha[1]\r\n# #Y value corresponding to alpha(t)\r\n# yAlpha= alpha[2]\r\n# \r\n# #X value corresponding to alpha(t)\r\n# xpAlpha= alphaP[1]\r\n# #Y value corresponding to alpha(t)\r\n# ypAlpha= alphaP[2]\r\n# normX<-norm(as.matrix(alphaDP[1]),\"F\")\r\n# normY<-norm(as.matrix(alphaDP[2]),\"F\")\r\n# #Tprime x direction\r\n# Tprimex=alphaDP[1]\r\n# #Tprime y direction\r\n# Tprimey=alphaDP[2]/normY\r\n# \r\n# print(Tprimex)\r\n# print(Tprimey)\r\n# #Returns matrix containing the projected osculating circle of alpha\r\n# #at some t\r\n# \r\n# \r\n# gammaMatrix <-gammaAlphaF()\r\n# betaAlphaTP <- betaAlpha()\r\n# \r\n# print(gammaMatrix)\r\n# \r\n# #Curvature of planar curve alpha(t)\r\n# kAlpha<-curvaturePlaneCurve(alphaP,alphaDP,t)\r\n# print(kAlpha)\r\n# #(Xo,Yo)= center of osculating circle of alpha(t) at t\r\n# Xo<-xAlpha+(Tprimex/kAlpha)\r\n# Yo<-yAlpha+(Tprimey/kAlpha)\r\n# print(Xo)\r\n# print(Yo)\r\n# \r\n# arcLengthGamma <- function(gammaMatrix){\r\n# Xo <- Xo\r\n# Yo <- Yo\r\n# kAlpha <- kAlpha\r\n# xfunc <- function(u){eval(gammaMatrix[1,1])}\r\n# yfunc <- function(u){eval(gammaMatrix[1,2])}\r\n# zfunc <- function(u){eval(gammaMatrix[1,3])}\r\n# f <- function(u) c(xfunc(u),yfunc(u),zfunc(u))\r\n# \r\n# return(arclength(f, t, (t)+2*pi))\r\n# \r\n# \r\n# }\r\n# print(\"Arc Length\")\r\n# arcLengthA = arcLengthGamma(gammaMatrix)\r\n# arcLength = arcLengthA$length\r\n# \r\n# #Environment\r\n# gammaEnv1 <- new.env(hash=TRUE,size=4)\r\n# assign(\"Xo\",value=Xo,envir=gammaEnv1)\r\n# assign(\"Yo\",value=Yo,envir=gammaEnv1)\r\n# assign(\"kAlpha\",value=kAlpha,envir=gammaEnv1)\r\n# assign(\"u\",value=t,envir=gammaEnv1)\r\n# \r\n# gammaEnv2 <- new.env(hash=TRUE,size=4)\r\n# assign(\"Xo\",value=Xo,envir=gammaEnv2)\r\n# assign(\"Yo\",value=Yo,envir=gammaEnv2)\r\n# assign(\"kAlpha\",value=kAlpha,envir=gammaEnv2)\r\n# assign(\"u\",value=t+.01,envir=gammaEnv2)\r\n# \r\n# gammaEnv3 <- new.env(hash=TRUE,size=4)\r\n# assign(\"Xo\",value=Xo,envir=gammaEnv3)\r\n# assign(\"Yo\",value=Yo,envir=gammaEnv3)\r\n# assign(\"kAlpha\",value=kAlpha,envir=gammaEnv3)\r\n# assign(\"u\",value=t+.02,envir=gammaEnv3)\r\n# \r\n# #Environment\r\n# betaEnv <- new.env(hash=TRUE,size=4)\r\n# assign(\"X\",value=xAlpha,envir=betaEnv)\r\n# assign(\"Y\",value=yAlpha,envir=betaEnv)\r\n# assign(\"Xp\",value=xpAlpha,envir=betaEnv)\r\n# assign(\"Yp\",value=ypAlpha,envir=betaEnv)\r\n# \r\n# \r\n# Pprime<- c(eval(gammaMatrix[1,1],gammaEnv1),eval(gammaMatrix[1,2],gammaEnv1),eval(gammaMatrix[1,3],gammaEnv1))\r\n# Aprime<- c(eval(gammaMatrix[1,1],gammaEnv2),eval(gammaMatrix[1,2],gammaEnv2),eval(gammaMatrix[1,3],gammaEnv2))\r\n# Bprime<- c(eval(gammaMatrix[1,1],gammaEnv3),eval(gammaMatrix[1,2],gammaEnv3),eval(gammaMatrix[1,3],gammaEnv3))\r\n# \r\n# \r\n# betaPrimeN <-c(eval(betaAlphaTP[1,1],betaEnv),eval(betaAlphaTP[1,2],betaEnv),eval(betaAlphaTP[1,3],betaEnv))\r\n# GammaPrimeA <-c(eval(gammaMatrix[2,1],gammaEnv2),eval(gammaMatrix[2,2],gammaEnv2),eval(gammaMatrix[2,3],gammaEnv2))\r\n# GammaPrimeB <-c(eval(gammaMatrix[2,1],gammaEnv3),eval(gammaMatrix[2,2],gammaEnv1),eval(gammaMatrix[2,3],gammaEnv3))\r\n# \r\n# \r\n# \r\n# gammaPAlphaA <- c(GammaPrimeA * alphaP)\r\n# gammaPAlphaB <- c(GammaPrimeB * alphaP)\r\n# \r\n# \r\n# \r\n# print(betaPrimeN)\r\n# betaPrimeAlpha <- c(betaPrimeN * alphaP)\r\n# \r\n# ##n\r\n# \r\n# \r\n# \r\n# ##P'-A'\r\n# v1 <-c(Aprime-Pprime)\r\n# ##P'-B'\r\n# v2 <-c(Bprime-Pprime)\r\n# \r\n# v1Prime <-c(betaPrimeAlpha - gammaPAlphaA)\r\n# v2Prime <- c(betaPrimeAlpha - gammaPAlphaB)\r\n# \r\n# normVec <- xprod(v1,v2)\r\n# \r\n# magNorm <- norm(as.matrix(normVec),\"F\")\r\n# \r\n# v1PCrossv2 <- xprod(v1Prime,v2)\r\n# v2PCrossv1 <- xprod(v2Prime,v1)\r\n# \r\n# Nprime <- c(v1PCrossv2 + v2PCrossv1)\r\n# \r\n# pPrimeDn <- c(-Pprime * Nprime)\r\n# pPrimedotDn <- sum(pPrimeDn)\r\n# \r\n# nbetaPrime <- c(normVec * betaPrimeAlpha)\r\n# ndotbetaPrime <- sum(nbetaPrime)\r\n# \r\n# const1 <- -pPrimedotDn + ndotbetaPrime\r\n# magNdotConst<- magNorm * const1\r\n# finalCons <- magNdotConst / (magNorm^2)\r\n# \r\n# \r\n# p4 <- c(-Pprime*normVec)\r\n# p4dotn <- sum(p4)\r\n# p <- p4dotn / magNorm\r\n# \r\n# cI <- c(p * normVec)\r\n# c <- c(cI/ magNorm)\r\n# \r\n# p7 <- p^2\r\n# \r\n# Rprimecons1 <- .5 * sqrt(1-p7)\r\n# Rprimecons2 <- Rprimecons1 *(-2*p*(finalCons))\r\n# \r\n# rPrime = Rprimecons1*Rprimecons2\r\n# #Curvature of Image of Alpha at t\r\n# kIAlpha= (2*pi)/arcLength\r\n# r = 1/kIAlpha\r\n# print(\"R\")\r\n# print(r)\r\n# print(kIAlpha)\r\n# N <- c(-Pprime-c)\r\n# uN <- c(N / r)\r\n# B<- normVec / magNorm\r\n# \r\n# Tv <- xprod(uN,B)\r\n# uT <- Tv\r\n# print(\"BTN\")\r\n# print(B)\r\n# print(uT)\r\n# print(uN)\r\n# \r\n# \r\n# \r\n# \r\n# Tv<- Tv*-kIAlpha\r\n# Ntp <- c(Nprime-Tv)\r\n# \r\n# torsionI1 = 1-r\r\n# torsionI2 =torsionI1/(rPrime^2)\r\n# torsion <- -1*(1 / sqrt(torsionI2))\r\n# \r\n# return(list(\"curvature\"=kIAlpha,\"normVec\"=normVec,\"center\"= c,\"torsion\"=torsion))\r\n# }\r\n\r\nfunins <- function(f, expr = expression(x<-2*x), after=1) {\r\n body(f)<-as.call(append(as.list(body(f)), expr, after=after))\r\n f\r\n}\r\n\r\n##Beta mapping represents the stereographic projection of alpha onto the\r\n##Unit sphere\r\nbetaAlpha <- function(){\r\n betaAlpha <- c(expression((4*X)/(X^2+Y^2+4)),\r\n expression((4*Y)/(X^2+Y^2+4)),\r\n expression((X^2+Y^2-4)/(X^2+Y^2+4)))\r\n \r\n betaAlphaP<- c(expression((((X^2+Y^2+4)*(Xp))-((4*X)*((2*X)*Xp+(2*Y)*Yp)))/(X^2+Y^2+4)^2),\r\n expression((((X^2+Y^2+4)*(Yp))-((4*Y)*((2*X)*Xp+(2*Y)*Yp)))/(X^2+Y^2+4)^2),\r\n expression(((X^2+Y^2+4)*((2*X)*Xp +(2*Y)*Yp)-((X^2+Y^2+4)*((2*X)*Xp +(2*Y)*Yp)))/(X^2+Y^2+4)^2))\r\n \r\n betaAlphMat = matrix(\r\n c(betaAlphaP,betaAlpha),\r\n nrow=2,\r\n ncol=3,\r\n byrow = TRUE\r\n )\r\n \r\n \r\n print(\"sup\")\r\n print(betaAlphMat)\r\n return(betaAlphMat)\r\n \r\n} \r\n\r\n\r\n##Parametric function defining osculating circle of a curve alpha(t)\r\n##at some t. ==> radius of osculatingAlpha= (1/kAlpha)\r\n##further we know [x_0,y_0]=[x(t),y(t)]+[T'_alpha(t)/kAlpha)]\r\n##0<=u<=2pi with will be the parameter of the osculating circle\r\n##uRange=data.frame(u=seq(0,2*pi,.1))\r\n\r\n#(x,y) represent values of osculating circle of some curve alphaN(t) at\r\n#some value t. gammaAlpha(t) gives the corresponding (x,y,z)\r\n#values of the osculating circle of the image of alphaN(t) or alphaNI(t)\r\n#at the same value t. Note x,y are depent on alphaN(t)\r\n#that is\r\n# if alphaN(t) = x(t),y(t)==> x=x(t)+((T'alpha(t)_x)/k(t))+(1/k(t))cos(u))\r\n## essentially x and y are functions of 0<=u<=2pi at each t on the curve ##alphaN\r\n\r\n##For simplicity sake know that ##(x,y)=gamma(u,v=1)=[(1)*(x_0+rcos(u)),(1)*(y_0+rsin(u)),1-2*(1)]\r\n##This mapping creates a surface of a cone. The projection mapping\r\n##gammAlpha gives us the intersection of the cone and the unit sphere.\r\n##this intersection happens at v=4/(x)^2+(y)^2+4\r\n\r\ngammaAlphaF <- function(){\r\n \r\n #Vector of expressions corresponding to the gamma mapping applied to alpha\r\n gammaAlpha <- c(expression((4*(Xo+(1/kAlpha)*cos(u)))/((Xo+(1/kAlpha)*cos(u))^2+(Yo+(1/kAlpha)*sin(u))^2+4)),\r\n expression((4*(Yo+(1/kAlpha)*sin(u)))/((Xo+(1/kAlpha)*cos(u))^2+(Yo+(1/kAlpha)*sin(u))^2+4)),\r\n expression(1+(-8/((Xo+(1/kAlpha)*cos(u))^2+(Yo+(1/kAlpha)*sin(u))^2+4))))\r\n \r\n \r\n gammaAlphaP <- c(DD(gammaAlpha[1], 'u',1),DD(gammaAlpha[2], 'u',1),DD(gammaAlpha[3], 'u',1))\r\n \r\n #gammaMatrix of expressions by row\r\n gammaMatrix = matrix(\r\n c(gammaAlpha,gammaAlphaP),\r\n nrow=2,\r\n ncol=3,\r\n byrow=TRUE,\r\n )\r\n \r\n dimnames(gammaMatrix)=list(c(\"GammaAlpha: \",\"GammaAlphaDP\"),c(\"X_gamma\",\"Y_gamma\",\"Z_gamma\"))\r\n \r\n \r\n return(gammaMatrix)\r\n \r\n}\r\n\r\n\r\n#parameter ktVecDeriv=[alpha(t),alpha'(t),alpha''(t)]\r\n#returns ||alpha'(t) x alpha''(t) ||/ ||(alpha'(t))^3||==K_alpha(t)\r\ncurvaturePlaneCurve <- function(alphaP,alphaDP,t){\r\n normCross <-xprod(alphaP,alphaDP)\r\n normAD <-norm(as.matrix(normCross),\"F\")\r\n normAP <-norm(as.matrix(alphaP),\"F\")\r\n kAlpha = normAD /(normAP^3)\r\n print(kAlpha)\r\n return(kAlpha)\r\n \r\n}\r\n\r\n# torsionI <- function(alphaNPrimeVec,t,normVec){\r\n# \r\n# alpha <-c(eval(alphaNPrimeVec[1,1]),eval(alphaNPrimeVec[1,2],-1))\r\n# alphaP <- c(eval(alphaNPrimeVec[2,1]),eval(alphaNPrimeVec[2,2]),0)\r\n# alphaDP <- c(eval(alphaNPrimeVec[3,1]),eval(alphaNPrimeVec[3,2]),0)\r\n# betaAlphMat = betaAlpha(alphaNPrimeVec,t)\r\n# \r\n# print(betaAlphaTP)\r\n# \r\n# print(normVec)\r\n# print(\"norm\")\r\n# num <-c(normVec)\r\n# \r\n# dotNum <- sum(num)\r\n# denom <- norm(as.matrix(normVec),\"F\")\r\n# torsionI <- dotNum/(denom^2)\r\n# print(denom^2)\r\n# print(dotNum)\r\n# \r\n# \r\n# return(torsionI)\r\n# \r\n# }\r\n\r\n##DD for calculation of high order derivatives\r\nDD <- function(expr, name, order=1) {\r\n if(order < 1) stop(\"'order' must be >= 1\")\r\n if(order == 1) \r\n return(D(expr, name))\r\n else DD(D(expr, name), name, order - 1)}\r\n\r\nxprod <- function(...) {\r\n args <- list(...)\r\n \r\n # Check for valid arguments\r\n \r\n if (length(args) == 0) {\r\n stop(\"No data supplied\")\r\n }\r\n len <- unique(sapply(args, FUN=length))\r\n if (length(len) > 1) {\r\n stop(\"All vectors must be the same length\")\r\n }\r\n if (len != length(args) + 1) {\r\n stop(\"Must supply N-1 vectors of length N\")\r\n }\r\n \r\n # Compute generalized cross product by taking the determinant of sub-matricies\r\n \r\n m <- do.call(rbind, args)\r\n sapply(seq(len),\r\n FUN=function(i) {\r\n det(m[,-i,drop=FALSE]) * (-1)^(i+1)\r\n })\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ac28fb0fbfb00f7af94794cddb0ee7b0d41bec12", "size": 20770, "ext": "r", "lang": "R", "max_stars_repo_path": "Main.r", "max_stars_repo_name": "LeytonTaylor/DynamicalSys", "max_stars_repo_head_hexsha": "b775b7dbc8aeab3c3d048acf5e650ca322219963", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-26T10:47:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T10:47:10.000Z", "max_issues_repo_path": "Main.r", "max_issues_repo_name": "LeytonTaylor/DynamicalSys", "max_issues_repo_head_hexsha": "b775b7dbc8aeab3c3d048acf5e650ca322219963", "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": "Main.r", "max_forks_repo_name": "LeytonTaylor/DynamicalSys", "max_forks_repo_head_hexsha": "b775b7dbc8aeab3c3d048acf5e650ca322219963", "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.1014492754, "max_line_length": 148, "alphanum_fraction": 0.6216658642, "num_tokens": 7227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.65194646449229}} {"text": "huen <- function(steps,final)\n{\n\t# RungeKutta Approximation and Heun's Method\n\tr <- -5;\n\ta <- 1/2;\n\tb <- 1/2;\n\talpha <- 1;\n\tbeta <- 1;\n\t\n\t#final <- 25;\n\t#steps <- 1000;\n\tdt <- final/steps;\n\t\n\tn <- 0;\n\ty <- 1;\n\t#i <- double(steps);\n\t#j <- double(steps);\n\t\n\t\n\twhile(n < steps) {\n\t k1 <- dt*r*y;\n\t k2 <- dt*r*(y + beta*k1);\n\t y <- y + a*k1 + b*k2;\n\t #i[n+1] <- dt*(n+1);\n\t #j[n+1] <- abs(y - exp(r*dt*(n + 1)));\n\t n <- n + 1;\n\t}\n\t\n\t#plot( \n # i, \n # j,\n # type = 'l',\n # xlim = c(0,25),\n # ylim = c(0,5),\n # # log = 'xy',\n # ylab = 'Error', \n # xlab = 'Time', \n # main = 'r = -5 and dt = ')\n\n\t\n\treturn(y)\n}\n\n\nx <- data.frame(,i,j);\n\nfile.create(\"/Users/kylemcgrath/Documents/SDE-REU-2015/SUNY-SDE-2015/REU15/Runge-Kutta/R/error-dat.csv\");\ndata <- file(\"/Users/kylemcgrath/Documents/SDE-REU-2015/SUNY-SDE-2015/REU15/Runge-Kutta/R/error-dat.csv\");\nwrite.table(c(\"dt\", \"step\", \"error\"), file = data, row.names=FALSE, col.names=FALSE);\nwrite.table(x, file = data, row.names=FALSE, col.names=FALSE);", "meta": {"hexsha": "fca44361a74e0f007553f7a62379921df560d9c8", "size": 1091, "ext": "r", "lang": "R", "max_stars_repo_path": "simulations/Runge-Kutta/R/RK.r", "max_stars_repo_name": "SUNY-SDE-2015/REU15", "max_stars_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "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": "simulations/Runge-Kutta/R/RK.r", "max_issues_repo_name": "SUNY-SDE-2015/REU15", "max_issues_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-06-04T17:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-09T15:38:17.000Z", "max_forks_repo_path": "simulations/Runge-Kutta/R/RK.r", "max_forks_repo_name": "SUNY-SDE-2015/REU15", "max_forks_repo_head_hexsha": "a54ace642d8696250c7fa0bf574b16a931ec91c9", "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": 21.82, "max_line_length": 106, "alphanum_fraction": 0.4940421632, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6519434102298453}} {"text": "#keep track of all movements\nmov<-c()\n\n#VACCINATION STRATEGY\nstrategy<-c('mobility','mortality')\n\n#INITIAL AMOUNT OF PEOPLE IN EACH SUBGROUP\n\n#age group 0-20\nI_1<- 26\nS_1<- 44403 - I_1\n#age group 21-40\nI_2<- 179\nS_2<- 40992 - I_2\n#age group 41-60\nI_3<- 148\nS_3<- 29839 - I_3\n#age group 60+\nI_4<- 56\nS_4<- 15029 - I_4\n\n#Put them in vectors for easier access\nS<-c(S_1, S_2, S_3, S_4)\nI<-c(I_1, I_2, I_3, I_4)\n\n#total dead\nD<- 0\n#total recuperated\nR<- 4018\n\n#average daily vaccination capacity (consider efficacy)\nV<- 10\n\n#SUBGROUP parameters\n\n#death rate\nk<-c(0.01,0.02,0.09,0.13)\n#recuperation rate\nb<-(1-k)\n#mobility\na<-c(2.25,3,2.75,2)\n\n#vaccines per group per day, set to 0 initially\nlambda<-c(0,0,0,0)\n\n#population in a vector\npop<-as.vector(c(rbind(S,I),D,R))\nnames(pop)<-c('S1','I1','S2','I2','S3','I3','S4','I4','D','R')\n\n#this way we can simply add the vector of the event to our pop counter\nposs<-data.frame(inf1=c(-1,1,rep(0,8)),\n inf2=c(0,0,-1,1,rep(0,6)),\n inf3=c(rep(0,4),-1,1,rep(0,4)),\n inf4=c(rep(0,6),-1,1,0,0),\n die1=c(0,-1,rep(0,6),1,0),\n die2=c(rep(0,3),-1,rep(0,4),1,0),\n die3=c(rep(0,5),-1,0,0,1,0),\n die4=c(rep(0,7),-1,1,0),\n rec1=c(0,-1,rep(0,7),1),\n rec2=c(rep(0,3),-1,rep(0,5),1),\n rec3=c(rep(0,5),-1,rep(0,3),1),\n rec4=c(rep(0,7),-1,0,1),\n vac1=c(-1,rep(0,8),1),\n vac2=c(0,0,-1,rep(0,6),1),\n vac3=c(rep(0,4),-1,rep(0,4),1),\n vac4=c(rep(0,6),-1,0,0,1))\n\n#put subgroup parameters into a data frame too, for easier handling\nparams<-data.frame(a, b, k, lambda)\n\n#we will call this function every time we iterate inside the simulation\nget_times<-function(pop,params){\n times<-c(rep(0,16))\n #population\n N<-sum(pop)\n #all infected\n infected<-sum(pop[c(2,4,6,8)])\n #iterate over each group\n for (i in 1:4){\n #infection\n times[i]<-rexp(n=1,rate=(0.06)*params$a[i]*pop[(2*i-1)]*infected/N)\n #death\n times[i+4]<-rexp(n=1,rate=params$k[i]*pop[(2*i)]*(1/17))\n #vaccination\n times[i+12]<-rexp(n=1,rate=params$lambda[i]*pop[2*i-1]/pop[2*i-1])\n #recuperation\n times[i+8]<-rexp(n=1,rate=params$b[i]*pop[(2*i)]*(1/14))\n }\n return(times)\n}\n\nget_lambda <- function(V, N, P){\n #distribute and normalize\n lambda<-c(0,0,0,0)\n lambda [ which(P*N==max(P*N))] <- V\n return(lambda)\n}\n\n\nset_lambda<-function(S, params, strategy, V){\n #id parameter of interest from strategy\n if (strategy=='mobility'){\n interest<-params$a\n }else if(strategy=='mortality'){\n interest<-params$k\n }\n #get lambda values according to priority parameter\n lambda<-get_lambda(P=interest,V=V,N=S)\n #return new lambda vector\n return(lambda)\n}\n\n#MAIN SIMULATION ITERATORS\n#We will fluctuate between strategies with different probability values (limit)\n#Each probability combination will be run e simulations\n#each simulation will run until herd immunity is achieved or no active cases remain\n#At the end of each simulation, a report will be printed\n\n\n#report titles\nprint(c('mobility','pandemic_time','death_toll','vaccines','total_cases'))\n\n#number of iterations on strategy probability\nlimit<-5\n#number of repetitions on with each strategy parameters\nreps<-10\n#amount of rec people needed for pandemic to end\nherd_immunity<-sum(pop[c(1:8,10)])*0.7\n\n#we will run the simulations with a range of probabilities\nfor (j in 0:limit){\n #new probability parameters for iteration\n strategyR<-c(j/limit,1-j/limit)\n \n #repetitions per value\n for (e in 1:reps){\n \n #time accumulator \n t<-0\n \n #run simulation\n while( sum(pop[c(2,4,6,8,10)]) < herd_immunity ){\n \n #select strategy according to probabilities\n strat<-sample(strategy, size=1, prob=strategyR)\n #update lambda values according to strategy\n params$lambda<-set_lambda(S=pop[c(1,3,5,7)],params=params,strategy=strat, V=V)\n #obtain times\n times<-get_times(pop,params)\n #identify next event\n chosen<-which(times==min(times[which(times>0)]))[1]\n #execute next event\n pop<-pop+(poss[,chosen])\n #accumulate time\n t<-t+times[chosen]\n #update amount of susceptible people needed for pandemic to end\n herd_immunity<-sum(pop[c(1:8,10)])*0.7\n #register event\n mov<-append(mov,chosen)\n \n }#end of simulation\n \n #save important output info for analysis\n tot_vacc<-sum(mov>=13)\n tot_cases<-sum(mov<=4)\n output<-c(strategyR[1],t,pop[[9]],tot_vacc,tot_cases)\n \n #print and save output\n print(output)\n \n #reset population values for new simulation repetitions\n pop<-as.vector(c(rbind(S,I),D,R))\n mov<-c()\n \n }#end of value repetitions\n \n}#end of whole enchilada\n\nprint('DONE')\n\n\n\n\n", "meta": {"hexsha": "f9ce5cac50e443a656803bfe2b64db644a03cd9b", "size": 4833, "ext": "r", "lang": "R", "max_stars_repo_path": "vaccination_strategy_SIR.r", "max_stars_repo_name": "lau-lhg/SIR_markov_R", "max_stars_repo_head_hexsha": "0cc1eaf85e0df866636b833694336180efa7ed4e", "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": "vaccination_strategy_SIR.r", "max_issues_repo_name": "lau-lhg/SIR_markov_R", "max_issues_repo_head_hexsha": "0cc1eaf85e0df866636b833694336180efa7ed4e", "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": "vaccination_strategy_SIR.r", "max_forks_repo_name": "lau-lhg/SIR_markov_R", "max_forks_repo_head_hexsha": "0cc1eaf85e0df866636b833694336180efa7ed4e", "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.2663043478, "max_line_length": 84, "alphanum_fraction": 0.6248706807, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190226, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6517872833871804}} {"text": "## this is an ugly script -- not meant to be \"source'd\"\ngDat <- read.delim(\"data/gapminderDataFiveYear.txt\")\nstr(gDat)\n\n## function that returns estimated intercept and slope from linear regression of\n## lifeExp on year\n## anticipated input: Gapminder data for one country\n## see block03 script for development of this\njFun <- function(z) {\n jCoef <- coef(lm(lifeExp ~ I(year - yearMin), z))\n names(jCoef) <- c(\"intercept\", \"slope\")\n return(jCoef)\n}\n\n## get intercept and slope for each country\nlibrary(plyr)\nyearMin <- min(gDat$year)\ngCoef <- ddply(gDat, .(country, continent), jFun)\nstr(gCoef)\ntail(gCoef)\n\n## reordering the continent factor rationally (vs. alphabetically)\nlibrary(lattice)\nbwplot(slope ~ continent, gCoef)\n## alphabetical order is rarely justified\n\ngCoef$continent <- reorder(gCoef$continent, gCoef$slope)\nstr(gCoef)\nbwplot(slope ~ continent, gCoef)\nlevels(gCoef$continent)\n## much more logical\n## tables and plots sorted this way will give more insight!\n\n## drop Oceania ... too few countries\ngCoef <- subset(gCoef, continent != \"Oceania\")\nlevels(gCoef$continent)\n## Oceania is still there as factor level?!?\nsubset(gCoef, continent == \"Oceania\")\n## but no observation have continent Oceania!\ngCoef <- droplevels(gCoef)\n## gets rid of unused factor levels\nlevels(gCoef$continent)\n\n## how to store data.frames for posterity\n\n## plain text is always good!\n## we slowly built up the arguments below\n## you may not want all of these?\nwrite.table(gCoef, \"results/gCoef.txt\", quote = FALSE, row.names = FALSE, sep = \"\\t\")\n\n## bad news about plain text storage:\n## upon re-import via read.table, factors levels revert to alphabetical order\nlevels(gCoef$continent) # rational level order\nrm(gCoef)\ngCoef <- read.delim(\"results/gCoef.txt\")\nlevels(gCoef$continent) # back to alphabetical!!\n\n## let's re-reorder the continent factor levels\ngCoef$continent <- reorder(gCoef$continent, gCoef$slope)\nbwplot(slope ~ continent, gCoef)\nlevels(gCoef$continent)\n\n## how to store a data.frame in a plain text file WITH factor level order being\n## preserved?\ndput(gCoef, \"results/gCoef_DPUT.txt\")\nrm(gCoef)\ngCoef <- dget(\"results/gCoef_DPUT.txt\")\nlevels(gCoef$continent)\n## success!\n## but the file written by dput() is not easy to browse or open\n## in Excel or anywhere outside of R, for that matter\n\n## if we abandon plain text, there is an R-specific binary format\nsaveRDS(gCoef, \"results/gCoef.rds\")\nrm(gCoef)\ngCoef <- readRDS(\"results/gCoef.rds\")\nlevels(gCoef$continent)\n## success!\n\n## bottom line:\n## I usually save as plain text AND via (dput|saveRDS|save)\n## plain text is for long-term, language-agnostic storage\n## *.rds is for my short-/medium-term reuse with R\n", "meta": {"hexsha": "c8d235fbbacd5eb6ab4e211264f9f2b972fb7971", "size": 2677, "ext": "r", "lang": "R", "max_stars_repo_path": "intermediate/r/Miami-SFU/session08_pipeline.r", "max_stars_repo_name": "BernhardKonrad/2014-02-22-SFU", "max_stars_repo_head_hexsha": "25cfac5f703943ddaa98cc30bb267eacba48d07f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-15T17:57:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-15T17:57:12.000Z", "max_issues_repo_path": "intermediate/r/Miami-SFU/session08_pipeline.r", "max_issues_repo_name": "BernhardKonrad/2014-02-22-SFU", "max_issues_repo_head_hexsha": "25cfac5f703943ddaa98cc30bb267eacba48d07f", "max_issues_repo_licenses": ["CC-BY-3.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": "intermediate/r/Miami-SFU/session08_pipeline.r", "max_forks_repo_name": "BernhardKonrad/2014-02-22-SFU", "max_forks_repo_head_hexsha": "25cfac5f703943ddaa98cc30bb267eacba48d07f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.869047619, "max_line_length": 85, "alphanum_fraction": 0.7385132611, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.6517872751925317}} {"text": "##\n## Calculate Jaccard similarities between the advice, help, sharing and gift networks\n##\nsource(\"init if necessary.r\")\n\nlibrary(igraph)\nlibrary(proxy)\n\nflog.info(\"Started social network analysis - similarities\")\n\n# make adjacency matrices from graphs of each type of net-map\nadj.advice = get.adjacency( graph.data.frame( net.maps.advice, vertices=herders, directed=T), sparse=F )\nadj.help = get.adjacency( graph.data.frame( net.maps.help, vertices=herders, directed=T), sparse=F )\nadj.sharing = get.adjacency( graph.data.frame( net.maps.sharing, vertices=herders, directed=T), sparse=F )\nadj.gifts = get.adjacency( graph.data.frame( gifts, vertices=herders, directed=T), sparse=F )\n\n# shorthand function to calculate Jaccard similarity between adjacency matrices a and b\njaccard = function(a, b) proxy::simil(list(as.vector(a), as.vector(b)), method=\"jaccard\")\n\njacs = matrix(NA, nrow=4, ncol=4, dimnames=list(c(\"Advice\", \"Help\", \"Sharing\", \"Gifts\"), c(\"Advice\", \"Help\", \"Sharing\", \"Gifts\")))\n\n# calculate similarities\njacs[\"Advice\", \"Help\"] = jaccard(adj.advice, adj.help)\njacs[\"Advice\", \"Sharing\"] = jaccard(adj.advice, adj.sharing)\njacs[\"Advice\", \"Gifts\"] = jaccard(adj.advice, adj.gifts)\n\njacs[\"Help\", \"Sharing\"] = jaccard(adj.help, adj.sharing)\njacs[\"Help\", \"Gifts\"] = jaccard(adj.help, adj.gifts)\n\njacs[\"Sharing\", \"Gifts\"] = jaccard(adj.sharing, adj.gifts)\n\n# save table\nwrite.csv(round(jacs, 3), file.path(results.dir, \"Network similarities.csv\"), row.names=T)\n\nflog.info(\"Finished society network analysis - similarities\")\n", "meta": {"hexsha": "46e98f14e47b4c73265b0906c5a1078f0af40c3f", "size": 1562, "ext": "r", "lang": "R", "max_stars_repo_path": "social network analysis - similarity.r", "max_stars_repo_name": "matthewgthomas/saami-norms", "max_stars_repo_head_hexsha": "2f58ab39e79f5f43501095c7b5a280cc08e23145", "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": "social network analysis - similarity.r", "max_issues_repo_name": "matthewgthomas/saami-norms", "max_issues_repo_head_hexsha": "2f58ab39e79f5f43501095c7b5a280cc08e23145", "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": "social network analysis - similarity.r", "max_forks_repo_name": "matthewgthomas/saami-norms", "max_forks_repo_head_hexsha": "2f58ab39e79f5f43501095c7b5a280cc08e23145", "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": 43.3888888889, "max_line_length": 130, "alphanum_fraction": 0.71446863, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6517463717461457}} {"text": "# Example : 1 Chapter : 5.2 Page No: 255\r\n# Determinant of matrices by multiplying pivots\r\nA<-matrix(c(0,0,4,0,2,5,1,3,6),ncol=3)\r\nP<-matrix(c(0,0,1,0,1,0,1,0,0),ncol=3)\r\nPA<-P%*%A\r\nprint(PA)\r\ndetA<--1*PA[1,1]*PA[2,2]*PA[3,3]\r\nprint(detA)\r\ndet(A)\r\nprint(\"detA is the determinant of the given matrix\")", "meta": {"hexsha": "92f5d7c0d0192d8798d19bc9720bd3715c0f6522", "size": 306, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.2.1/Ex5.2_1.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.2.1/Ex5.2_1.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "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": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH5/EX5.2.1/Ex5.2_1.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 30.6, "max_line_length": 52, "alphanum_fraction": 0.6274509804, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6516767681192289}} {"text": "library(\"car\")\ndata(\"Leinhardt\")\n\nhead(Leinhardt)\nstr(Leinhardt)\npairs(Leinhardt)\n\nplot(infant ~ income, data=Leinhardt)\nhist(Leinhardt$infant)\nhist(Leinhardt$income)\n\n\nLeinhardt$loginfant = log(Leinhardt$infant)\nLeinhardt$logincome = log(Leinhardt$income)\n\nplot(loginfant ~ logincome, data=Leinhardt)\n\n###Modeling \nlmod = lm(loginfant ~ logincome, data=Leinhardt)\nsummary(lmod) # estimates of coefficents very large in comparison to their standard error, showing statistical significance \n #r-squared tells us how much of the variability is explained by model \n\ndat = na.omit(Leinhardt)\n#Leinhardt\n\nlibrary(\"rjags\")\n\n# likelyhood is a normal distribution p(y|mu)\n# use a linearn model to draw mu\n# prior on the leniar model coeficents is a normal distribution with 2 coefecients, mean =0 and a variance = 1m \n# sig^2: inverse gamma for the variance == gamma prior on precision\n# lower the sample size of prior if we are not so confident in guess \nmod2_string =\" model {\n for (i in 1:n){\n y[i] ~ dnorm(mu[i], prec)\n mu[i] = b[1] + b[2]*log_income[i] + b[3]*is_oil[i]\n }\n\n for (j in 1:3){\n b[j] ~ dnorm(0.0, 1.0/1.0e6)\n }\n\n prec ~ dgamma(5.0/2.0, 5.0*10.0/2.0)\n sig2 = 1.0 / prec\n sig = sqrt(sig2)\n\n} \"\n\nset.seed(75)\ndata2_jags = list(y=dat$loginfant, n=nrow(dat), log_income=dat$logincome, is_oil=as.numeric(dat$oil==\"yes\"))\n\ndata2_jags$is_oil\n\n# choose to monitor standard dev \nparams2 = c(\"b\", \"sig\")\n\ninits2 = function() { \n inits = list(\"b\"=rnorm(3, 0.0, 100.0), \"prec\"=rgamma(1,1.0,1.0))\n}\n\n# run the model with 3 chains each starting with inits1 params\nmod2 = jags.model(textConnection(mod2_string), data=data2_jags, inits=inits2, n.chains=3)\n\ndic.samples(mod1, n.iter=1e3)\n\n# burn in period \nupdate(mod2, 1000)\n\nmod2_sim = coda.samples(model=mod2, variable.names=params2, n.iter=5e3)\n\n# stack matrices vertically \nmod2_csim = do.call(rbind, mod2_sim)\n\n\n### Convergence \nplot(mod2_sim)\ngelman.diag(mod2_sim)\nautocorr.diag(mod2_sim)\neffectiveSize(mod2_sim)\nsummary(mod2_sim)\nsummary(lmod)\n\n### Residuals differece between response the actual obsevation and the models prediction for each value \n# very important as they revieal violations with our assumptions to specify mode\n# looking for signs of non liniarity, not normally distributed, obsevation are not independent from one another \nlmod0 = lm(infant ~ income, data=Leinhardt)\nplot(resid(lmod0)) # assume independence if no patterns seen\nplot(predict(lomd0), resid(lmod0)) # want to see randomness \nqqnorm(resid(lmod0)) # check for normality, if nomal posint follow straight line, curves shows squew \n\nX = cbind(rep(1.0, dat2_jags$n), data2_jags$log_income, data2_jags$is_oil)\n\npm_params2 = colMeans(mod2_csim)\n\nyhat = drop(X %*% pm_params2[1:3]) #vector of predicated values from model\nresid2 = data2jags$y - yhat\n\nplot(resid2)\nplot(yhat, resid2)\nqqnorm(resid2)\n\nhead(rownames(dat)[order(resid2, decreasing=TRUE)])\n\n\n\n#tau = scale parameter \n# df= degrees of freedom, smaller give heavier tail\n# for the model (likeylihood) to have a mea nand variance we force the df to be greater than 2 \nmod3_string =\" model {\n for (i in 1:n){\n y[i] ~ dt(mu[i], rau, df)\n mu[i] = b[1] + b[2]*log_income[i] + b[3]*is_oil[i]\n }\n\n for (j in 1:3){\n b[j] ~ dnorm(0.0, 1.0/1.0e6)\n }\n\n df = nu + 2.0\n nu ~ dexp(1.0)\n\n tau ~ dgamma(5.0/2.0, 5.0*10.0/2.0)\n sig = sqrt(1.0/tau * df/(df-2.0))\n} \"\n\n\n", "meta": {"hexsha": "dbdf3f98d366d4678bc476c091279b2191be82d0", "size": 3441, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/linearRegressionMod2.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/linearRegressionMod2.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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": "montyCarlo/linearRegressionMod2.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "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.094488189, "max_line_length": 124, "alphanum_fraction": 0.6945655333, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6516767646660597}} {"text": "gig_lpdf <- function(x,p,a,b) {\n (p * 0.5 * log(a / b)\n - log(2 * besselK(sqrt(a * b), p))\n + (p - 1) * log(x)\n - (a * x + b / x) * 0.5\n )\n}\n\nx <- exp(seq(-10,log(10),length.out=200))\nplot(x,exp(gig_lpdf(x,2,1,1)))\n", "meta": {"hexsha": "cdfc371452c27723e29ae116b24ad7fe2a620604", "size": 232, "ext": "r", "lang": "R", "max_stars_repo_path": "sandbox/gig.r", "max_stars_repo_name": "oxcsml/Rmap", "max_stars_repo_head_hexsha": "5ae74e8b0e110cba578fe19159c0f87ea52fa495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-03T10:25:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-03T10:25:31.000Z", "max_issues_repo_path": "sandbox/gig.r", "max_issues_repo_name": "oxcsml/Rmap", "max_issues_repo_head_hexsha": "5ae74e8b0e110cba578fe19159c0f87ea52fa495", "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": "sandbox/gig.r", "max_forks_repo_name": "oxcsml/Rmap", "max_forks_repo_head_hexsha": "5ae74e8b0e110cba578fe19159c0f87ea52fa495", "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": 21.0909090909, "max_line_length": 41, "alphanum_fraction": 0.4482758621, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.651467204871574}} {"text": "# Thanks: Kai Chen. M.D.\n# Resident\n# Dept of Breast surgery,\n# Breast Tumor Center; \n# Sun Yat-sen Memorial Hospital\n# chenkai23@mail.sysu.edu.cn\n\n# Fit logistic model on 100 observations simulated from the actual \n# model given by Prob(Y=1 given X1, X2, X3) = 1/(1+exp[-(-1 + 2X1)]),\n# where X1 is a random uniform [0,1] variable. Hence X2 and X3 are \n# irrelevant. After fitting a linear additive model in X1, X2,\n# and X3, the coefficients are used to predict Prob(Y=1) on a\n# separate sample of 100 observations. Note that data splitting is\n# an inefficient validation method unless n > 20,000.\n\nrequire(rms)\nset.seed(1)\nn <- 200\nx1 <- runif(n)\nx2 <- runif(n)\nx3 <- runif(n)\nlogit <- 2*(x1-.5)\nP <- 1/(1+exp(-logit))\ny <- ifelse(runif(n)<=P, 1, 0)\nd <- data.frame(x1,x2,x3,y)\nf <- lrm(y ~ x1 + x2 + x3, subset=1:100)\npred.logit <- predict(f, d[101:200,])\nphat <- 1/(1+exp(-pred.logit))\n\nval.prob(phat, y[101:200], m=20, cex=.5) # subgroups of 20 obs.\n\nval.prob(x2[101:200], y[101:200], m=20, cex=.5) # subgroups of 20 obs.\n", "meta": {"hexsha": "597da62a325627f10b37daaec2a0896b4a7ad8bc", "size": 1034, "ext": "r", "lang": "R", "max_stars_repo_path": "SilveR/R/library/rms/tests/val.prob.r", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": "SilveR/R/library/rms/tests/val.prob.r", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": "SilveR/R/library/rms/tests/val.prob.r", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 31.3333333333, "max_line_length": 71, "alphanum_fraction": 0.6605415861, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6513847656541272}} {"text": "# A minimalistic Echo State Networks demo with Mackey-Glass (delay 17) data \r\n# in \"plain\" R.\r\n# by Mantas Lukosevicius 2012-2018\r\n# http://mantas.info\r\n\r\n# load the data\r\ntrainLen = 2000\r\ntestLen = 2000\r\ninitLen = 100\r\ndata = as.matrix(read.table('MackeyGlass_t17.txt'))\r\n\r\n# plot some of it\r\nwhile( dev.cur() != 1 ) dev.off() # close all previous plots\r\ndev.new()\r\nplot(data[1:1000],type='l')\r\ntitle(main='A sample of data')\r\n\r\n# generate the ESN reservoir\r\ninSize = outSize = 1\r\nresSize = 1000\r\na = 0.3 # leaking rate\r\n\r\nset.seed(42)\r\nWin = matrix(runif(resSize*(1+inSize),-0.5,0.5),resSize)\r\nW = matrix(runif(resSize*resSize,-0.5,0.5),resSize)\r\n\r\n# normalizing and setting spectral radius\r\ncat('Computing spectral radius...')\r\nrhoW = abs(eigen(W,only.values=TRUE)$values[1])\r\nprint('done.')\r\nW = W * 1.25 / rhoW\r\n\r\n# allocated memory for the design (collected states) matrix\r\nX = matrix(0,1+inSize+resSize,trainLen-initLen)\r\n# set the corresponding target matrix directly\r\nYt = matrix(data[(initLen+2):(trainLen+1)],1)\r\n\r\n# run the reservoir with the data and collect X\r\nx = rep(0,resSize)\r\nfor (t in 1:trainLen){\r\n u = data[t]\r\n x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )\r\n if (t > initLen)\r\n X[,t-initLen] = rbind(1,u,x)\r\n}\r\n\r\n# train the output\r\nreg = 1e-8 # regularization coefficient\r\nX_T = t(X)\r\nWout = Yt %*% X_T %*% solve( X %*% X_T + reg*diag(1+inSize+resSize) )\r\n\r\n# run the trained ESN in a generative mode. no need to initialize here, \r\n# because x is initialized with training data and we continue from there.\r\nY = matrix(0,outSize,testLen)\r\nu = data[trainLen+1]\r\nfor (t in 1:testLen){\r\n x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )\r\n y = Wout %*% rbind(1,u,x)\r\n Y[,t] = y\r\n # generative mode:\r\n u = y\r\n # this would be a predictive mode:\r\n #u = data[trainLen+t+1] \r\n}\r\n\r\n# compute MSE for the first errorLen time steps\r\nerrorLen = 500\r\nmse = ( sum( (data[(trainLen+2):(trainLen+errorLen+1)] - Y[1,1:errorLen])^2 )\r\n\t/ errorLen )\r\nprint( paste( 'MSE = ', mse ) )\r\n\r\n# plot some signals\r\ndev.new() \r\nplot( data[(trainLen+1):(trainLen+testLen+1)], type='l', col='green' )\r\nlines( c(Y), col='blue' )\r\ntitle(main=expression(paste('Target and generated signals ', bold(y)(italic(n)), \r\n\t' starting at ', italic(n)==0 )))\r\nlegend('bottomleft',legend=c('Target signal', 'Free-running predicted signal'), \r\n\tcol=c('green','blue'), lty=1, bty='n' )\r\n\r\ndev.new()\r\nmatplot( t(X[(1:20),(1:200)]), type='l' )\r\ntitle(main=expression(paste('Some reservoir activations ', bold(x)(italic(n)))))\r\n\r\ndev.new()\r\nbarplot( Wout )\r\ntitle(main=expression(paste('Output weights ', bold(W)^{out})))", "meta": {"hexsha": "3e5d9121492778ff903670023d854a1bf1e406c6", "size": 2645, "ext": "r", "lang": "R", "max_stars_repo_path": "minimalESN.r", "max_stars_repo_name": "schmitts/mantas_simple_esn", "max_stars_repo_head_hexsha": "dcb2bfd8dc0ad87bec51a6581fbac48c0dbe6836", "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": "minimalESN.r", "max_issues_repo_name": "schmitts/mantas_simple_esn", "max_issues_repo_head_hexsha": "dcb2bfd8dc0ad87bec51a6581fbac48c0dbe6836", "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": "minimalESN.r", "max_forks_repo_name": "schmitts/mantas_simple_esn", "max_forks_repo_head_hexsha": "dcb2bfd8dc0ad87bec51a6581fbac48c0dbe6836", "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.4022988506, "max_line_length": 82, "alphanum_fraction": 0.6355387524, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.65131421816737}} {"text": "# library(rgl)\n\neuclidean <- function(a, b) {\n return (sqrt(sum((a - b) ^ 2)))\n}\n\nw1 <- function(k, dist) {\n return (1 ^ k)\n}\n\nkwNN <- function(dataset, points, k, dist = euclidean, weight = w1) {\n answer <- array(dim = c(length(points[,1])))\n classes = unique(dataset$class)\n \n for (i in 1:length(points[,1])) {\n distance <- array(dim = c(length(dataset[,1])))\n for (j in 1:length(dataset[,1])) {\n distance[j] = dist(points[i, ], dataset[j, 1:2])\n }\n sortedDataset <- dataset[order(distance),]\n distance <- sort(distance)\n \n scores <- rep(x = 0, times = length(classes))\n names(scores) = classes\n for (j in 1:k) {\n scores[sortedDataset$class[j]] = scores[sortedDataset$class[j]] + weight(j, distance[j])\n }\n \n answer[i] = names(which.max(scores))[1]\n }\n \n return (answer)\n}\n\nkwNN_point <- function(dataset, point, k, dist = euclidean, weight = w1) {\n distances <- array(dim = c(length(dataset[,1])))\n for (i in 1:length(distances)) {\n distances[i] <- dist(point[,3:4], dataset[i,3:4])\n }\n \n sortedDataset <- dataset[order(distances),]\n distances <- sort(distances)\n scores <- array(0L, length(unique(dataset$Species)))\n names(scores) = unique(dataset$Species)\n for (i in 1:k) {\n scores[sortedDataset$Species[i]] = scores[sortedDataset$Species[i]] + weight(i, distances[i])\n }\n \n return (names(which.max(scores)))\n}\n\nkwnn_loo <- function(k, dset) {\n \n classes = unique(dset$class)\n qs <- seq(from = 0.0, to = 1.0, by = 0.05)\n result <- array(0L, dim = c(length(qs)))\n for (i in 1:length(dset[,1])) {\n cat(\"\\rProcessing sample\", i, \"of\", length(dset[,1]))\n dataset <- dset[-i,]\n distance <- array(dim=c(length(dataset[,1])))\n for (j in 1:(length(dataset[,1]))) {\n distance[j] <- euclidean(dataset[j, 1:2], dset[i, 1:2])\n }\n sortedDataset <- dataset[order(distance),]\n distance <- sort(distance)\n \n classesCount <- array(0L, dim = c(length(classes)))\n dimnames(classesCount) = list(classes)\n \n classesCount <- array(0L, dim = c(length(classes), length(qs)))\n dimnames(classesCount) = list(classes)\n for (j in 1:k) { # k's\n index <- 1\n for (q in qs) {\n classesCount[sortedDataset$class[j],index] <- classesCount[sortedDataset$class[j],index] + (q ^ j)\n classForCurrentK = names(which.max(classesCount[,index]))[1]\n \n index <- index + 1\n }\n }\n for (j in 1:length(qs)) {\n ans = names(which.max(classesCount[,j]))[1]\n \n \n if (ans == paste(dset$class[i])) {\n result[j] <- result[j] + 1\n }\n }\n }\n cat(\"\\n\")\n \n for (i in 1:length(result)) {\n result[i] <- result[i] / length(dset[,1])\n }\n \n return (result)\n}\n\ndf = data.frame(x = double(), y = double(), class = character())\n\ndf <- rbind(df, data.frame(x = 122, y = 2208, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 148, y = 1136, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 270, y = 2186, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 271, y = 2016, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 306, y = 1023, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 413, y = 1153, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 503, y = 2013, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 541, y = 971, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 706, y = 1018, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 837, y = 867, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 875, y = 1011, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 927, y = 1915, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 997, y = 897, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1005, y = 529, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1028, y = 1176, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1050, y = 1429, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1125, y = 781, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1144, y = 1061, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1146, y = 1751, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1192, y = 1601, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1264, y = 888, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1275, y = 1412, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1329, y = 576, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1366, y = 1586, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1405, y = 386, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1432, y = 1226, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1597, y = 279, class = \"class-2\"))\ndf <- rbind(df, data.frame(x = 1615, y = 1604, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1631, y = 1200, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1638, y = 1365, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1765, y = 1262, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1806, y = 1444, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1821, y = 1056, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1896, y = 877, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 1993, y = 695, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2027, y = 1415, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2087, y = 889, class = \"class-1\"))\ndf <- rbind(df, data.frame(x = 2189, y = 674, class = \"class-1\"))\n\nz = array(c(c(1164, 1232)), dim = c(1,2))\n\n# m <- fast_cvloo_kwnn()\nk <- 6\n\nqs <- (seq(from = 0.0, to = 1.0, by = 0.05))\nacc = kwnn_loo(6, df)\n\npar(mfrow=c(1,2), pty=\"s\")\n\nprint(qs[which.max(acc)])\n\nplot(qs, acc, type = \"l\", xlab = \"q\", ylab=\"Accuracy\")\npoints(qs[which.max(acc)], max(acc), pch = 19, col = \"red\")\n\nbestQ <- qs[which.max(acc)]\n\ncat(\"Best accuracy:\", max(acc), \"for q =\", qs[which.max(acc)])\n\ncolors <- c(\"class-1\" = \"blue\", \"class-2\" = \"red\")\nplot(df[, 1:2], bg = colors[paste(df$class)], pch=23, asp=1)\n\nresult <- kwNN(df, z, 5, euclidean, function(k, dist) { return(bestQ ^ k) })\npoints(z[,1], z[,2], bg = colors[result], pch = 22)", "meta": {"hexsha": "2d26faa273d0ad71a2ece5c75d2c728042a27163", "size": 5955, "ext": "r", "lang": "R", "max_stars_repo_path": "1 - Nearest neighbors algorithm/kwnn-loocv-img-exp.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "1 - Nearest neighbors algorithm/kwnn-loocv-img-exp.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "1 - Nearest neighbors algorithm/kwnn-loocv-img-exp.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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.5337423313, "max_line_length": 106, "alphanum_fraction": 0.5785054576, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6508923867909959}} {"text": "library(nloptr)\nlibrary(rlist)\n\nget_expected_I = function(N0, C0, beta, gamma, lambda) {\n \"\n Calculates expected new case counts for each step in the time series.\n \n Parameters\n ----------\n N0 : numeric\n Initial number of contagious patients.\n C0 : numeric\n Initial number of infected but non-contagious patients.\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n Lagged one step (beta[1] = beta(0) in our notation).\n gamma : numeric\n Probability that an infected, non-contagious patient will turn infectious in\n the next time step.\n lambda : numeric\n (1 / mean) number of days an individual will continue to be infectious.\n \n Returns\n -------\n expected_I : numeric vector\n Daily expected number of new cases.\n \"\n steps = length(beta)\n expected_I = rep(0, steps)\n expected_N = rep(0, steps)\n expected_C = rep(0, steps)\n N_previous = N0\n C_previous = C0\n for(t in 1:steps) {\n expected_I[t] = gamma * C_previous\n expected_N[t] = N_previous * pexp(1, rate=lambda, lower.tail=FALSE) + expected_I[t]\n expected_C[t] = (1 - gamma) * C_previous + beta[t] * N_previous\n N_previous = expected_N[t]\n C_previous = expected_C[t]\n }\n return(expected_I)\n}\n\nfit = function(observed_I, beta0, beta_min, beta_max, gamma0, gamma_min,\n gamma_max, lambda0, lambda_min, lambda_max, N00, N0_min, N0_max,\n C00, C0_min, C0_max, alpha, ignore_beta_diff) {\n \"\n Fits the model to observed daily new case counts.\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta0 : numeric vector\n Initial value for beta; the expected number of cases stemming from a single\n person in a single day.\n beta_min : numeric\n Beta lower bound.\n beta_max : numeric\n Beta upper bound.\n ignore_beta_diff : numeric vector\n List of beta indices for which differences should be ignored while\n calculating the loss function. This amounts to moments in time in which we\n allow the beta series to be discontinuous.\n \n Returns\n -------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n \"\n # concatenate initial parameters into a single vector for optimization\n x0 = c(beta0, gamma0, lambda0, N00, C00)\n steps = length(observed_I)\n lb = c(rep(beta_min, steps), gamma_min, lambda_min, N0_min, C0_min)\n ub = c(rep(beta_max, steps), gamma_max, lambda_max, N0_max, C0_max)\n # set optimization parameters\n opts = list(\"algorithm\" = \"NLOPT_LN_BOBYQA\", \"xtol_rel\" = 1.0e-7,\n \"maxeval\" = 10000000)\n # define loss function\n loss = function(x) {\n # unpack values\n beta = x[1:steps]\n gamma = x[steps + 1]\n lambda = x[steps + 2]\n N0 = x[steps + 3]\n C0 = x[steps + 4]\n # calculate loss\n expected_I = get_expected_I(N0, C0, beta, gamma, lambda)\n beta_diff = diff(beta)\n beta_diff = beta_diff[!1:length(beta_diff) %in% ignore_beta_diff]\n loss = mean((expected_I - observed_I) ^ 4) + alpha * mean(beta_diff ^ 2)\n }\n result = nloptr(x0=x0, eval_f=loss, eval_grad_f=NULL, lb=lb, ub=ub, opts=opts)\n model = list()\n model$beta = result$solution[1:steps]\n model$gamma = result$solution[steps + 1]\n model$lambda = result$solution[steps + 2]\n model$N0 = result$solution[steps + 3]\n model$C0 = result$solution[steps + 4]\n model$loss = result$objective\n return(model)\n}", "meta": {"hexsha": "8d3454acc1631ee04da36b5ecd9c1bcf7fd42622", "size": 3422, "ext": "r", "lang": "R", "max_stars_repo_path": "contagious_infected/model.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "contagious_infected/model.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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": "contagious_infected/model.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "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.5490196078, "max_line_length": 87, "alphanum_fraction": 0.6803039158, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6508923769141355}} {"text": "isLeapYear <- function(year) {\n ifelse(year%%100==0, year%%400==0, year%%4==0)\n}\n\nfor (y in c(1900, 1994, 1996, 1997, 2000)) {\n cat(y, ifelse(isLeapYear(y), \"is\", \"isn't\"), \"a leap year.\\n\")\n}\n", "meta": {"hexsha": "50cc305f6fefd86f983ac15d91cd6b63dc9b2c64", "size": 197, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Leap-year/R/leap-year.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Leap-year/R/leap-year.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/Leap-year/R/leap-year.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.625, "max_line_length": 64, "alphanum_fraction": 0.578680203, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6508270231814319}} {"text": "#' Path costs based on BPR link cost function\r\n#'\r\n#' This function calculates the path costs as a function of link flows over network. BPR link cost functions are assumed. \r\n#' @param x Traffic flow on all links of network\r\n#' @param A link-path incidence matrix\r\n#' @param Alpha Vector of free flow travel time parameters for each link\r\n#' @param Beta Vector of capacity parameters for each link\r\n#' @param pow Polynomial order of cost function for each link. Defaults to 4.\r\n#' @return Vector of path costs\r\n#' @keywords path route cost\r\n#' @examples\r\n#' A <- matrix(c(0,1,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1),ncol=4,byrow=T)\r\n#' Alpha <- rep(10,7)\r\n#' Beta <- rep(2,7)\r\n#' pow <- rep(4,7)\r\n#' path_flow <- c(10,20,15,15)\r\n#' x <- A%*%path_flow\r\n#' PathCost(x,A,Alpha,Beta)\r\n#' @export\r\n\r\nPathCost <- function(x,A=diag(length(x)),Alpha,Beta,pow=4){\r\n \tc(t(A)%*%LinkCost(A%*%x,Alpha,Beta,pow=pow))\r\n}", "meta": {"hexsha": "72e6c25d82dc0b47f87e11af3669077bcafd5ac9", "size": 918, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PathCost.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "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/PathCost.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "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/PathCost.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "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": 39.9130434783, "max_line_length": 123, "alphanum_fraction": 0.6644880174, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6507498315397356}} {"text": "library(shiny)\nlibrary(matrixcalc)\nlibrary(plotly)\n\ngaussPdf <- function (x, mu, E) {\n k <- length(x)\n ans <- exp(-0.5 * t(x - mu) %*% solve(E) %*% (x - mu)) /\n sqrt((2 * pi) ^ k * det(E))\n return (ans)\n}\n\nfunction(input, output, session, ...) {\n output$err <- function() {\n E <- matrix(c(input$E1, input$E3, input$E2, input$E4), nrow = 2)\n if (!matrixcalc::is.positive.definite(E)) {\n return(\"Error: covariance matrix has to be positive definite.\")\n }\n return(\"\")\n }\n \n output$p <- renderPlotly({\n mu = c(input$mu1, input$mu2)\n E <- matrix(c(input$E1, input$E3, input$E2, input$E4), nrow = 2)\n \n if (!matrixcalc::is.positive.definite(E)) {\n plot_ly()\n return()\n }\n \n xs <- seq(from = mu[1] - 5, to = mu[1] + 5, by = 0.1)\n ys <- seq(from = mu[2] - 5, to = mu[2] + 5, by = 0.1)\n z <- c()\n \n \n for (y in ys) {\n curr <- c()\n for (x in xs) {\n arg <- c(x, y)\n value <- gaussPdf(arg, mu, E)\n \n curr <- c(curr, value)\n }\n z <- rbind(z, curr)\n }\n \n \n fig <- plot_ly(\n type = 'surface',\n x = ~xs,\n y = ~ys,\n z = ~z) %>% add_surface(\n contours = list(\n z = list(\n show=TRUE,\n usecolormap=TRUE,\n highlightcolor=\"#ff0000\",\n project=list(z=TRUE)\n )\n )\n )\n fig\n })\n}", "meta": {"hexsha": "ac0da57794ede71e74eb4c9a93e382acfc83dab9", "size": 1390, "ext": "r", "lang": "R", "max_stars_repo_path": "5 - Contour lines of the Gaussian distribution PDF/shiny/server.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "5 - Contour lines of the Gaussian distribution PDF/shiny/server.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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": "5 - Contour lines of the Gaussian distribution PDF/shiny/server.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "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.0634920635, "max_line_length": 69, "alphanum_fraction": 0.4633093525, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6507498237261704}} {"text": "baseball <- read.csv(\"baseball.csv\")\r\nstr(baseball)\r\n\r\nmoneyball <- subset(baseball, Year < 2002)\r\nstr(moneyball)\r\n\r\nmoneyball$RD <- moneyball$RS - moneyball$RA\r\nstr(moneyball)\r\n\r\nplot(moneyball$RD, moneyball$W)\r\nWinsReg <- lm(W ~ RD, data = moneyball)\r\nsummary(WinsReg)\r\n\r\n# W = 80.88 + 0.105*(RD)\r\n# 80.88 + 0.1058(RD) >= 95, hence RD >= 135 =)\r\n\r\n# Quiz", "meta": {"hexsha": "2e1a1c65a6cffaa3cb859f7deb200d87d560c86f", "size": 356, "ext": "r", "lang": "R", "max_stars_repo_path": "RPubs_MITxWeek2/baseball.r", "max_stars_repo_name": "lugasraka/mitx-RAnalyticsEdge", "max_stars_repo_head_hexsha": "dfdefdd08a3a35edc33e596deb296cb5997b9328", "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": "RPubs_MITxWeek2/baseball.r", "max_issues_repo_name": "lugasraka/mitx-RAnalyticsEdge", "max_issues_repo_head_hexsha": "dfdefdd08a3a35edc33e596deb296cb5997b9328", "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": "RPubs_MITxWeek2/baseball.r", "max_forks_repo_name": "lugasraka/mitx-RAnalyticsEdge", "max_forks_repo_head_hexsha": "dfdefdd08a3a35edc33e596deb296cb5997b9328", "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.9411764706, "max_line_length": 47, "alphanum_fraction": 0.6376404494, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6507218884051904}} {"text": "=begin\n # sample-groebner03.rb\n\n require \"algebra\"\n F5 = ResidueClassRing(Integer, 2)\n F = AlgebraicExtensionField(F5, \"a\") {|a| a**3 + a + 1}\n a = F.var\n P = MPolynomial(F)\n \n x, y, z = P.vars(\"xyz\")\n f1 = x + y**2 + z**2 - 1\n f2 = x**2 + z**2 - y * a\n f3 = x - z - a\n \n f = x**3 + y**3 + z**3\n q, r = f.divmod_s(f1, f2, f3)\n p f == q.inner_product([f1, f2, f3]) + r #=> true\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "9ebb23f5cc6732a25e5d33dc2f6bceaf62a04093", "size": 414, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-groebner03.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-groebner03.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-groebner03.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.7, "max_line_length": 57, "alphanum_fraction": 0.5024154589, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6506270424955994}} {"text": "#############\n# ARS for the sampling of alpha in GMM and IGMM\n############\nlibrary(ars)\n\n\n# function\nf_y <- function(y, K=3, U=10){\n y*(K-3/2) - 1/(2*exp(y)) + lgamma(exp(y)) - lgamma(exp(y)+U)\n}\n\n# first derivative function\nf_y_prima <- function(y, K=3, U=10){\n (K-3/2) + 1/(2*exp(y)) + exp(y)*digamma(exp(y)) - exp(y)*digamma(exp(y)+U)\n}\n\n# Wrapper for ARS function\nsample_alpha <- function(K=3, U=10){\n y <- ars2(1, f_y, f_y_prima, x=c(-2,0,30), K=K, U=U)\n exp(y)\n}\n\n###############################################################################\n# Hack ARS function so that it returns the ifault codes and not just print them\n# so that we can handle it like an exception\n###############################################################################\n\nars2 <- function (n = 1, f, fprima, x = c(-4, 1, 4), ns = 100, m = 3, \n emax = 64, lb = FALSE, ub = FALSE, xlb = 0, xub = 0, ...) \n{\n mysample <- rep(0, n)\n iwv <- rep(0, ns + 7)\n rwv <- rep(0, 6 * (ns + 1) + 9)\n hx <- f(x, ...)\n hpx <- fprima(x, ...)\n initial <- .C(\"initial_\", as.integer(ns), as.integer(m), \n as.double(emax), as.double(x), as.double(hx), as.double(hpx), \n as.integer(lb), as.double(xlb), as.integer(ub), as.double(xub), \n ifault = as.integer(0), iwv = as.integer(iwv), rwv = as.double(rwv))\n if (initial$ifault == 0) {\n h <- function(x) f(x, ...)\n hprima <- function(x) fprima(x, ...)\n for (i in 1:n) {\n sample <- .C(\"sample_\", as.integer(initial$iwv), \n as.double(initial$rwv), h, hprima, new.env(), \n beta = as.double(0), ifault = as.integer(0))\n if (sample$ifault == 0) {\n if (i < ns) {\n x <- c(x, sample$beta)\n h <- function(x) f(x, ...)\n hprima <- function(x) fprima(x, ...)\n }\n mysample[i] <- sample$beta\n }\n else {\n cat(\"\\nError in sobroutine sample_...\")\n cat(\"\\nifault=\", sample$ifault, \"\\n\")\n stop(paste(\"\\nError in sobroutine sample_...\", sample$ifault))\n }\n }\n }\n else {\n cat(\"\\nError in sobroutine initial_...\")\n cat(\"\\nifault=\", initial$ifault, \"\\n\")\n stop(paste(\"\\nError in sobroutine initial_...\", initial$ifault))\n }\n return(mysample)\n}\n\nenvironment(ars2) <- environment(ars)", "meta": {"hexsha": "e68b69b03ddc4902af6ccae030e74e3132c628a7", "size": 2296, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ars_alpha.r", "max_stars_repo_name": "alumbreras/DP-GMM", "max_stars_repo_head_hexsha": "53507113710b7187b785408b429258f08787ef24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-02-25T16:31:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-17T17:43:46.000Z", "max_issues_repo_path": "ars_alpha.r", "max_issues_repo_name": "alumbreras/Dual-DPGMM", "max_issues_repo_head_hexsha": "a6153e74d23d6c45faf7e706de60b83c512f67bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-08T11:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-08T15:08:02.000Z", "max_forks_repo_path": "R/ars_alpha.r", "max_forks_repo_name": "alumbreras/DP-GMM", "max_forks_repo_head_hexsha": "53507113710b7187b785408b429258f08787ef24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T13:33:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:33:58.000Z", "avg_line_length": 32.8, "max_line_length": 84, "alphanum_fraction": 0.4908536585, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6504889138049926}} {"text": "#Code for calculating the area under curve using Trapezoidal Integration\n#Input File has single column containing Values\n\n\nargs <- commandArgs(trailingOnly = TRUE);\nraw_data = read.csv(args[1])\ndata <- cbind(1:dim(raw_data)[1],raw_data)\nrequire(pracma)\nAUC = trapz(as.vector(t(data[1])),as.vector(t(data[2])))\ndisp(AUC)\n", "meta": {"hexsha": "008800f6d070bd8c708ce4348a3148350153088b", "size": 320, "ext": "r", "lang": "R", "max_stars_repo_path": "area_under_curve.r", "max_stars_repo_name": "nairvinayv/Rscripts", "max_stars_repo_head_hexsha": "b740a13149494de9aba95fd8efecda2384d82624", "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": "area_under_curve.r", "max_issues_repo_name": "nairvinayv/Rscripts", "max_issues_repo_head_hexsha": "b740a13149494de9aba95fd8efecda2384d82624", "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": "area_under_curve.r", "max_forks_repo_name": "nairvinayv/Rscripts", "max_forks_repo_head_hexsha": "b740a13149494de9aba95fd8efecda2384d82624", "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.0909090909, "max_line_length": 72, "alphanum_fraction": 0.746875, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6503851411553866}} {"text": "# 4. faza: Analiza podatkov\n\n\n#6 Napoved števila igralcev tedna za centre\n\ntabela_centri_vmesno <- igralci_tedna %>% filter(Pozicija == \"C\")\nstetje <- count(tabela_centri_vmesno, Sezona_okrajsano)\ntabela_centri <- as.data.frame(stetje)\n\npril_lm <- lm(data=tabela_centri, n ~ Sezona_okrajsano)\nnova_leta <- data.frame(Sezona_okrajsano=seq(2019,2022,1))\nnapoved <- mutate(nova_leta, n=predict(pril_lm, nova_leta))\n\ngraf_napoved <- ggplot(tabela_centri, aes(Sezona_okrajsano,n)) + geom_smooth(method=\"lm\", fullrange=TRUE, alpha = 0.3, color = \"dodgerblue2\", size = 0.6)+\n geom_point(data=napoved,aes(Sezona_okrajsano,n),color=\"red\", size=2)+ theme_bw() +\n geom_point(color=\"dodgerblue4\", size = 2) + ggtitle(\"Napoved števila centrov kot igralcev tedna\") + xlab(\"Sezona\")+ylab(\"Število\")\n\n\n\n#7 Primerjava dveh igralcev\n\n\ntabela_harden2 <- tabela_harden[,-c(2,3,4,5,6,7,8,9,10,11,13)]\ntabela_harden2$Year <- as.numeric(tabela_harden2$Year)\ntabela_harden2 <- as.data.frame(tabela_harden2)\n\npril_lmh <- lm(data=tabela_harden2,P_WEEK ~ Year)\nnova_letah <- data.frame(Year=19)\nnapovedh <- mutate(nova_letah, P_WEEK=predict(pril_lmh,nova_letah))\n\n\ntabela_curry2 <- tabela_curry[,-c(2,3,4,5,6,7,8,9,10,11,13)]\ntabela_curry2$Year <- as.numeric(tabela_curry2$Year)\ntabela_curry2 <- as.data.frame(tabela_curry2)\n\npril_lmc <- lm(data=tabela_curry2,P_WEEK ~ Year)\nnova_letac <- data.frame(Year=19)\nnapovedc <- mutate(nova_letac, P_WEEK=predict(pril_lmc,nova_letac))\n\n\n\n\npril_lmh2 <- loess(data=tabela_harden2,P_WEEK ~ Year,control=loess.control(surface=\"direct\"))\nnova_letah2 <- data.frame(Year=19)\nnapovedh2 <- mutate(nova_letah2, P_WEEK=predict(pril_lmh2,nova_letah2))\n\npril_lmc2 <- loess(data=tabela_curry2,P_WEEK ~ Year,control=loess.control(surface=\"direct\"))\nnova_letac2 <- data.frame(Year=19)\nnapovedc2 <- mutate(nova_letac2, P_WEEK=predict(pril_lmc2,nova_letac2))\nnapovedc2[1,2] <- 0 # Ker vrednost ne more biti manjša od 0\n\n\n\ngraf_harden_curry2 <- ggplot(data=zdruzena, aes(Year,P_WEEK)) + geom_point(data = zdruzena %>% filter (Name ==\"Harden\"), color=\"red\", size=2.8) + \n geom_smooth(data = zdruzena %>% filter (Name ==\"Harden\"), color=\"red\", fill=\"indianred1\", size=1, alpha = 0.2, method=\"loess\") +\n geom_point(data= zdruzena %>% filter (Name == \"Curry\"), color = \"darkgoldenrod\", size =2.8) + theme_bw()+\n geom_smooth(data= zdruzena %>% filter (Name == \"Curry\"), color = \"darkgoldenrod\", fill=\"goldenrod1\", size=1, alpha= 0.2, method=\"loess\") + \n geom_point(data=napovedh,aes(Year,P_WEEK), color=\"tomato\",size=6,shape=16)+\n geom_point(data=napovedh,aes(Year,P_WEEK), color=\"black\",size=5,shape=49)+\n geom_point(data=napovedc,aes(Year,P_WEEK), color=\"goldenrod1\",size=6,shape=16)+\n geom_point(data=napovedc,aes(Year,P_WEEK), color=\"black\",size=5,shape=49)+\n geom_point(data=napovedh2, aes(Year, P_WEEK), color=\"tomato\",size=6,shape=16)+\n geom_point(data=napovedh2, aes(Year, P_WEEK), color=\"black\",size=5,shape=50)+\n geom_point(data=napovedc2,aes(Year,P_WEEK), color=\"goldenrod1\",size=6,shape=16)+\n geom_point(data=napovedc2,aes(Year,P_WEEK), color=\"black\",size=5,shape=50)+\n xlab(\"Sezona\") + ylab(\"Igralec tedna\") +\n ggtitle(\"Primerjava in napoved števila osvojenih nazivov igralca tedna\") + theme(legend.position = \"right\") +\n annotate(\"text\", x=16.8, y=7, label= \"James Harden\", color=\"red\", size=5) + \n annotate(\"text\",x=14,y=-2,label=\"Stephen Curry\", color=\"darkgoldenrod\", size=5)\n", "meta": {"hexsha": "4f898e76e7102459e60657ebad2d233f87383b04", "size": 3403, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "dePauk/APPR-2018-19", "max_stars_repo_head_hexsha": "3a81d510ba706beac195aa22220a3d8187134cd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-06T15:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-06T15:12:56.000Z", "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "dePauk/APPR-2018-19", "max_issues_repo_head_hexsha": "3a81d510ba706beac195aa22220a3d8187134cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-12-19T12:40:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-09T12:37:11.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "dePauk/APPR-2018-19", "max_forks_repo_head_hexsha": "3a81d510ba706beac195aa22220a3d8187134cd6", "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": 48.6142857143, "max_line_length": 154, "alphanum_fraction": 0.7296503086, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6503851258380726}} {"text": "=begin\n # sample-quotientfield04.rb\n\n require \"algebra\"\n \n F13 = ResidueClassRing(Integer, 13)\n F = RationalFunctionField(F13, \"x\")\n x = F.var\n AF = AlgebraicExtensionField(F, \"a\") {|a| a**2 - 2*x}\n a = AF.var\n \n p( (a/4*x + AF.unity/2)/(x**2 + a*x + 1) +\n (-a/4*x + AF.unity/2)/(x**2 - a*x + 1) )\n #=> (-x^3 + x^2 + 1)/(x^4 + 11x^3 + 2x^2 + 1)\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "47062f2ff55e22e75a7284c19e235744ae7207db", "size": 381, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-quotientfield04.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-quotientfield04.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-quotientfield04.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "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.4117647059, "max_line_length": 55, "alphanum_fraction": 0.5223097113, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6502547779909096}}