{"text": "library(foreign)\ndata <- read.dta('MPDataset.dta')\nsweden <- droplevels(subset(data, country == 'sweden'))\nlevels(sweden$party) <- c(\"MP\",\n \"V\",\n \"S\",\n \"FP\",\n \"KD\",\n \"M\",\n \"SD\",\n \"C\",\n \"NyD\")\nsweden$party <- factor(sweden$party, levels=levels(sweden$party)[c(2,3,1,8,5,4,6,7,9)])\ncolors <- c(\"#b70410\", \"#f9232b\", \"#79cf49\", \"#00993c\", \"#211974\",\n \"#5cb7e9\", \"#0049d8\", \"#dedd37\", \"#ffff41\")\n# These are the additive scaled dimensions from Lowe et.al., pp. 135 sqq.\nfreemarket.l <- c(401, 402)\nfreemarket.r <- c(403, 412, 413, 415)\nenvironment.l <- c(501, 416)\nenvironment.r <- c(410)\nstateconomy.l <- c(403, 404, 406, 412, 413, 504, 506, 701)\nstateconomy.r <- c(401, 402, 407, 414, 505)\nstateservices.l <- c(504, 506)\nstateservices.r <- c(505, 507)\nlogrile.l <- c(103, 105, 106, 107, 202, 403, 404, 406, 412, 413, 504, 506, 701)\nlogrile.r <- c(104, 201, 203, 305, 401, 402, 407, 414, 505, 601, 603, 605, 606)\nlogplaneco.l <- c(403, 404, 412)\nlogplaneco.r <- c(401, 414)\nlibcons.l <- c(103, 105, 106, 107, 202)\nlibcons.r <- c(104, 201, 203, 305, 601, 603, 605, 606)\nlogitm <- function(dataset, vars.l, vars.r) {\n log(rowSums(dataset[paste0(\"per\", vars.l)] + 0.5) / rowSums(dataset[paste0(\"per\", vars.r)] + 0.5))\n}\nsweden$freemarket <- logitm(sweden, freemarket.l, freemarket.r)\nsweden$environment <- logitm(sweden, environment.l, environment.r)\nsweden$stateconomy <- logitm(sweden, stateconomy.l, stateconomy.r)\nsweden$stateservices <- logitm(sweden, stateservices.l, stateservices.r)\nsweden$logrile <- -logitm(sweden, logrile.l, logrile.r)\nsweden$logplaneco <- logitm(sweden, logplaneco.l, logplaneco.r)\nsweden$libcons <- logitm(sweden, libcons.l, libcons.r)\n# These are logit scales for bipolar categories (again, Lowe et.al., pp. 131 sqq.)\nlogits <- function(dataset, var.l, var.r) {\n log(rowSums(dataset[paste0(\"per\", var.l)] + 0.5) / rowSums(dataset[paste0(\"per\", var.r)] + 0.5))\n}\nsweden$foreignalliances <- logits(sweden, 101, 102)\nsweden$militarism <- -logits(sweden, 105, 104)\nsweden$internationalism <- logits(sweden, 107, 109)\nsweden$logeu <- logits(sweden, 108, 110)\nsweden$constitutionalism <- logits(sweden, 203, 204)\nsweden$decentralization <- logits(sweden, 301, 302)\nsweden$protectionism <- logits(sweden, 406, 407)\nsweden$keynesian <- logits(sweden, 409, 414)\nsweden$nationalism <- -logits(sweden, 602, 601)\nsweden$morality <- -logits(sweden, 604, 603)\nsweden$multiculturalism <- logits(sweden, 607, 608)\nsweden$laborpolicy <- logits(sweden, 701, 702)\nsweden$logwelfare <- logits(sweden, 504, 505)\nsweden$education <- logits(sweden, 506, 507)\n\n## TODO: plot interesting 2d graph(s)\nlibrary(ggplot2)\nlibrary(reshape2)\nlibrary(Hmisc)\n\n# Plot all variables from Lowe et.al.\nvars <- c(\"freemarket\", \"environment\", \"stateconomy\", \"stateservices\", \"logrile\",\n \"logplaneco\", \"libcons\", \"foreignalliances\", \"militarism\", \"internationalism\",\n \"logeu\", \"constitutionalism\", \"decentralization\", \"protectionism\", \"keynesian\",\n \"nationalism\", \"morality\", \"multiculturalism\", \"laborpolicy\", \"logwelfare\",\n \"education\")\nfor(var in vars) {\n pdf(paste0(var, \".pdf\"), width=11.70, height=4.1)\n p <- ggplot(sweden, aes_string(x=\"edate\", y=var, group=\"party\", colour=\"party\"))\n print(\n p + geom_line() + geom_point() + scale_colour_manual(name=\"Parti\", values=colors) +\n labs(x = \"År\") +\n stat_summary(aes(group=country), fun.data=\"mean_cl_normal\", geom=\"smooth\", colour=\"#666666\", fill=\"#cccccc\")\n )\n dev.off()\n}\n\n# References\n# Lowe, W., Benoit, K., Mikhaylov, S. and Laver, M. 2011. ”Scaling Policy Preferences from Coded Political Texts.” Legislative Studies Quarterly 36 (1): 123–155.\n", "meta": {"hexsha": "ca8a931c1aec6d0bff54f026574f15dcf2c14eaf", "size": 3879, "ext": "r", "lang": "R", "max_stars_repo_path": "manifesto/manifesto.r", "max_stars_repo_name": "urdh/r-things", "max_stars_repo_head_hexsha": "e94c713a877eb4b3f3e9c00dedf03bf6e426096a", "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": "manifesto/manifesto.r", "max_issues_repo_name": "urdh/r-things", "max_issues_repo_head_hexsha": "e94c713a877eb4b3f3e9c00dedf03bf6e426096a", "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": "manifesto/manifesto.r", "max_forks_repo_name": "urdh/r-things", "max_forks_repo_head_hexsha": "e94c713a877eb4b3f3e9c00dedf03bf6e426096a", "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": 46.1785714286, "max_line_length": 161, "alphanum_fraction": 0.6385666409, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5999553740054354}} {"text": "#' Compute one component of the periodogram.\n#'\n#' @param t Sampling times.\n#' @param x Value of timeseries at each sample time, after demeaning and standardizing.\n#' @param omega Angular frequency to evaluate periodogram at.\n#' @param tau Time-shift parameter tau.\n#' @param sincos Either \"sin\" or \"cos\": whichever component is desired.\n#'\n#' @return Periodogram component value.\n#'\n#' @examples\n#' periodogram.component(1:10, sin(1:10), 1, tau(1:10, 1), \"sin\")\n#'\n#' @export\nperiodogram.component <- function(t, x, omega, tau, sincos) {\n\n ## Input Validation ##\n\n # Parse the strings \"sin\" and \"cos\" into their respective functions,\n # and raise an error if neither provided.\n sincos.fn <- switch(sincos, sin = sin, cos = cos)\n if (is.null(sincos.fn)) {\n stop(\"Invalid value '\", sincos, \"' provided for 'sincos'. \",\n \"Must be either 'sin' or 'cos'.\")\n }\n\n t.minus.tau <- outer(tau, t, FUN = `-`)\n sincos.vec <- sincos.fn(t.minus.tau * omega)\n\n (sincos.vec %*% x) / sqrt(rowSums(sincos.vec^2))\n\n}\n", "meta": {"hexsha": "c073992b28111d434ae8e1f2929d9cb47be984b8", "size": 1044, "ext": "r", "lang": "R", "max_stars_repo_path": "R/periodogram.component.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/periodogram.component.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/periodogram.component.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": 31.6363636364, "max_line_length": 87, "alphanum_fraction": 0.6427203065, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5995946896725249}} {"text": "## Created on Friday, November 12, 2021 at 3:02pm EST by WeekendEditor on WeekendEditorMachine.\n## Copyright (c) 2021, SomeWeekendReading.blog. All rights reserved. As if you care.\n\nlibrary(\"gsDesign\") # For ciBinomial()\n\n##\n## Simple-minded efficacy computation, with confidence limits using a scaled binomial model.\n## (To be eventually replaced by my super-duper Beta ratios stuff with Gauss hypergeometric magic!)\n##\n\n## Molnupiravir example, hospitalizations:\n## > signif(efficacyAndCL(384, 28, 376, 53), digits = 3)\n## LCL Eff UCL\n## 0.205 0.483 0.665\n##\n## Paxlovid example, hospitalizations:\n## > signif(efficacyAndCL(389, 3, 385, 27), digits = 3)\n## LCL Eff UCL\n## 0.663 0.890 0.964\n##\n## Paxlovid example, deaths:\n## > signif(efficacyAndCL(389, 0, 385, 7), digits = 3)\n## LCL Eff UCL\n## 0.46 1.00 1.00\n##\n## Paxlovid final report, hospitalizations:\n## > signif(efficacyAndCL(1039, 8, 1046, 66), digits = 3)\n## LCL Eff UCL\n## 0.751 0.878 0.940\n##\n## Paxlovid final report, deaths:\n## > signif(efficacyAndCL(1039, 0, 1046, 12), digits = 3)\n## LCL Eff UCL\n## 0.679 1.000 1.000\n##\n## Try the qBetaRatio() method here? Are these numbers small enough for the naive implementation?\n## For molnumpiravir\n## > 1 - medianCLBetaRatio(28 + 1, 384 - 28 + 1, 53 + 1, 376 - 53 + 1, 0.05, 0, 10)\nefficacyAndCL <- function(Ntrt, Ktrt, Ncnt, Kcnt) { # Treatment efficacy & 95% conf limit\n ## Ntrt = number of subjects in treatment arm\n ## Ktrt = number of sick in treatment arm\n ## Ncnt = number of subjects in control arm\n ## Kcnt = number of sick in control arm\n eff <- 1 - (Ktrt / Ntrt) / (Kcnt / Ncnt) # Point estimate, then confidence limits\n effCL <- rev(1 - ciBinomial(Ktrt, Kcnt, Ntrt, Ncnt, scale = \"RR\"))\n c(LCL = effCL[[1]], Eff = eff, UCL = effCL[[2]]) # Return 3-vector of LCL, estimate, and UCL\n} #\n", "meta": {"hexsha": "76eaa0a5730bad065acac11c8f5b1ea3d3f83be9", "size": 1949, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2021-11-12-covid-treatments-simple-efficacy-confidence-limits.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/2021-11-12-covid-treatments-simple-efficacy-confidence-limits.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/2021-11-12-covid-treatments-simple-efficacy-confidence-limits.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": 40.6041666667, "max_line_length": 99, "alphanum_fraction": 0.6295536172, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6959583250334525, "lm_q1q2_score": 0.5995946842395087}} {"text": "#' @title calcAdmPwr\n#'\n#' @description Calculates ship power (kW) using the admiralty formula.\n#'\n#' @param totalInstalledPwr Total installed main engine power (vector of numericals,\n#' kW) (maximum continuous rated power)\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param refSpeed Reference speed of the ship (service speed or maximum speed)\n#' (vector of numericals, m/s)\n#' @param actualDraft Actual draft (vector of numericals, m)\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#' @param serviceMargin A service margin to account for weather and sea effects:\n#' \\itemize{\\item At-sea operations = 15 (Default) \\item Coastal operations = 10}\n#' Can supply either a vector of numericals, a single number, or rely on the default.\n#' @param n Exponential relationship applied to the ship speed ratio (dimensionless).\n#' Default = 3. This argument is not vectorized, so supply a single number or rely\n#' on the default\n#' @param refSpeedType Indicates if the reference speed is service speed or\n#' maximum speed: \\itemize{\n#' \\item \"serviceSpeed (Default)\"\n#' \\item \"maxSpeed\"}\n#' Can supply either a vector of strings, a single value, or rely on the default.\n#'\n#' @details\n#' Ship speed and actual draft are typically obtained from sources such as AIS\n#' messages or ship records.\n#'\n#' This implementation assumes the following default values:\n#'\n#' n = 3 (IMO greenhouse gas study)\n#'\n#' serviceMargin = 10 or 15, based on IMO (Prpic Orsic and Faltinsen, 2012).\n#' 15 indicates 15\\% increased resistance in at-sea water conditions, and 10\n#' indicates 10\\% increased resistance in coastal water conditions.\n#'\n#' Note that service margin is treated as an added resistance here\n#' (instead of as a reduced efficiency) to maintain consistency with the other\n#' power models used in this library. (See MAN, 2011).\n#'\n#' @return power (vector of numericals, kW)\n#'\n#' @references\n#'International Maritime Organization. 2014. \"Third IMO GHG study 2014 - Final\n#'report.\" London: International Maritime Organization.\n#'\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calcPropPwr}}\n#'\\item \\code{vignette(\"OverviewOfPowerModels\", package=\"ShipPowerModel\")}\n#'\\item \\code{vignette(\"Admiralty.Formula.Example\", package=\"ShipPowerModel\")}\n#'}\n#'\n#' @examples\n#' calcAdmPwr(9363, seq(0,13,1), 15, 12.48, 13.57, serviceMargin = 15, n=3)\n#'\n#' @export\n\ncalcAdmPwr <- function(totalInstalledPwr, shipSpeed, refSpeed, actualDraft, maxDraft,\n serviceMargin = 15, n=3,\n refSpeedType = \"serviceSpeed\"){\n\n #The admiralty formula method requires the the reference speed to be maximum speed, to be consistent with the other terms.\n #Convert service speed to maximum speed by assuming service speed is 94% of maximum speed.\n refSpeed<-ifelse(tolower(refSpeedType) == \"servicespeed\",\n refSpeed/0.94,\n refSpeed\n )#end ifelse\n\n power <- ifelse(shipSpeed==0,\n 0,\n totalInstalledPwr*\n pmin(1, #set maximum power to 100%\n pmax(.02, #limit minimum power to 2%\n ((actualDraft/maxDraft)^(2/3)*\n (shipSpeed/refSpeed)^(n))*\n ((100+serviceMargin)/100)\n )\n )\n )#end ifelse\n return(power)\n\n}#end of calcAdmPwr\n", "meta": {"hexsha": "d764d166126811f458d8c649bbc949074a188c91", "size": 3692, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcAdmPwr.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/calcAdmPwr.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/calcAdmPwr.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 42.4367816092, "max_line_length": 124, "alphanum_fraction": 0.6684723727, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5995414739130017}} {"text": "#################################################################\r\n####### Risk Analysis for Wind Turbine Toolkit ########\r\n#################################################################\r\n\r\n## FEM.mean.R (2014-2020)\r\n##\r\n## Copyright 2014-2020 Alexandre Brouste \r\n\r\n## INPUT VARIABLES\r\n#################################################################\r\n## x : \r\n## theta :\r\n## Delta :\r\n#################################################################\r\n\r\n\r\n## OUTPUT VARIABLES\r\n#################################################################\r\n## forecast\r\n#################################################################\r\n\r\n# parameters = (kappa,theta,sigma) --> theta[1,2,3] respectively\r\n\r\naf<-function(x,theta){return(theta[1]*(theta[2]-x))}\r\n\r\nbf<-function(x,theta){return(theta[3]^2)}\r\n\r\nbfprime<-function(x,theta){return(0)}\r\n\r\nOU.FEM<-function(x0,theta,DeltaTime,param=list(Minf=-8,Msup=8,N=200),R=10){\r\n \r\n Minf<-param$Minf\r\n Msup<-param$Msup\r\n N<-param$N\r\n \r\n space<-seq(Minf,Msup,length=N+1)\r\n Delta<-(Msup-Minf)/N\r\n \r\n # Elements finis\r\n \r\n phi<-function(x,n){\r\n (1-1/Delta*abs(x-space[n+1]))*(x>space[n])*(xspace[n]) - (x>space[n+1])*(x 0) {\n if ((FOUR * q + r - t) < (n * t)) {\n if (char_printed == 80) {\n cat(\"\\n\")\n char_printed <- 0\n }\n how_many <- how_many - 1\n char_printed <- char_printed + 1\n cat(as.integer(n))\n if (first) {\n cat(\".\")\n first <- FALSE\n char_printed <- char_printed + 1\n }\n nr <- as.bigz(TEN * (r - n * t))\n n <- as.bigz(((TEN * (THREE * q + r)) %/% t) - (TEN * n))\n q <- as.bigz(q * TEN)\n r <- as.bigz(nr)\n } else {\n nr <- as.bigz((TWO * q + r) * l)\n nn <- as.bigz((q * (SEVEN * k + TWO) + r * l) %/% (t * l))\n q <- as.bigz(q * k)\n t <- as.bigz(t * l)\n l <- as.bigz(l + TWO)\n k <- as.bigz(k + ONE)\n n <- as.bigz(nn)\n r <- as.bigz(nr)\n }\n}\ncat(\"\\n\")\n", "meta": {"hexsha": "f202b73ffe0e15d8a044099da34169e728d4b55d", "size": 1057, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Pi/R/pi.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": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Pi/R/pi.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/Pi/R/pi.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.7254901961, "max_line_length": 62, "alphanum_fraction": 0.4635761589, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5992905092940788}} {"text": "# Day 6: Lanternfish\n\nget_day6_input_path <- function() {\n paste(getwd(), \"/2021/Day 6/Day6_input.txt\", sep = \"\")\n}\n\npart1 <- function(num_days = 80) {\n readings <- readLines(get_day6_input_path())\n\n days <- num_days\n fishies <- strtoi(unlist(strsplit(readings[1], \",\")))\n\n lanternfish <- optimize_fishies(fishies, c(1:5))\n\n for (i in 1:days) {\n lanternfish[, 1] <- lanternfish[, 1] - 1\n\n sum_new_fishies <- sum(lanternfish[which(lanternfish[, 1] == -1), 2])\n\n lanternfish[, 1][lanternfish[, 1] == -1] <- 6\n if (sum_new_fishies > 0) {\n lanternfish <- rbind(lanternfish, c(8, sum_new_fishies))\n }\n }\n print(sum(lanternfish[, 2]))\n print(paste(sum(lanternfish[, 2])))\n}\n\npart2 <- function() {\n part1(256)\n}\n\noptimize_fishies <- function(fishies, starting_vals) {\n lanternfish <- matrix(ncol = 2)[-1, ]\n\n for (i in seq_len(length(starting_vals))) {\n sum_of_i <- sum(fishies == i)\n if (sum_of_i > 0) {\n lanternfish <- rbind(lanternfish, c(i, sum_of_i))\n }\n }\n\n lanternfish\n}\n\npart1()\npart2()\n", "meta": {"hexsha": "de739ba5d7b26f6633b235ebe148d901f71634d7", "size": 1108, "ext": "r", "lang": "R", "max_stars_repo_path": "2021/Day 06/Day6_Lanternfish.r", "max_stars_repo_name": "jonmichalik/advent-of-code", "max_stars_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021/Day 06/Day6_Lanternfish.r", "max_issues_repo_name": "jonmichalik/advent-of-code", "max_issues_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021/Day 06/Day6_Lanternfish.r", "max_forks_repo_name": "jonmichalik/advent-of-code", "max_forks_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 77, "alphanum_fraction": 0.5821299639, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5988871815569916}} {"text": "sierpinski.triangle = function(n) {\n\tlen <- 2^(n+1)\n\tb <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2))\n\tfor (i in 1:(len/2))\n\t{\n\t\tcat(paste(ifelse(b,\"*\",\" \"),collapse=\"\"),\"\\n\")\n\t\tn <- rep(FALSE,len+1)\n\t\tn[which(b)-1]<-TRUE\n\t\tn[which(b)+1]<-xor(n[which(b)+1],TRUE)\n\t\tb <- n\n\t}\n}\nsierpinski.triangle(5)\n", "meta": {"hexsha": "ea27c43a70a2895445785c04e70f4939661fa19b", "size": 298, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sierpinski-triangle/R/sierpinski-triangle-1.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/R/sierpinski-triangle-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/Sierpinski-triangle/R/sierpinski-triangle-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": 21.2857142857, "max_line_length": 48, "alphanum_fraction": 0.5604026846, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5985335013773321}} {"text": "#' @title\n#' Generate initial estimators\n#'\n#' @description\n#' This function provides the initial estimators of U and V to initialize the\n#' blockwise coordinate descent algorithm.\n#'\n#' @usage\n#' NRRR.ini(Y, X, r, rx, ry, jx, jy, p, d, n)\n#'\n#'\n#' @param Y response matrix of dimension n-by-jy*d.\n#' @param X design matrix of dimension n-by-jx*p.\n#' @param r rank of the local reduced-rank structure.\n#' @param rx number of latent predictors.\n#' @param ry number of latent responses.\n#' @param jx number of basis functions to expand the functional predictor.\n#' @param jy number of basis functions to expand the functional response.\n#' @param p number of predictors.\n#' @param d number of responses.\n#' @param n sample size.\n#'\n#'\n#' @return The function returns a list:\n#' \\item{Ag}{the estimated U.}\n#' \\item{Bg}{the estimated V.}\n#'\n#' @references Liu, X., Ma, S., & Chen, K. (2020).\n#' Multivariate Functional Regression via Nested Reduced-Rank Regularization.\n#' arXiv: Methodology.\n#'\n#' @examples\n#' library(NRRR)\n#' simDat <- NRRR.sim(n = 100, ns = 200, nt = 200, r = 5, rx = 3, ry = 3,\n#' jx = 15, jy = 15, p = 10, d = 6, s2n = 1, rho_X = 0.5,\n#' rho_E = 0, Sigma = \"CorrAR\")\n#' fit_init <- with(simDat, NRRR.ini(Y = Yest, X = Xest, r = 5,\n#' rx = 3, ry = 3, jx = 15, jy = 15,\n#' p = 10, d = 6, n = 100))\n#' fit_init$Ag\n#' @export\nNRRR.ini <- function(Y,X,r,rx,ry,jx,jy,p,d,n){\n #require(rrpack)\n if (r == 0) stop(\"r cannot be 0\")\n if (r > min(dim(Y)[2])) stop(\"r cannot be greater than jy*d\")\n if(p < rx) stop(\"rx cannot be greater than p\")\n if(d < ry) stop(\"ry cannot be greater than d\")\n\n\n # ignore the global structure to estimate C from RRR\n fit_RRR <- RRR(Y,X,nrank=r)\n Crr <- fit_RRR$C\n # Compute Bghat, i.e, V\n if(p==rx){\n Bghat <- diag(nrow=rx,ncol=rx)\n }else{\n Cbg <- matrix(nrow=p,ncol=d*jy*jx,NA)\n for(j in 1:jx){\n a1 <- d*jy*(j-1) + 1\n b1 <- d*jy*j\n\n a2 <- p*(j-1) + 1\n b2 <- p*j\n Cbg[,a1:b1] <- Crr[a2:b2,]\n }\n Bghat <- as.matrix(svd(Cbg, nu=rx,nv=rx)$u)\n }\n\n\n #Compute Aghat, i.e., U\n if(d==ry){\n Aghat <- diag(nrow=ry,ncol=ry)\n }else{\n Cag <- matrix(nrow=d,ncol=p*jy*jx,NA)\n for(j in 1:jy){\n a1 <- p*jx*(j-1) + 1\n b1 <- p*jx*j\n\n a2 <- d*(j-1) + 1\n b2 <- d*j\n\n Cag[,a1:b1] <- t(Crr[,a2:b2])\n }\n Aghat <- as.matrix(svd(Cag, nu=ry,nv=ry)$u)\n }\n\n\n return(list(Ag=Aghat,Bg=Bghat,C=Crr))\n}\n\n\n\n", "meta": {"hexsha": "10010a184c4914c1fb09e42d94c3eb1ff84190cd", "size": 2486, "ext": "r", "lang": "R", "max_stars_repo_path": "R/NestRRRini.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/NestRRRini.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/NestRRRini.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": 26.7311827957, "max_line_length": 77, "alphanum_fraction": 0.5683829445, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5984829586226027}} {"text": "#'@title calcHMTotalRes\n#'\n#' @description Calculate total ship resistance (\\code{Rtot}) (kN) using the\n#' Holtrop & Mennen method.\n#'\n#' @param Rapp Appendage resistance (vector of numericals, kN) (see \n#' \\code{\\link{calcHMAppendageRes}})\n#' @param Rw Wave waking (similar to residual) resistance (vector of numericals, kN)\n#' (see \\code{\\link{calcHMWaveMakingRes}})\n#' @param Rb Bulbous bow resistance (vector of numericals, kN) (see \n#' \\code{\\link{calcHMBulbousBowRes}})\n#' @param Rtr Immersed transom resistance (vector of numericals, kN) (see \n#' \\code{\\link{calcHMImmersedTransomRes}})\n#' @param seawaterDensity Sea water density. Default = 1.025 (g/cm^2). Can \n#' supply either a vector of numericals, a single number, or rely on the default\n#' @param wettedSA Wetted hull surface area (vector of numericals, m^2) (see \n#' \\code{\\link{calcHMWettedSA}})\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see \n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param Cf Frictional resistance coefficient (vector of numericals, dimensionless) \n#' (see \\code{\\link{calcCf}})\n#' @param formFactor Form factor (1+k) (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcHMFormFactor}})\n#' @param Ca Incremental hull (roughness) resistance coefficient (vector of \n#' numericals, dimensionless) (see \\code{\\link{calcHMCa}})\n#' @param serviceMargin A service margin to account for weather and sea effects:\n#' \\itemize{\\item Coastal operations = 10 \\item At-sea operations = 15 (default)}.\n#' Can 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#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#' @seealso \\code{\\link{calcSpeedUnitConversion}}\n#'\n#' @family Holtrop-Mennen Calculations\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcHMTotalRes(Rapp=0.24,\n#' Rw=2.6,\n#' Rb=c(4.538188e-07,3.579217e-06,1.180116e-05,2.709520e-05,5.085940e-05),\n#' Rtr=c(0.58,2.2,4.8,8.1,12.1),\n#' seawaterDensity=1.025,\n#' wettedSA=10746.282,\n#' shipSpeed=seq(1,5,1),\n#' Cf=c(0.0019,0.0017,0.0016,0.0016,0.0015),\n#' formFactor=1.275601,\n#' Ca=0.0003356088,\n#' serviceMargin=15)\n#'\n#' @export\n\ncalcHMTotalRes<- function(Rapp,Rw,Rb,Rtr,seawaterDensity,wettedSA,shipSpeed,\n Cf,formFactor,Ca,serviceMargin){\n Rtot<-\n( Rapp+Rw+Rb+Rtr+\n (.5*seawaterDensity*wettedSA*((shipSpeed)^2)*Cf)*(formFactor)+\n (.5*seawaterDensity*wettedSA*((shipSpeed)^2)*Ca))*(1+serviceMargin/100)\n return(Rtot)\n}\n\n", "meta": {"hexsha": "a404f4d9f5356d497aad66e933c9ef2f68d23344", "size": 2842, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMTotalRes.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/calcHMTotalRes.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/calcHMTotalRes.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": 41.7941176471, "max_line_length": 89, "alphanum_fraction": 0.6713581985, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5984784111208136}} {"text": "#' Z-polytope sampler for linear inverse problems\r\n#'\r\n#' For the linear inverse problem y=Ax where y and x are counts, the y-fibre (solution set) is a Z-polytope (i.e. the points on the integer lattice within a convex polytope). This function implements samplers for the Z-polytope, with using a dynamic lattice basis or a full Markov basis. The underyling model for x can be Poisson, uniform or negative binomial.\r\n#' @param y Vector of observed count data.\r\n#' @param A Model configuration matrix, assumed to be binary.\r\n#' @param lambda Mean vector for x.\r\n#' @param U Optional matrix the columns of which should be a Markov (sub)-basis.\r\n#' @param Method \"MH\" for Metropolis-Hastings sampler, \"Gibbs\" for Gibbs sampler.\r\n#' @param Reorder Should the columns of A be reordered? Defaults to TRUE.\r\n#' @param tune.par Tuning parameter (alpha) controlling variation in fitness values for lattice bases. Defaults to 0.5.\r\n#' @param combine Should extra moves be included combining lattice basis vectors? Defaults to FALSE, but should usually be set to TRUE if A is not unimodular.\r\n#' @param x.order If Reorder=FALSE, x.order can be used to reorder columns of A to match ordering of entries of x. Defaults to NULL when no such reordering is performed.\r\n#' @param x.ini Vector of initial values for x. Default is NULL, when initial values derived through integer programming.\r\n#' @param Model \"Poisson\", \"Uniform\", \"NegBin\" or \"Normal\" (the last being a discrete approximation).\r\n#' @param Proposal \"NonUnif\" or \"Unif\" (default).\r\n#' @param NB.alpha Dispersion parameter for negaqtive-binomial distribution. Defaults to 1.\r\n#' @param ndraws Number of iterations to run sampler after burn-in. One iteration comprises cycling through the full basis (possibly augmented by a combined move). Defaults to 10^4.\r\n#' @param burnin Number of iteractions for burn in period. Defaults to 2000, which is usually more than adequate.\r\n#' @param verbose Controls level of detail in recording lattice bases used.\r\n#' @param THIN Thinning parameter for output. Defaults to 1 (no thinning).\r\n#' @return A list with components X (a matrix, each row corresponding to samplers for an entry of x) and x.order (a vector describing dynamic selection of lattice bases, if verbose=1).\r\n#' @export\r\n#' @examples \r\n#' data(LondonRoad)\r\n#' Xsampler(A=LondonRoad$A,y=LondonRoad$y,lambda=LondonRoad$lambda,Model=\"Poisson\",Method=\"Gibbs\",tune.par=0.5,combine=FALSE)\r\n\r\nXsampler <- function (y, A, lambda, U=NULL, Method=\"MH\", Reorder=TRUE, tune.par=0.5, combine=FALSE, x.order=NULL, x.ini=NULL, Model=\"Poisson\", Proposal=\"Unif\", NB.alpha=1, ndraws = 10000, burnin = 2000, verbose = 0, THIN = 1) {\r\n\trequire(lpSolve)\r\n\trequire(numbers)\r\n\trequire(extraDistr)\r\n \tif(Model==\"NegBin\" & NB.alpha<=0) NB.alpha=1\r\n\tif(Model==\"Uniform\") Method <- \"Gibbs\"\r\n\ty <- as.numeric(y)\r\n\tr <- ncol(A)\r\n\tn <- nrow(A)\r\n\ttol <- 10^{-10}\r\n\r\n\tif (is.matrix(U)) Reorder=FALSE\r\n\t\r\n\tif (Reorder){\r\n\t\tlambda.star <- lambda\r\n\t\tlam.order <- order(lambda.star,decreasing=TRUE) \r\n\t\tA <- A[,lam.order]\r\n\t\tx.order <- lam.order\r\n\t\tfor (i in 3:n){\r\n\t\t\twhile (qr(A[,1:i])$rank < i){\r\n\t\t\t\tA <- A[,c(1:(i-1),(i+1):r,i)]\r\n\t\t\t\tx.order <- x.order[c(1:(i-1),(i+1):r,i)]\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (!Reorder) { \r\n\t\tif(is.null(x.order)) x.order <- 1:r\r\n\t\tA <- A[,x.order]\r\n\t}\r\n\r\n\tlambda <- lambda[x.order]\r\n\t\r\n\tif (is.matrix(U)){\r\n\t \tdA1 <- 1\r\n\t\ttune.par <- -1\r\n\t}\r\n\tif (!is.matrix(U)){\r\n\t\tA1 <- A[,1:n]\r\n\t\tdA1 <- det(A1)\r\n\t\tA2 <- as.matrix(A[,-c(1:n)])\r\n\t\tA1.inv <- solve(A1)\r\n\t\tC <- A1.inv%*%A2\r\n\t\tU <- rbind(-C,diag(r-n))\r\n\t}\r\n\r\n\tm <- ncol(U) + 1*combine\r\n\r\n\tX <- matrix(0, r, m*(ndraws + burnin)+1)\r\n\tif (verbose==1) X.ORDER <- matrix(0, r, m*(ndraws + burnin)+1)\r\n\r\n\tif (!is.null(x.ini)) x.ini <- x.ini[x.order]\r\n\tif (is.null(x.ini)){\r\n\t\tx.ini <- lp(\"max\",objective.in=rep(1,r),const.mat=A,const.dir=rep(\"=\",nrow(A)),const.rhs=y,all.int=T)$solution\r\n\t}\r\n\tx <- x.ini\r\n X[x.order,1] <- x\r\n\tif (verbose==1) X.ORDER[,1] <- x.order\r\n\t\r\n\tfor (iter in seq(1, ndraws + burnin)) {\r\n\t\tfor (j in 1:m){\r\n\t\t\tif (j <= ncol(U)) z <- U[,j]\r\n\t\t\tif (j > ncol(U)){\r\n\t\t\t\tdelta <- 0\r\n\t\t\t\twhile(sum(delta)==0) delta <- rpois(ncol(U),lambda=0.5)\r\n\t\t\t\tdelta <- delta*sample(c(-1,1),size=ncol(U),replace=T)\r\n\t\t\t\tz <- U%*%delta\r\n\t\t\t}\r\n\t\t\tif (abs(dA1)!=1) { if(is_wholenumber(z)==F) z <- round(z*abs(dA1))/mGCD(round(abs(z*dA1))) }\r\n\t\t\tmax.move <- floor(min((x/abs(z))[which(z<0)]))\r\n\t\t\tmin.move <- -floor(min((x/abs(z))[which(z>0)]))\r\n\t\t\tx.min <- x+min.move*z\r\n\t\t\tx.max <- x+max.move*z\r\n\t\t\tindx <- 1:(max.move-min.move+1)\r\n\t\t\tupdate.indx <- which(z!=0)\r\n\t\t\tif (max(indx>1)){\r\n\t\t\t\tif (Method==\"Gibbs\"){\r\n\t\t\t\t\tif (Model!=\"Uniform\") x.matrix <- round(t(mapply(seq,from=x.min[update.indx],by=z[update.indx],length.out=max.move-min.move+1)))\r\n\t\t\t\t\tif (Model==\"Poisson\") {\r\n\t\t\t\t\t\tlog.probs <- colSums(dpois(x.matrix,lambda[update.indx],log=T))\r\n\t\t\t\t\t\tprobs <- exp(log.probs-max(log.probs))\r\n\t\t\t\t\t\tx <- x.min + sample(indx-1,size=1,prob=probs)*z\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Model==\"NegBin\"){\r\n\t\t\t\t\t\tlog.probs <- colSums(dnbinom(x.matrix,mu=lambda[update.indx],size=lambda[update.indx]/NB.alpha,log=T))\r\n\t\t\t\t\t\tprobs <- exp(log.probs-max(log.probs)) \r\n\t\t\t\t\t\tx <- x.min + sample(indx-1,size=1,prob=probs)*z\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Model==\"Uniform\") x <- x.min+sample(indx-1,size=1)*z\r\n\t\t\t\t}\r\n\t\t\t\tif (Method==\"MH\"){\r\n\t\t\t\t\tif (Proposal==\"Unif\") move.length <- sample(min.move:max.move,1)\r\n\t\t\t\t\tif (Proposal==\"NonUnif\"){\r\n\t \t\t\tif (Model==\"Poisson\") {\r\n\t\t\t\t\t\t\taa <- x[n+j]+z[n+j]*min.move\r\n\t\t\t\t\t\t\tbb <- x[n+j]+z[n+j]*max.move\r\n\t\t\t\t\t\t\tmove.length <- (rtpois(1,lambda=lambda[n+j],a=aa-0.5,b=bb)-x[n+j])/z[n+j]\r\n\t\t\t\t\t\t\t}\r\n\t \t\t\tif (Model==\"NegBin\") move.length <- sample(min.move:max.move,1,prob=dnbinom((x[n+j]+z[n+j]*min.move):(x[n+j]+z[n+j]*max.move),mu=lambda[n+j],size=lambda[n+j]/NB.alpha)) \t\t\t\r\n\t\t\t\t\t\tif (Model==\"Normal\") move.length <- rtnorm(1,lambda[n+j],sd=sqrt((1+NB.alpha)*lambda[n+j]),lower=x[n+j]+z[n+j]*min.move,upper=x[n+j]+z[n+j]*max.move)\r\n\t\t\t\t\t} \r\n\t\t\t\t\tx.cand <- x + z*move.length\r\n\t\t\t\t\tif (Model==\"Poisson\"){\r\n\t\t\t\t\t\tL <- sum(dpois(x[update.indx],lambda[update.indx],log=T))\r\n\t\t\t\t\t\tL.cand <- sum(dpois(x.cand[update.indx],lambda[update.indx],log=T))\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Model==\"NegBin\"){\r\n\t\t\t\t\t\tL <- sum(dnbinom(x[update.indx],mu=lambda[update.indx],size=lambda[update.indx]/NB.alpha,log=T))\r\n\t\t\t\t\t\tL.cand <- sum(dnbinom(x.cand[update.indx],mu=lambda[update.indx],size=lambda[update.indx]/NB.alpha,log=T))\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Model==\"Normal\"){\r\n\t\t\t\t\t\tL <- sum(dnorm(x[update.indx],mean=lambda[update.indx],sd=sqrt((1+NB.alpha)*lambda[update.indx]),log=T))\r\n\t\t\t\t\t\tL.cand <- sum(dnorm(x.cand[update.indx],mean=lambda[update.indx],sd=sqrt((1+NB.alpha)*lambda[update.indx]),log=T))\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Proposal==\"Unif\") acc.prob <- exp(L.cand - L)\r\n\t\t\t\t\tif (Proposal==\"NonUnif\"){\r\n\t \t\t\t\tif (Model==\"Poisson\"){\r\n\t\t\t\t\t\t\tq.can <- dpois(x.cand[n+j],lambda[n+j],log=T) \r\n\t\t\t\t\t\t\tq.cur <- dpois(x[n+j],lambda[n+j],log=T)\r\n\t\t\t\t\t\t}\r\n\t \t\t\t\tif (Model==\"NegBin\"){\r\n\t\t\t\t\t\t\tq.can <- dnbinom(x.cand[n+j],mu=lambda[n+j],size=lambda[n+j]/NB.alpha,log=T) \r\n\t\t\t\t\t\t\tq.cur <- dnbinom(x[n+j],mu=lambda[n+j],size=lambda[n+j]/NB.alpha,log=T)\r\n\t\t\t\t\t\t}\r\n \t\t\t\t\t\tif (Model==\"Normal\") {\r\n\t\t\t\t\t\t\tq.can <- dnorm(x.cand[n+j],lambda[n+j],sqrt((1+NB.alpha)*lambda[n+j]),log=T) \r\n\t\t\t\t\t\t\tq.cur <- dnorm(x[n+j],lambda[n+j],sqrt((1+NB.alpha)*lambda[n+j]),log=T)\r\n\t\t\t\t\t\t} \r\n\t\t\t \t\t\tacc.prob <- exp(L.cand - L + q.cur - q.can)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (is.na(acc.prob)) acc.prob <- 0\r\n\t\t\t\t\tif (runif(1) < acc.prob) x <- x.cand\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (tune.par > 0){\r\n \tlambda.star <- rnorm(r,mean=lambda,sd=tune.par*lambda)\r\n\t\t\t\tii <- sample(1:n,1)\r\n\t\t\t\tswap.indx <- abs(C[ii,])>tol\r\n\t\t\t\tif (any(swap.indx)){\r\n\t\t\t\t\tjj <- sample((1:(r-n))[swap.indx],1)\r\n\t\t\t\t\tif (lambda.star[ii] <= lambda.star[jj+n]/abs(C[ii,jj])){\r\n\t\t\t\t\tei <- rep(0,n)\r\n \t\t\t\t\tej <- rep(0,r-n)\r\n\t\t\t\t\tei[ii] <- 1\r\n\t\t\t\t\tej[jj] <- 1\r\n\t\t\t\t\tdA1 <- round(C[ii,jj]*dA1)\r\n\t\t\t\t\tC <- C - outer(C[,jj]-ei,C[ii,]+ej)/C[ii,jj]\r\n\t\t\t\t\tU <- rbind(-C,diag(r-n))\r\n\t\t\t\t\tx.order[c(ii,jj+n)] <- x.order[c(jj+n,ii)]\r\n\t\t\t\t\tx[c(ii,jj+n)] <- x[c(jj+n,ii)]\r\n \t\t\t\t\tlambda[c(ii,jj+n)] <- lambda[c(jj+n,ii)]\r\n \t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tX[x.order,1+(iter-1)*m+j] <- x\r\n\t\t\tif (verbose==1) X.ORDER[,1+(iter-1)*m+j] <- x.order\r\n\t\t}\r\n\t}\r\n\tif (verbose==1) x.order <- X.ORDER\r\n\tlist(X=X[,seq(1,ncol(X),by=THIN)],x.order=x.order)\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "5c8a4a5daa55903619c1d91e562e53618bf9e67e", "size": 8359, "ext": "r", "lang": "R", "max_stars_repo_path": "R/x-sampler.r", "max_stars_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_stars_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "max_stars_repo_licenses": ["MIT"], "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/x-sampler.r", "max_issues_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_issues_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "max_issues_repo_licenses": ["MIT"], "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/x-sampler.r", "max_forks_repo_name": "MartinLHazelton/DynamicLatticeBasis", "max_forks_repo_head_hexsha": "6c9a134acf398c4e80f06f8e837d4298efedca4c", "max_forks_repo_licenses": ["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.9947368421, "max_line_length": 361, "alphanum_fraction": 0.5972006221, "num_tokens": 2720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5984577139328181}} {"text": "# Computes the Kullback-Leibler divergence based on kernel density\n# estimates with Gaussian kernel\n\nkld_d = function(x,y,...){\n \n integrand = function(x,y,t){\n denx = density(x, na.rm = T)\n deny = density(y, na.rm = T)\n f.x = approx(denx$x,denx$y,t)$y\n f.y = approx(deny$x,deny$y,t)$y\n tmpRatio = f.x *(log2(f.x) - log2(f.y))\n tmpRatio = ifelse(is.infinite(tmpRatio),0,ifelse(is.na(tmpRatio),0,tmpRatio))\n tmpRatio\n }\n integrate(integrand,-Inf,Inf,x = x,y = y,stop.on.error=FALSE)$value\n \n}\n\n", "meta": {"hexsha": "7bef42679df570b63373867a05ed1305fbdb5d05", "size": 521, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/r/kld_d.r", "max_stars_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_stars_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/r/kld_d.r", "max_issues_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_issues_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/r/kld_d.r", "max_forks_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_forks_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4210526316, "max_line_length": 81, "alphanum_fraction": 0.6353166987, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5983862107912798}} {"text": "#########################################################################################################\r\n# Empirical Application Codes of\r\n# \r\n# \"Threshold Unit Root Tests with Smooth Transitions\"\r\n# \r\n# written by \r\n# \r\n# Dr. Mehmet ÖZCAN\r\n# mehmetozcan@kmu.edu.tr\r\n#\r\n# *NOTES*\r\n# 1) Caner & Hansen (2001) Threshold Unit Root test and Threshold Effect test\r\n# programs are taken from Hansen's web page http://www.ssc.wisc.edu/~bhansen/ .\r\n# However, unit root test program are adjusted to test unit root null hypothesis \r\n# without any deterministic component.\r\n#\r\n# 2) There are two indicator which come from Caner & Hansen (2001)'s codes. Caner &\r\n# Hansen investigate different type of threshol variable type and different trimming\r\n# intervals. In this study, lagged difference threshold variable and [0.15, 0.85] \r\n# trimming interval are used for all simulation experiments and empirical application.\r\n# \r\n# thresh Type of threshold variable\r\n# \t\t 1 for long difference, z(t-1)=y(t-1)-y(t-(m-1))\r\n# \t\t 2 for lagged difference, z(t-1)=y(t-m)-y(t-m-1)\r\n# \t\t 3 for lagged level, z(t-1)=y(t-m)\r\n# trim Trimming Range (normalized threshold, lambda)\r\n# \t\t 1 for [.15,.85]\r\n# \t \t 2 for [.10,.90]\r\n# \t\t 3 for [.05,.95]\r\n# \r\n# 3) Results are printed to the screen.\r\n#\r\n# 4) All steps of application process are explained below. Please check them before run the codes.\r\n#\r\n# *Instructions*\r\n#\r\n# 1) First, please install required R packcages stated in PART-1\r\n# 2) Run all codes in PART-1\r\n# 3) Before run PART-2, please chose working directory folder that contains your \"data.txt\" file.\r\n# 4) PART-2 codes analyse both the USA's and Turkey's data. Threfore, before analyse your data try\r\n# data of this study. It could be found at \"data.txt\" file in same repository of Dr. Özcan's GitHub page.\r\n#\r\n#\r\n#\r\n#########################################################################################################\r\n# PART -1 \r\n#########################################################################################################\r\n# Required Packcages \r\nlibrary(nloptr)\r\nlibrary(zoo)\r\n# Required Functions\r\n#########################################################################################################\r\n# Starting value estimation for LNV(1998) Models (A, B & C) #\r\nstartLNV<-function(dta){\r\ntt<-length(dta)\r\ntr<-as.matrix(c(1:tt))\r\ncc<-as.matrix(rep(1,tt))\r\n\r\ntauGs<-c()\r\nfor(kk in 1:tt){ tauGs[kk]<-(kk/tt) }\r\ngamaGs<-seq(1,10,1)\r\n\r\nSSRA<-matrix(0,length(tauGs),length(gamaGs))\r\nSSRB<-matrix(0,length(tauGs),length(gamaGs))\r\nSSRC<-matrix(0,length(tauGs),length(gamaGs))\r\n\r\nfor(vk in 1:3){\r\nfor(vi in 1:(length(gamaGs))){\r\nfor(vj in 1:(length(tauGs))){\r\nst<-as.matrix((1/(1+exp(-(gamaGs[vi])*((tr)-(tauGs[vj]*tt))))))\r\nif(vk==1){X<-as.matrix(cbind(cc,st))}\r\nif(vk==2){X<-as.matrix(cbind(cc,tr,st))}\r\nif(vk==3){X<-as.matrix(cbind(cc,tr,st,(tr*st)))} \r\nXX<-(MASS:::ginv(t(X)%*%X, tol=1e-25))\r\nbetas<-XX%*%(t(X)%*%dta)\r\nYhat<-t((t(betas)%*%t(X)))\r\nehat<-(dta-Yhat)\r\nif(vk==1){SSRA[vj,vi]<-sum((ehat)^2)}\r\nif(vk==2){SSRB[vj,vi]<-sum((ehat)^2)}\r\nif(vk==3){SSRC[vj,vi]<-sum((ehat)^2)} \r\n}\r\n}\r\n}\r\n\r\nfor(vs in 1:3){\r\nif(vs==1){posA<-which(SSRA == min(SSRA), arr.ind = TRUE);\r\nst<-as.matrix((1/(1+exp(-(gamaGs[posA[2]])*((tr)-(tauGs[posA[1]]*tt))))));\r\nX<-as.matrix(cbind(cc,st))}\r\nif(vs==2){posB<-which(SSRB == min(SSRB), arr.ind = TRUE);\r\nst<-as.matrix((1/(1+exp(-(gamaGs[posB[2]])*((tr)-(tauGs[posB[1]]*tt))))));\r\nX<-as.matrix(cbind(cc,tr,st))}\r\nif(vs==3){posC<-which(SSRC == min(SSRC), arr.ind = TRUE);\r\nst<-as.matrix((1/(1+exp(-(gamaGs[posC[2]])*((tr)-(tauGs[posC[1]]*tt))))));\r\nX<-as.matrix(cbind(cc,tr,st,(tr*st)))}\r\n\r\nXX<-(MASS:::ginv(t(X)%*%X, tol=1e-25))\r\n\r\nif(vs==1){betasA<-XX%*%(t(X)%*%dta);\r\nbetasA<-rbind(betasA,gamaGs[posA[2]],tauGs[posA[1]])}\r\nif(vs==2){betasB<-XX%*%(t(X)%*%dta);\r\nbetasB<-rbind(betasB,gamaGs[posB[2]],tauGs[posB[1]])}\r\nif(vs==3){betasC<-XX%*%(t(X)%*%dta);\r\nbetasC<-rbind(betasC,gamaGs[posC[2]],tauGs[posC[1]])}\r\n}\r\nlist(betasA=betasA, betasB=betasB, betasC=betasC)\r\n}\r\n#########################################################################################################\r\n# LNV(1998) Models (A, B & C) Estimation with Sequential Quadratic Programing\r\nestLNV<-function(yt, X, b0a, b0b, b0c){\r\ntt<-length(yt)\r\nstabA<-function(b){sum((yt-(b[1]*X[,1]+b[2]*(1/(1+exp(-(b[3])*((X[,2])-b[4]*tt))))))^2)}\r\nstabB<-function(b){sum((yt-(b[1]*X[,1]+b[2]*X[,2]+b[3]*(1/(1+exp(-(b[4])*((X[,2])-b[5]*tt))))))^2)}\r\nstabC<-function(b){sum((yt-(b[1]*X[,1]+b[2]*X[,2]+b[3]*(1/(1+exp(-(b[5])*((X[,2])-b[6]*tt))))+\r\nb[4]*(X[,2])*(1/(1+exp(-(b[5])*((X[,2])-b[6]*tt))))))^2)}\r\n\r\nlba<-c(-Inf,-Inf,0,0)\r\nuba<-c(Inf,Inf,Inf,1)\r\n\r\nlbb<-c(-Inf,-Inf,-Inf,0,0)\r\nubb<-c(Inf,Inf,Inf,Inf,1)\r\n\r\nlbc<-c(-Inf,-Inf,-Inf,-Inf,0,0)\r\nubc<-c(Inf,Inf,Inf,Inf,Inf,1)\r\n\r\nSA<-nloptr:::slsqp(b0a,fn=stabA,lower=lba,upper=uba, control=list(xtol_rel=1e-25))\r\nSB<-nloptr:::slsqp(b0b,fn=stabB,lower=lbb,upper=ubb, control=list(xtol_rel=1e-25))\r\nSC<-nloptr:::slsqp(b0c,fn=stabC,lower=lbc,upper=ubc, control=list(xtol_rel=1e-25))\r\n\r\nstaba<-function(b){(b[1]*X[,1]+b[2]*(1/(1+exp(-(b[3])*((X[,2])-b[4]*tt)))))}\r\nyhatA<-staba(SA$par)\r\n\r\nstabb<-function(b){b[1]*X[,1]+b[2]*X[,2]+b[3]*(1/(1+exp(-(b[4])*((X[,2])-b[5]*tt))))}\r\nyhatB<-stabb(SB$par)\r\n\r\nstabc<-function(b){(b[1]*X[,1]+b[2]*X[,2]+b[3]*(1/(1+exp(-(b[5])*((X[,2])-b[6]*tt))))+\r\nb[4]*(X[,2])*(1/(1+exp(-(b[5])*((X[,2])-b[6]*tt)))))}\r\nyhatC<-stabc(SC$par)\r\n\r\nlist(ehat=as.matrix(cbind((yt-yhatA),(yt-yhatB),(yt-yhatC))), yhat=as.matrix(cbind(yhatA,yhatB,yhatC)),BetaA=as.matrix(SA$par),BetaB=as.matrix(SB$par),BetaC=as.matrix(SC$par))\r\n}\r\n#########################################################################################################\r\n# ADF Estimator\r\nlinear<-function(dat,p,cons,trend){\r\n t <- nrow(dat)\r\n n <- t - 1 - p\r\n dy <- as.matrix(dat[2:t]-dat[1:(t-1)])\r\n y <- as.matrix(dy[(1+p):(t-1)])\r\n x <- cbind(dat[(1+p):(t-1)], dy[p:(t-2)])\r\n\r\n if(p>=2){for (k in 2:p) x <- cbind(x,dy[(p+1-k):(t-1-k)])}\r\n if(cons==1 & trend==0) x <- cbind(rep(1,n), x)\r\n if(cons==1 & trend==1) x <- cbind(rep(1,n),seq(1,n,1),x)\r\n\r\n kx <- ncol(x)\r\n xx <- solve(t(x)%*%x, tol=1e-25)\r\n bols <- xx%*%(t(x)%*%y) \r\n eols <- y - x%*%bols\r\n sols <- t(eols)%*%eols\r\n sigols <- sols/(n-kx)\r\n seols <- sqrt(diag(xx)%*%sigols)\r\n rho <- bols[1+cons+trend]\r\n tadf <- rho/seols[1+cons+trend]\r\n ar0 <- as.matrix(bols[(cons+trend+2):(cons+trend+1+p)])\r\n bic<-log((sum(eols^2))/t)+(length(bols)*(log(t)/t))\r\n aic<-log((sum(eols^2))/t)+(length(bols)*(2/t))\r\n list(ar0=ar0,eols=eols,aic=aic,bic=bic,tadf=tadf,rho=rho)\r\n}\r\n#########################################################################################################\r\n# Caner & Hansen (2001) Estimator\r\ntur_est2 <- function(dat,p,mmin,mmax,m,constant,trend){\r\n t <- nrow(dat)\r\n n <- t - 1 - p\r\n mn <- mmax-mmin+1\r\n ms <- as.matrix(seq(mmin,mn,1))\r\n dy <- as.matrix(dat[2:t]-dat[1:(t-1)])\r\n y <- as.matrix(dy[(1+p):(t-1)])\r\n if(constant==1) x <- matrix(1,n,1)\r\n if (trend==1) x <- cbind(x,as.matrix(seq(1,n,1)))\r\n if(constant==1){x <- cbind(x,dat[(1+p):(t-1)],dy[p:(t-2)])}else{\r\n x <- cbind(dat[(1+p):(t-1)],dy[p:(t-2)])}\r\n if(p>1) for (ki in 2:p) x <- cbind(x,dy[(p+1-ki):(t-1-ki)])\r\n\r\n if (sum(coef)==0){\r\n xi_ns <- as.matrix(seq(1,p,1)+1+constant+trend)\r\n }else{\r\n idex <- colSums(as.matrix(coef%*%matrix(1,1,p))==(matrix(1,nrow(coef),1)%*%seq(1,p,1)))\r\n xi_ns <- seq(1,p,1)\r\n xi_ns <- as.matrix(xi_ns[idex==0]+1+constant+trend)\r\n }\r\n\r\n if (trend==0){\r\n if(constant==0){\r\n\t if (sum(coef)==0){\r\n xi_s <- rbind(1)\r\n }else{xi_s <- rbind(1,(coef+1))\r\n }\r\n }\r\n }\r\n if (trend==0){\r\n if(constant==1){\r\n\t if (sum(coef)==0){\r\n xi_s <- rbind(1,2)\r\n }else{\r\n xi_s <- rbind(1,2,(coef+2))\r\n }\r\n }\r\n }\r\n if (trend==1){\r\n if(constant==1){\r\n\t if (sum(coef)==0){\r\n xi_s <- rbind(1,2,3)\r\n }else{\r\n xi_s <- rbind(1,2,3,(coef+3))\r\n }\r\n }\r\n } \r\n xs <- as.matrix(x[,xi_s])\r\n xns <- as.matrix(x[,xi_ns])\r\n if (thresh==1){\r\n qs <- dat[(1+p):(t-1)]-dat[(1+p-mmin):(t-1-mmin)]\r\n qs <- as.matrix(qs)\r\n if(p>1){\r\n\t for (mi in (mmin+1):mmax){\r\n qs <- cbind(qs,(dat[(1+p):(t-1)]-dat[(1+p-mi):(t-1-mi)]))\r\n }\r\n\t }\r\n }\r\n if (thresh==2){\r\n qs <- dat[(1+p-mmin+1):(t-1-mmin+1)]-dat[(1+p-mmin):(t-1-mmin)]\r\n qs <- as.matrix(qs)\r\n if(p>1){\r\n\t for (mi in (mmin+1):mmax){\r\n qs <- cbind(qs,(dat[(1+p-mi+1):(t-1-mi+1)]-dat[(1+p-mi):(t-1-mi)]))\r\n }\r\n\t }\r\n }\r\n if (thresh==3){\r\n qs <- dat[(1+p-mmin+1):(t-mmin)]\r\n qs <- as.matrix(qs)\r\n if(p>1){\r\n\t for (mi in (mmin+1):mmax){\r\n qs <- cbind(qs,(dat[(1+p-mi+1):(t-mi)]))\r\n }\r\n\t }\r\n }\r\n kx <- ncol(x)\r\n ks <- nrow(coef)+1+constant+trend\r\n xx <- solve(t(x)%*%x, tol=1e-25)\r\n bols <- xx%*%(t(x)%*%y) \r\n eols <- y - x%*%bols\r\n sols <- t(eols)%*%eols\r\n wwss <- matrix(0,mn,1)\r\n smins <- matrix(0,mn,1)\r\n lams <- matrix(0,mn,1)\r\n ws <- matrix(0,mn,1)\r\n r1 <- matrix(0,mn,1)\r\n r2 <- matrix(0,mn,1)\r\n t1 <- matrix(0,mn,1)\r\n t2 <- matrix(0,mn,1)\r\n rur <- rbind(1,(ks+1))+trend+constant\r\n indx <- 1:(n)\r\n pi1 <-.2-.05*trim\r\n pi2 <-.8+.05*trim\r\n for (mi in 1:mn){\r\n q <- qs[,mi]\r\n qq <- unique(q)\r\n qq <- as.matrix(sort(qq))\r\n qq <- as.matrix(qq[(floor(n*pi1)+1):(ceiling(n*pi2)-1)])\r\n qn <- nrow(qq)\r\n s <- matrix(0,qn,1)\r\n wws<- matrix(0,qn,1)\r\n for (qi in 1:qn){\r\n d1 <- as.matrix((qlam)\r\nlist(mhat=mhat,lam=lam,e=e,bs_s=bs_s,ar01=ar01,ar02=ar02,b1=b1,b2=b2,r1=r1,r2=r2,t1=t1,t2=t2,ts=ts,ws=ws,w=w,\r\nwws=wws, wwss=wwss,leng=leng,vd=vd)\r\n}\r\n# Caner & Hansen (2001) Threshold Effect Wald Test Bootstrap p-values\r\npvWald<-function(dat,p,ar0,eols,rho,boot,w){\r\nt <- nrow(dat)\r\nn <- t - 1 - p\r\ny0 <- dat-mean(dat)\r\ny0 <- as.matrix(y0[1:(1+p)])\r\naa <- matrix(0,p+1,1)\r\naa[1] <- 1 + rho\r\naa[1:p] <- aa[1:p] + ar0\r\naa[2:(p+1)] <- aa[2:(p+1)] - ar0\r\nbootw <- matrix(0,boot,1)\r\nfor (ib in 1:boot){\r\n eols_c <- as.matrix(eols[ceiling(runif(t)*n)])\r\n datb <- y0\r\nfor (i in (nrow(y0)+1):(nrow(eols_c))){\r\n datbb <- eols_c[i]\r\n for (j in 1:nrow(y0)) datbb <- datbb + aa[j]*datb[(i-j)]\r\n datb <- rbind(datb,datbb)\r\n }\r\nout <- tur_est2(datb,p,1,p,0,0,0) \r\nbootw[ib] <- out$w\r\n}\r\npw <- mean(bootw > w)\r\ncbind(w,pw)\r\n}\r\n\r\n#########################################################################################################\r\n# 5% Criticals T=200\r\nR1A <- 20.82907\r\nR2A <- 21.07073\r\nR1B <- 26.67934\r\nR2B <- 26.80033\r\nR1C <- 29.65022\r\nR2C <- 29.69269\r\nLNVa<- -4.161\r\nLNVb<- -4.629\r\nLNVc<- -4.867\r\nADFm<- -2.8759 \r\nADFt<- -3.4326 # MacKinnon (1991) based Critical value\r\n\r\n#########################################################################################################\r\n# PART - 2\r\n#########################################################################################################\r\n# Aplication\r\n# select working directory file.\r\n# setwd(\"your folder directory\") \r\n# read data\r\nD <- read.table(\"data.txt\")\r\ntri <- D[,1]\r\nusi <- D[,2]\r\n# logarithms\r\ntri <-as.matrix(log(tri))\r\nusi <-as.matrix(log(usi))\r\n# estimation parameter of LNV smooth transition functions \r\ntr <-as.matrix(c(1:length(tri)))\r\ncc <-as.matrix(rep(1,length(tri)))\r\nX <-as.matrix(cbind(cc,tr))\r\nSLNVtr<- startLNV(tri)\r\nSLNVus<- startLNV(usi)\r\nb0atr <- SLNVtr$betasA; b0btr <- SLNVtr$betasB; b0ctr <- SLNVtr$betasC\r\nb0aus <- SLNVus$betasA; b0bus <- SLNVus$betasB; b0cus <- SLNVus$betasC\r\n\r\nELNVtr<- estLNV(tri, X, b0atr, b0btr, b0ctr)\r\nELNVus<- estLNV(usi, X, b0aus, b0bus, b0cus)\r\nYtr <- as.matrix(ELNVtr$yhat)\r\nYus <- as.matrix(ELNVus$yhat)\r\nDtr <- as.matrix(ELNVtr$ehat)\r\nDus <- as.matrix(ELNVus$ehat)\r\n# plots\r\n# TR\r\npar(mfrow=c(3,1))\r\nplot(ts(Ytr[,1], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model A\",ylim=c(min(tri),max(tri)))\r\nmtext(side=3,text=paste(\"industrial production and fitted smooth transition for Turkey\"),line=2.5,lwd=2,cex=1)\r\nlines(ts(tri, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(tri),1),round(max(tri),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(tri),1),round(max(tri),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\nplot(ts(Ytr[,2], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model B\",ylim=c(min(tri),max(tri)))\r\nlines(ts(tri, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(tri),1),round(max(tri),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(tri),1),round(max(tri),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\nplot(ts(Ytr[,3], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model C\",ylim=c(min(tri),max(tri)))\r\nlines(ts(tri, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(tri),1),round(max(tri),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(tri),1),round(max(tri),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\n\r\n# US\r\npar(mfrow=c(3,1))\r\nplot(ts(Yus[,1], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model A\",ylim=c(min(usi),max(usi)))\r\nmtext(side=3,text=paste(\"industrial production and fitted smooth transition for USA\"),line=2.5,lwd=2,cex=1)\r\nlines(ts(usi, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(usi),1),round(max(usi),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(usi),1),round(max(usi),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\nplot(ts(Yus[,2], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model B\",ylim=c(min(usi),max(usi)))\r\nlines(ts(usi, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(usi),1),round(max(usi),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(usi),1),round(max(usi),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\nplot(ts(Yus[,3], start=c(2004,1),frequency=12),lty=2,axes=FALSE,lwd=2,col=\"black\",ylab=NA,xlab=\"Years\",main=\"Model C\",ylim=c(min(usi),max(usi)))\r\nlines(ts(usi, start=c(2004,1), frequency=12),lty=1, lwd=2, col=\"gray42\")\r\naxis(1, at=c(2004:2020), labels=c(2004:2020),las=3, gap.axis=0.1)\r\naxis(2, at = seq(round(min(usi),1),round(max(usi),1),0.1),lwd=1.5)\r\nabline(v=(seq(2004,2020,1)), col=\"lightgray\", lty=\"dotted\")\r\nabline(h=seq(round(min(usi),1),round(max(usi),1),0.1), col=\"lightgray\", lty=\"dotted\")\r\n\r\n# Extraction of Estimated Data\r\n# write.table(as.matrix(cbind(tri,Ytr[,1],Ytr[,2],Ytr[,3])),\"TRest.txt\",row.names=FALSE,col.names=FALSE)\r\n# write.table(as.matrix(cbind(usi,Yus[,1],Yus[,2],Yus[,3])),\"USest.txt\",row.names=FALSE,col.names=FALSE)\r\n\r\n# ADF Test\r\nmaxp<- 10\r\nBIC <- matrix(0,maxp,2) \r\nfor(i in 1:maxp){\r\nadftr <- linear(as.matrix(tri),i,1,1)\r\nadfus <- linear(as.matrix(usi),i,1,1)\r\nBIC[i,1]<-adftr$bic\r\nBIC[i,2]<-adfus$bic\r\n}\r\nptr <- which.min(BIC[,1])\r\npus <- which.min(BIC[,2])\r\n\r\nadftr0 <- linear(as.matrix(tri),ptr,1,1)\r\nadfus0 <- linear(as.matrix(usi),pus,1,1)\r\n\r\n# LNV Test\r\nBICL <- matrix(0,maxp,6) \r\nfor(i in 1:maxp){\r\nadftra <- linear(as.matrix(Dtr[,1]),i,1,1)\r\nadftrb <- linear(as.matrix(Dtr[,2]),i,1,1)\r\nadftrc <- linear(as.matrix(Dtr[,3]),i,1,1)\r\n\r\nadfusa <- linear(as.matrix(Dus[,1]),i,1,1)\r\nadfusb <- linear(as.matrix(Dus[,2]),i,1,1)\r\nadfusc <- linear(as.matrix(Dus[,3]),i,1,1)\r\n\r\nBICL[i,1]<-adftra$bic; BICL[i,2]<-adftrb$bic; BICL[i,3]<-adftrc$bic;\r\nBICL[i,4]<-adfusa$bic; BICL[i,5]<-adfusb$bic; BICL[i,6]<-adfusc$bic\r\n}\r\nptra <- which.min(BICL[,1]); ptrb <- which.min(BICL[,2]); ptrc <- which.min(BICL[,3]);\r\npusa <- which.min(BICL[,4]); pusb <- which.min(BICL[,5]); pusc <- which.min(BICL[,6]);\r\nPLNV <-cbind(ptra,ptrb,ptrc,pusa,pusb,pusc)\r\n\r\nadftrA <- linear(as.matrix(Dtr[,1]),ptra,1,1)\r\nadftrB <- linear(as.matrix(Dtr[,2]),ptrb,1,1)\r\nadftrC <- linear(as.matrix(Dtr[,3]),ptrc,1,1)\r\n\r\nadfusA <- linear(as.matrix(Dus[,1]),pusa,1,1)\r\nadfusB <- linear(as.matrix(Dus[,2]),pusb,1,1)\r\nadfusC <- linear(as.matrix(Dus[,3]),pusc,1,1)\r\n\r\n# Caner & Hansen (2001) Test with Smooth Transition\r\n# Caner & Hansen (2001) TAR Model Estimation Settings \r\nthresh <- 2 \r\ntrim <- 1 \r\n#\r\nMAXR <- matrix(0,maxp,6)\r\nfor(i in 1:maxp){\r\ncoef <- matrix(c(1:i),i,1)\r\ntarAtr <-tur_est2(as.matrix(Dtr[,1]),i,1,i,0,0,0)\r\ntarBtr <-tur_est2(as.matrix(Dtr[,2]),i,1,i,0,0,0)\r\ntarCtr <-tur_est2(as.matrix(Dtr[,3]),i,1,i,0,0,0)\r\n\r\ntarAus <-tur_est2(as.matrix(Dus[,1]),i,1,i,0,0,0)\r\ntarBus <-tur_est2(as.matrix(Dus[,2]),i,1,i,0,0,0)\r\ntarCus <-tur_est2(as.matrix(Dus[,3]),i,1,i,0,0,0)\r\n\r\nMAXR[i,1]<-tarAtr$r1[tarAtr$mhat]; MAXR[i,2]<-tarBtr$r1[tarBtr$mhat]; MAXR[i,3]<-tarCtr$r1[tarCtr$mhat];\r\nMAXR[i,4]<-tarAus$r1[tarAus$mhat]; MAXR[i,5]<-tarBus$r1[tarBus$mhat]; MAXR[i,6]<-tarCus$r1[tarCus$mhat]\r\n}\r\nptrA <- which.max(MAXR[,1]); ptrB <- which.max(MAXR[,2]); ptrC <- which.max(MAXR[,3]);\r\npusA <- which.max(MAXR[,4]); pusB <- which.max(MAXR[,5]); pusC <- which.max(MAXR[,6]);\r\nPLCH <- cbind(ptrA,ptrB,ptrC,pusA,pusB,pusC)\r\n\r\ncoef <- matrix(c(1:ptrA),ptrA,1)\r\ntartrA <- tur_est2(as.matrix(Dtr[,1]),ptrA,1,ptrA,0,0,0)\r\ncoef <- matrix(c(1:ptrB),ptrB,1)\r\ntartrB <- tur_est2(as.matrix(Dtr[,2]),ptrB,1,ptrB,0,0,0)\r\ncoef <- matrix(c(1:ptrC),ptrC,1)\r\ntartrC <- tur_est2(as.matrix(Dtr[,3]),ptrC,1,ptrC,0,0,0)\r\n\r\ncoef <- matrix(c(1:pusA),pusA,1)\r\ntarusA <- tur_est2(as.matrix(Dus[,1]),pusA,1,pusA,0,0,0)\r\ncoef <- matrix(c(1:pusB),pusB,1)\r\ntarusB <- tur_est2(as.matrix(Dus[,2]),pusB,1,pusB,0,0,0)\r\ncoef <- matrix(c(1:pusC),pusC,1)\r\ntarusC <- tur_est2(as.matrix(Dus[,3]),pusC,1,pusC,0,0,0)\r\n\r\n# Caner & Hansen (2001) Threshold Effect test statistics and p-values #\r\nset.seed(12345)\r\nboot<-1000\r\n# Turkey\r\ncoef <- matrix(c(1:ptrA),ptrA,1)\r\nlnWAtr <- linear(as.matrix(Dtr[,1]),ptrA,0,0)\r\npvalAtr <- pvWald(as.matrix(Dtr[,1]),ptrA,lnWAtr$ar0,lnWAtr$eols,lnWAtr$rho,boot,tartrA$w)\r\ncoef <- matrix(c(1:ptrB),ptrB,1)\r\nlnWBtr <- linear(as.matrix(Dtr[,2]),ptrB,0,0)\r\npvalBtr <- pvWald(as.matrix(Dtr[,2]),ptrB,lnWBtr$ar0,lnWBtr$eols,lnWBtr$rho,boot,tartrB$w)\r\ncoef <- matrix(c(1:ptrC),ptrC,1)\r\nlnWCtr <- linear(as.matrix(Dtr[,3]),ptrC,0,0)\r\npvalCtr <- pvWald(as.matrix(Dtr[,3]),ptrC,lnWCtr$ar0,lnWCtr$eols,lnWCtr$rho,boot,tartrC$w)\r\n# USA\r\ncoef <- matrix(c(1:pusA),pusA,1)\r\nlnWAus <- linear(as.matrix(Dus[,1]),pusA,0,0)\r\npvalAus <- pvWald(as.matrix(Dus[,1]),pusA,lnWAus$ar0,lnWAus$eols,lnWAus$rho,boot,tarusA$w)\r\ncoef <- matrix(c(1:pusB),pusB,1)\r\nlnWBus <- linear(as.matrix(Dus[,2]),pusB,0,0)\r\npvalBus <- pvWald(as.matrix(Dus[,2]),pusB,lnWBus$ar0,lnWBus$eols,lnWBus$rho,boot,tarusB$w)\r\ncoef <- matrix(c(1:pusC),pusC,1)\r\nlnWCus <- linear(as.matrix(Dus[,3]),pusC,0,0)\r\npvalCus <- pvWald(as.matrix(Dus[,3]),pusC,lnWCus$ar0,lnWCus$eols,lnWCus$rho,boot,tarusC$w)\r\n\r\n\r\n# Tables\r\ntrit<-ts(diff(tri,1),start<-c(2004,2),frequency=12)\r\nusit<-ts(diff(usi,1),start<-c(2004,2),frequency=12)\r\nntr <-length(tri)\r\nnus <-length(usi)\r\nprintlog<-function(tri,usi){\r\ncat (\"\\n\")\r\ncat (\"Parameter Estimation Result of Smooth Transition for Industrial Production Index of Turkey\" , \"\\n\")\r\ncat (\"Number of Observations:\", ntr , \"\\n\")\r\ncat (\"Optimization : Sequential Quadratic Programming\" , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(trit))[round((ELNVtr$BetaA[4]*ntr))])\r\ncat (\"Mid Point Tau :\", ELNVtr$BetaA[4] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVtr$BetaA[3] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(trit))[round((ELNVtr$BetaB[5]*ntr))])\r\ncat (\"Mid Point Tau :\", ELNVtr$BetaB[5] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVtr$BetaB[4] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(trit))[round((ELNVtr$BetaC[6]*ntr))])\r\ncat (\"Mid Point Tau :\", ELNVtr$BetaC[6] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVtr$BetaC[5] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"*******************************************************************************************\", \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Parameter Estimation Result of Smooth Transition for Industrial Production Index of USA\" , \"\\n\")\r\ncat (\"Number of Observations:\", nus , \"\\n\")\r\ncat (\"Optimization : Sequential Quadratic Programming\" , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(usit))[round((ELNVus$BetaA[4]*nus))])\r\ncat (\"Mid Point Tau :\", ELNVus$BetaA[4] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVus$BetaA[3] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(usit))[round((ELNVus$BetaB[5]*nus))])\r\ncat (\"Mid Point Tau :\", ELNVus$BetaB[5] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVus$BetaB[4] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Mid Point Date\" , \"\\n\")\r\ncat (\"--------------\" , \"\\n\")\r\nprint(as.yearmon(time(usit))[round((ELNVus$BetaC[6]*nus))])\r\ncat (\"Mid Point Tau :\", ELNVus$BetaC[6] , \"\\n\")\r\ncat (\"Speed of Transition Gamma :\", ELNVus$BetaC[5] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"*******************************************************************************************\", \"\\n\")\r\ncat (\"\\n\")\r\n}\r\n\r\nprintadf<-function(tri,usi,ptr,pus){\r\ncat (\"\\n\")\r\ncat (\"ADF Results for Industrial Production Index of Turkey\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(tri) , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", ptr, \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Model Type : Constant & Trend\" , \"\\n\")\r\ncat (\"Test Statistics :\", adftr0$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\",ADFt , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"ADF Results for Industrial Production Index of USA\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(usi) , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", pus, \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Model Type : Constant & Trend\" , \"\\n\")\r\ncat (\"Test Statistics :\", adfus0$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\",ADFt , \"\\n\")\r\n}\r\n\r\nprintlnv<-function(tri,usi,PLNV){\r\ncat (\"\\n\")\r\ncat (\"LNV Results for Industrial Production Index of Turkey\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(tri) , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[1] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adftrA$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVa , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[2] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adftrB$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVb , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[3] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adftrC$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVc , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"******************************************************\", \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"LNV Results for Industrial Production Index of USA\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(usi) , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[4] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adfusA$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVa , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[5] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adfusB$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVb , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\", PLNV[6] , \"\\n\")\r\ncat (\"Information Criteria : BIC\" , \"\\n\")\r\ncat (\"Test Statistics :\", adfusC$tadf , \"\\n\")\r\ncat (\"5% Critical Value :\", LNVc , \"\\n\")\r\ncat (\"\\n\")\r\n}\r\n\r\nprintlch<-function(tri,usi,PLCH){\r\ncat (\"\\n\")\r\ncat (\"New Combined Caner & Hansen (2001) Results for Industrial Production Index of Turkey\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(tri) , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[1] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tartrA$r1[tartrA$mhat],\" / R2 Test Statistics :\",tartrA$r2[tartrA$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1A ,\"/ R2 5% Critical Value :\",R2A , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalAtr[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalAtr[2] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[2] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tartrB$r1[tartrB$mhat],\"/ R2 Test Statistics :\",tartrB$r2[tartrB$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1B ,\"/ R2 5% Critical Value :\",R2B , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalBtr[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalBtr[2] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[3] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tartrC$r1[tartrC$mhat],\"/ R2 Test Statistics :\",tartrC$r2[tartrC$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1C ,\"/ R2 5% Critical Value :\",R2C , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalCtr[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalCtr[2] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"************************************************************************************************\", \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"New Combined Caner & Hansen (2001) Results for Industrial Production Index of USA\" , \"\\n\")\r\ncat (\"Number of Observations:\", length(usi) , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model A\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[4] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tarusA$r1[tarusA$mhat],\"/ R2 Test Statistics :\",tarusA$r2[tarusA$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1A ,\"/ R2 5% Critical Value :\",R2A , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalAus[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalAus[2] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model B\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[5] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tarusB$r1[tarusB$mhat],\"/ R2 Test Statistics :\",tarusB$r2[tarusB$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1B ,\"/ R2 5% Critical Value :\",R2B , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalBus[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalBus[2] , \"\\n\")\r\ncat (\"\\n\")\r\ncat (\"Model C\" , \"\\n\")\r\ncat (\"Selected Optimal Lag :\",PLCH[6] , \"\\n\")\r\ncat (\"Information Criteria : Superme RT\" , \"\\n\")\r\ncat (\"R1 Test Statistics :\",tarusC$r1[tarusC$mhat],\"/ R2 Test Statistics :\",tarusC$r2[tarusC$mhat] , \"\\n\")\r\ncat (\"R1 5% Critical Value :\",R1C ,\"/ R2 5% Critical Value :\",R2C , \"\\n\")\r\ncat (\"++++++++++++++++++++++\" , \"\\n\")\r\ncat (\"Caner & Hansen (2001) Threshold Effect Wald Test\" , \"\\n\")\r\ncat (\"Test Statistics :\",pvalCus[1] , \"\\n\")\r\ncat (\"Bootstrap p-value :\",pvalCus[2] , \"\\n\")\r\ncat (\"\\n\")\r\n}\r\n\r\nprintlog(tri,usi)\r\nprintadf(tri,usi,ptr,pus)\r\nprintlnv(tri,usi,PLNV)\r\nprintlch(tri,usi,PLCH)\r\n\r\n# END\r\n", "meta": {"hexsha": "8153a39dd9de6e94d81ffc16540baae341ba4b34", "size": 36966, "ext": "r", "lang": "R", "max_stars_repo_path": "Application-1.r", "max_stars_repo_name": "mehmet-ozcan/2021-bookchapter-1", "max_stars_repo_head_hexsha": "576ad6c2c047a152081769dfde62a8af3d4262c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Application-1.r", "max_issues_repo_name": "mehmet-ozcan/2021-bookchapter-1", "max_issues_repo_head_hexsha": "576ad6c2c047a152081769dfde62a8af3d4262c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Application-1.r", "max_forks_repo_name": "mehmet-ozcan/2021-bookchapter-1", "max_forks_repo_head_hexsha": "576ad6c2c047a152081769dfde62a8af3d4262c8", "max_forks_repo_licenses": ["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.5118110236, "max_line_length": 176, "alphanum_fraction": 0.4463020072, "num_tokens": 11457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6959583313396338, "lm_q1q2_score": 0.5982901393090265}} {"text": "#' Title\n#'\n#' @param observed observed values of dependent variable. \n#' @param predicted predicted values of dependent variable. \n#' @param norm Normalize RMSE score to the mean abundance of the observed values? Default is FALSE.\n#'\n#' @return returns RMSE score.\n#' @export\n#'\n#' @examples\nrmse <- function(observed, predicted, norm = F){\n #compatability tests.\n if(sum(is.na(observed )) > 0){stop('Error: NAs in observed vector.' )}\n if(sum(is.na(predicted)) > 0){stop('Error: NAs in predicted vector.')}\n if(length(observed) != length(predicted)){stop('Error: predicted and observed vectors must be the same length.')}\n \n #get sample size.\n N <- length(observed)\n \n #calculate residual sums of squares relative to actual prediction (i.e. \"1:1 line\")\n SS.res <- sum((observed - predicted)^2)\n \n #divide by sample size, take square root.\n obs.rmse <- sqrt(SS.res / N)\n \n #Normalize RMSE score, if desired.\n if(norm == T){\n obs.rmse <- obs.rmse / mean(observed)\n }\n \n #return RMSE.\n return(obs.rmse)\n}", "meta": {"hexsha": "9eb3527c9b3fd30e9a8c2395708ad5da94661f2a", "size": 1045, "ext": "r", "lang": "R", "max_stars_repo_path": "NEFI_functions/rmse.r", "max_stars_repo_name": "colinaverill/NEFI_microbe", "max_stars_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-13T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T17:13:54.000Z", "max_issues_repo_path": "NEFI_functions/rmse.r", "max_issues_repo_name": "colinaverill/NEFI_microbe", "max_issues_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NEFI_functions/rmse.r", "max_forks_repo_name": "colinaverill/NEFI_microbe", "max_forks_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-21T20:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T16:09:44.000Z", "avg_line_length": 31.6666666667, "max_line_length": 115, "alphanum_fraction": 0.6650717703, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5982809644038696}} {"text": "rares = c(\n \"8217\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"38\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"7544\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2605\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"313\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"7599\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"2285\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7848\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"6662\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1382\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"4531\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"4975\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"2591\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7880\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7458\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1893\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"7459\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"6288\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"2543\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"2313\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"1104\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"392\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7958\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7252\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8032\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"2787\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1176\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"3073\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"9309\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7535\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"7423\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8356\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"3255\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"9228\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1759\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8994\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"469\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"4182\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2638\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"3403\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"1820\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5139\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"6208\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"4849\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"8951\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"7168\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"6167\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"2096\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"9571\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"6417\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"7942\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"9727\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"4396\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"3159\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"5099\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"5420\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"8572\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"3513\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"1053\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"16\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"4502\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^4))),\n \"2295\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^4))),\n \"8634\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^4))),\n \"3112\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^4))),\n \"744\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^4)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^4))),\n \"6564\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"6593\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"985\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"3605\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"7061\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5753\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"6278\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"4745\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"6726\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5013\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5531\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"2513\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"8872\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5594\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"9891\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"4158\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5870\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"7910\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"2500\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"5711\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"1677\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"904\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"3897\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"6660\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2345\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"7087\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"345\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"3900\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"6557\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"4358\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"8033\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"3856\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"396\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8482\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"5702\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1516\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8762\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"3576\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"6987\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"4397\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"5975\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1042\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"5225\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"2794\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"2589\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8392\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"8715\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"4401\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"1384\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"894\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"5738\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"3951\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"5193\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^1 - cos(x_i^4))),\n \"3257\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"7350\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"759\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"6342\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^4))),\n \"8926\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^3))),\n \"3148\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^1))),\n \"2913\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^1))),\n \"998\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"371\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"3500\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"7312\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2376\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"8324\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"2169\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"5834\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^0)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^0))),\n \"6292\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^0)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^0))),\n \"5984\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^0)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^0))),\n \"2939\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^1))),\n \"173\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^1))),\n \"3378\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^1))),\n \"1505\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^3))),\n \"9728\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^3)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^3))),\n \"7116\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^5)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^5))),\n \"1757\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - sin(x_i^2))),\n \"9907\" = list(x= quote(runif(1, -1, 1) * x_i^4 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^4 - cos(x_i^2))),\n \"7238\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"9484\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2338\" = list(x= quote(runif(1, -1, 1) * x_i^3 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^3 - cos(x_i^2))),\n \"2338\" = list(x= quote(runif(1, -1, 1) * x_i^1 - sin(y_i^1)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))),\n \"2338\" = list(x= quote(runif(1, -1, 1) * x_i^2 - sin(y_i^2)), y = quote(runif(1, -1, 1) * y_i^2 - cos(x_i^2))))", "meta": {"hexsha": "f2682ae866c01f674162b6453c4762fc1ec00825", "size": 17026, "ext": "r", "lang": "R", "max_stars_repo_path": "rares.r", "max_stars_repo_name": "marcosteixeira/generative_art", "max_stars_repo_head_hexsha": "1031010aaf949e529779af1e24693fc369dd12ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rares.r", "max_issues_repo_name": "marcosteixeira/generative_art", "max_issues_repo_head_hexsha": "1031010aaf949e529779af1e24693fc369dd12ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rares.r", "max_forks_repo_name": "marcosteixeira/generative_art", "max_forks_repo_head_hexsha": "1031010aaf949e529779af1e24693fc369dd12ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.2684563758, "max_line_length": 114, "alphanum_fraction": 0.5035240221, "num_tokens": 8870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.598249915315424}} {"text": "# James Rekow\r\n\r\npartition = function(n, numPartitions){\r\n \r\n # ARGS: n - number to be partitioned\r\n # numPartitions - number of pieces into which n is to be partitioned\r\n #\r\n # RETURNS: partitionSizeVec - numeric vector of the unique set of numPartitions numbers with the\r\n # property that the sum of the numbers is n and any two numbers in\r\n # partitionSizeVec differ by at most 1\r\n \r\n # if the number of partitions is greater than n, set it to n\r\n numPartitions = min(numPartitions, n)\r\n \r\n # compute the size of the partitions, ignoring the remainder\r\n basePartitionSize = floor(n / numPartitions)\r\n \r\n # compute the number of partition elements that will be one larger than the base partition size\r\n # in order to account for the remainder\r\n remainder = n %% numPartitions\r\n \r\n # create base partition, ignoring remainder\r\n partitionSizeVec = rep(basePartitionSize, numPartitions)\r\n \r\n # increase the size of some elements of the partition by 1 to account for the remainder\r\n if(remainder > 0){\r\n partitionSizeVec[1:remainder] = sapply(partitionSizeVec[1:remainder], function(z) z + 1)\r\n } # end if\r\n \r\n return(partitionSizeVec)\r\n \r\n} # end partition function\r\n", "meta": {"hexsha": "7285fe7f6456d85275f223f4e064ecf728994c08", "size": 1272, "ext": "r", "lang": "R", "max_stars_repo_path": "partition.r", "max_stars_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_stars_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "partition.r", "max_issues_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_issues_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "partition.r", "max_forks_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_forks_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5454545455, "max_line_length": 100, "alphanum_fraction": 0.6737421384, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5981106435388907}} {"text": "# Chart 1\n\n#p_0 are 0.2, 0.8, 0.4, 0.6, 0.7\n#p_0 <- c(1,2,3,4,5) # C(x,y) is a vector to store values. A List that we can iterate over.\n\n# Matrix, values converted to characters\n#naming <- c(\"a\", \"a\", \"a\", \"a\", \"a\")\n#cbind(p_0, naming)\n\n#frequencia(geracoes) = (p_0 - p')(1-m)^geracoes\n\nm <- 0.1\n\np_constant <- 0.5\n\np_0 <- c(0.1,0.3,0.5,0.7,0.9) # C(x,y) is a vector to store values. A List that we can iterate over.\n\nt <- c(10,20,30,40,50)\n\n\n#valores <- 1\n#b <- c(b, 2)\n\nfor (geracao in t) {\n\tmessage(\"Inicio\")\n\tmessage(t)\n\tfor (i in p_0) {\n\t\tmessage(\"inner loop\")\n\t\tmessage(i)\n\t\tresultado <- ( i - p_constant ) * (1 - m) ^ geracao\n\t\tvalores <- c(valores, resultado)\n\t}\n}\nunlist(valores)", "meta": {"hexsha": "679f872c628934210b17e187c29bb3ec9e450b6f", "size": 688, "ext": "r", "lang": "R", "max_stars_repo_path": "Charts/chart1.r", "max_stars_repo_name": "lcustodio/R_sample_charting", "max_stars_repo_head_hexsha": "44d5e07f5e9d556ec0f8fcc6373465771913d04c", "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": "Charts/chart1.r", "max_issues_repo_name": "lcustodio/R_sample_charting", "max_issues_repo_head_hexsha": "44d5e07f5e9d556ec0f8fcc6373465771913d04c", "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": "Charts/chart1.r", "max_forks_repo_name": "lcustodio/R_sample_charting", "max_forks_repo_head_hexsha": "44d5e07f5e9d556ec0f8fcc6373465771913d04c", "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.2352941176, "max_line_length": 100, "alphanum_fraction": 0.5930232558, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5980212617374971}} {"text": "## Salidas de funciones\n\n# En esta lección vamos a explorar las diferentes opciones de salida que podemos\n# darle a una función, desde un valor sencillo sin ningún detalle hasta salidas\n# listadas más complejas.\n\nv <- 15:25 # Vamos a necesitar un objeto 'v' para los ejemplos.\n\n# Salidas simples\n# Si recordamos la lección anterior, los objetos definidos dentro del cuerpo de\n# una función sólo existen en el instante que dura el ambiente creado durante la\n# ejecución de la misma. En la medida en que nos interesa obtener una salida de\n# la evaluación de una función, hay que definir qué objetos van a salir de este\n# ambiente a la consola, y para ello debemos definir salidas en el cuerpo de la\n# función.\n# Por defecto, la salida de una función es el resultado de la última evaluación\n# contenida en el cuerpo de la misma. Si tomamos como ejemplo la siguiente\n# función\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n p\n}\nf(v)\n\n# la salida va a ser el valor de 'p', en este caso el promedio de 'v'.\n# El último comando no necesita ser la llamada a un objeto, puede ser una\n# operación. Intentemos ver qué pasa si suprimimos la llamada a 'p', y nos que-\n# damos sólo con la operación anterior pero sin asignar el resultado.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n sum(v) / length(v)\n}\nf(v)\n\n# El resultado final es el mismo.\n# Veamos ahora qué sucede si asignamos el objeto 'p', pero no lo llamamos al\n# final del cuerpo de 'f'.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n}\nf(v)\n\n# En este caso no hay una salida visible a la consola. Esto no implica que no\n# exista una salida, ya que si asignamos la evaluación de la función a un objeto\n# en la consola, éste va a ser asignado con esta salida invisible.\n\na <- f(v)\na\n\n# Una opción que podemos adoptar es interrumpir la ejecución de la función y\n# definir con precisión una salida de la misma. Para ello podemos utilizar el\n# comando 'return', utilizando como argumento el objeto que queremos en la\n# salida.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n if (p > 15) return(15)\n p\n}\nf(v + 20)\n\n# En este caso, cuando el condicional 'if' es verdadero, la función devuelve el\n# valor indicado en este comando, y todo lo que se encuentra posterior al mismo\n# no es ejecutado. (El uso de condicionales lo veremos detalladamente en la\n# unidad siguiente)\n\n# Otro comando que se puede utilizar es 'invisible', que hace que la salida de\n# nuestra función no sea impresa en la consola.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n invisible(p)\n}\nf(v)\n\n# Esto produce el mismo resultado que la situación en la que el resultado sólo\n# era visible si asignábamos la evaluación de la función a un nuevo objeto.\n\na <- f(v)\na\n\n\n## Salidas más elaboradas\n\n# A veces las salidas que queremos no se limitan a un vector o matriz, sino que\n# necesitamos obtener más de un resultado de nuestra función. La solución más\n# sencilla y frecuente es usar listas.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n m <- matrix(rnorm(9, mean = p), 3, 3)\n list(prom = p, matriz = m)\n}\nf(v)\n\n# Si recordamos de unidades anteriores, en funciones como 'lm', 'summary', etc.,\n# se utiliza exactamente este método.\n\n\n# A modo de cierre y resumen de la presente lección, nos quedan 3 puntos:\n# - Definir las salidas es necesario ya que los objetos del ambiente de\n# ejecución de una función no son accesibles desde los ambientes parentales\n# (i.e.: el área de trabajo).\n# - En general la salida de una función es la última evaluación del cuerpo de\n# instrucciones, pero esto cambia al usar 'return'.\n# - El uso de listas (generalmente nombradas) suele ser una solución útil para\n# obtener salidas elaboradas cuando no nos alcanza con un objeto sencillo.\n", "meta": {"hexsha": "06f139133225a55252f5f5669122aafa16e06e69", "size": 3791, "ext": "r", "lang": "R", "max_stars_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.3-salidas-de-funciones.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/5.3-salidas-de-funciones.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/5.3-salidas-de-funciones.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": 32.6810344828, "max_line_length": 80, "alphanum_fraction": 0.7148509628, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.5979115034877867}} {"text": "#' Mean difference test (t-test) for local random approach\n#'\n#' @param basemod baseline formula. `outcome ~ running variable`.\n#' @param data data.frame which you want to use.\n#' @param bootse numeric.\n#' Generate N averages of bootstrap samples and\n#' use the standard deviation as the standard error of the average.\n#' If missing, standard error of mean is calculated by\n#' sqrt(v / e) where v is unbiased variance of outcome,\n#' and e is effective sample size: e = sum(w) ^ 2 / sum(w ^ 2).\n#' If w is missing, we set w = 1, and obtain e = 1 / n.\n#' standard error of mean difference is obtained by\n#' sqrt((v1 / e1) + (v0 / e0))\n#' @param bootp numeric.\n#' Perform a permutation test with N re-randomizations.\n#' The p-value is obtained at a rate\n#' where the absolute value of the mean difference\n#' due to rerandomization is greater than\n#' the absolute value of the observed mean difference.\n#' If missing, standard t-test is performed.\n#'\n#' @importFrom rlang f_lhs\n#' @importFrom rlang eval_tidy\n#' @importFrom stats var\n#' @importFrom stats pt\n#' @examples\n#' \\dontrun{\n#' running <- sample(1:100, size = 1000, replace = TRUE)\n#' cov1 <- rnorm(1000, sd = 2); cov2 <- rnorm(1000, mean = -1)\n#' y0 <- running + cov1 + cov2 + rnorm(1000, sd = 10)\n#' y1 <- 2 + 1.5 * running + cov1 + cov2 + rnorm(1000, sd = 10)\n#' y <- ifelse(running <= 50, y1, y0)\n#' bin <- ifelse(y > mean(y), 1, 0)\n#' w <- sample(c(1, 0.5), size = 1000, replace = TRUE)\n#' raw <- data.frame(y, bin, running, cov1, cov2, w)\n#'\n#' set_optDiscRD(discRD.cutoff = 50, discRD.assign = \"smaller\")\n#' useit <- clean_rd_data(y ~ running, data = raw)\n#' str(local_random_test_int(y ~ running, useit$data))\n#' str(local_random_test_int(y ~ running, useit$data, bootse = 100))\n#' str(local_random_test_int(y ~ running, useit$data, bootp = 100))\n#' }\n#'\nlocal_random_test_int <- function(basemod,\n data,\n bootse,\n bootp) {\n # create weights if null\n if (is.null(data$\"(weights)\")) data$\"(weights)\" <- 1\n\n # treated and control data\n d1 <- data$d == 1\n n1 <- sum(d1)\n n0 <- sum(!d1)\n\n yvar <- rlang::f_lhs(basemod)\n y1 <- rlang::eval_tidy(yvar, data[d1, ])\n y0 <- rlang::eval_tidy(yvar, data[!d1, ])\n\n w1 <- data[d1, \"(weights)\"]\n w0 <- data[!d1, \"(weights)\"]\n\n # average and mean difference\n ymu1 <- mean(y1 * w1) / mean(w1)\n ymu0 <- mean(y0 * w0) / mean(w0)\n diff_mu <- ymu1 - ymu0\n\n # create output list\n out <- list()\n out$outcome <- as.character(yvar)\n out$observe$treat$N <- n1\n out$observe$treat$mean <- ymu1\n out$observe$control$N <- n0\n out$observe$control$mean <- ymu0\n out$local.ate$estimate <- diff_mu\n\n # standard errors\n if (missing(bootse)) {\n effective_size_1 <- sum(w1)^2 / sum(w1^2)\n effective_size_0 <- sum(w0)^2 / sum(w0^2)\n\n yse1 <- var(y1) / effective_size_1\n yse0 <- var(y0) / effective_size_0\n mean_se <- sqrt(yse1 + yse0)\n } else {\n yse1 <- bootstrap(y1, w1, bootse)$boot$se\n yse0 <- bootstrap(y0, w0, bootse)$boot$se\n mean_se <- sqrt(yse1 + yse0)\n }\n\n out$observe$treat$se <- yse1\n out$observe$control$se <- yse0\n out$local.ate$se <- mean_se\n\n # two-sided test or permutation test\n if (missing(bootp)) {\n dfval <- n1 + n0 - 2\n tval <- abs(diff_mu) / mean_se\n pval <- 2 * pt(tval, df = dfval, lower.tail = FALSE)\n\n out$local.ate$df <- dfval\n out$local.ate$t <- tval\n out$local.ate$p.value <- pval\n out$local.ate$method <- \"Two-sided t-test\"\n } else {\n y <- rlang::eval_tidy(yvar, data)\n d <- data$d\n w <- data$\"(weights)\"\n\n perm <- permutation(y, d, w, bootp)\n\n out$local.ate$p.value <- perm$ate$p.value\n out$local.ate$method <- perm$ate$method\n }\n\n out\n}\n\n#'\n#' Perform Local Randomization Approach\n#'\n#' @description An analysis of the difference between\n#' the means of the two groups is performed\n#' under the assumption that\n#' the treatment assignments are random near the cutoff (local random).\n#' Statistical inference has a permutation test for small sample sizes\n#' in addition to the standard t-test.\n#'\n#' @param basemod baseline formula. `outcome ~ running variable`.\n#' @param data data.frame which you want to use.\n#' @param weights weight variable.\n#' @param submod numeric vector.\n#' Which baseline model you want to use.\n#' @param subset subset condition.\n#' @param bw numeric vector of bandwidth.\n#' If specified, use data\n#' whose running variables are within this range will be used.\n#' If missing, use data from treatment and control groups\n#' where the running variable is closest to the cutoff\n#' @param global logical (default is FALSE).\n#' Whether to use all observations.\n#' @param bootse numeric.\n#' Generate N averages of bootstrap samples and\n#' use the standard deviation as the standard error of the average.\n#' If missing, standard error of mean is calculated by\n#' sqrt(v / e) where v is unbiased variance of outcome,\n#' and e is effective sample size: e = sum(w) ^ 2 / sum(w ^ 2).\n#' If w is missing, we set w = 1, and obtain e = 1 / n.\n#' standard error of mean difference is obtained by\n#' sqrt((v1 / e1) + (v0 / e0))\n#' @param bootp numeric.\n#' Perform a permutation test with N re-randomization.\n#' The p-value is obtained at a rate\n#' where the absolute value of the mean difference\n#' due to re-randomization is greater than\n#' the absolute value of the observed mean difference.\n#' If missing, standard t-test is performed.\n#' @param cutoff numeric of cutoff points\n#' If missing, try to find `getOption(\"discRD.cutoff\")`.\n#' @param assign assignment rule of treatment.\n#' If \"greater\",\n#' treated whose running variable is greater than or equal to cutoff.\n#' If \"smaller\",\n#' treated whose running variable is less than or equal to cutoff.\n#' If missing, try to find `getOption(\"discRD.assign\")`.\n#'\n#' @export\n#' @examples\n#' running <- sample(1:100, size = 1000, replace = TRUE)\n#' cov1 <- rnorm(1000, sd = 2); cov2 <- rnorm(1000, mean = -1)\n#' y0 <- running + cov1 + cov2 + rnorm(1000, sd = 10)\n#' y1 <- 2 + 1.5 * running + cov1 + cov2 + rnorm(1000, sd = 10)\n#' y <- ifelse(running <= 50, y1, y0)\n#' bin <- ifelse(y > mean(y), 1, 0)\n#' w <- sample(c(1, 0.5), size = 1000, replace = TRUE)\n#' raw <- data.frame(y, bin, running, cov1, cov2, w)\n#'\n#' set_optDiscRD(\n#' y + bin ~ running,\n#' discRD.cutoff = 50,\n#' discRD.assign = \"smaller\"\n#' )\n#'\n#' est1 <- local_random_test(data = raw, weights = w, global = TRUE)\n#' str(est1)\n#' est2 <- local_random_test(data = raw, bootp = 1000, submod = 1)\n#' str(est2)\n#'\nlocal_random_test <- function(basemod,\n data,\n weights,\n submod,\n subset,\n bw,\n global = FALSE,\n bootse,\n bootp,\n cutoff,\n assign) {\n # check basemod\n if (missing(basemod)) basemod <- getOption(\"discRD.basemod\")\n if (!is.list(basemod)) basemod <- list(basemod)\n if (length(basemod) == 0) stop(\"Baseline model not found\")\n if (missing(submod)) submod <- seq_len(length(basemod))\n usemod <- basemod[submod]\n\n # check arguments for cleaning data\n dtarg <- rlang::enquos(\n weights = weights,\n subset = subset\n )\n dtarg <- Filter(Negate(rlang::quo_is_missing), dtarg)\n dtarg$data <- data\n if (!missing(cutoff)) dtarg$cutoff <- cutoff\n if (!missing(assign)) dtarg$assign <- assign\n if (!missing(global)) dtarg$global <- global\n if (!missing(bw)) dtarg$bw <- bw\n\n # check arguments for test\n estarg <- list()\n if (!missing(bootse)) estarg$bootse <- bootse\n if (!missing(bootp)) estarg$bootp <- bootp\n\n # run test\n est <- lapply(usemod, function(m) {\n # cleaning data\n dtarg$basemod <- m\n clean <- do.call(\"clean_rd_data\", dtarg)\n\n # temporal output\n temp <- list()\n temp$RD.info <- clean$RD.info\n temp$bandwidth <- clean$bw.subset\n\n # run t-test / permutation test\n estarg$basemod <- m\n estarg$data <- clean$data\n temp$estimate <- do.call(\"local_random_test_int\", estarg)\n\n # output\n class(temp) <- \"local_random\"\n temp\n })\n\n # final output\n class(est) <- append(\"list_local_random\", class(est))\n est\n}\n", "meta": {"hexsha": "5e495ced71b61fe11b8b7ad483b5106022a7fda5", "size": 8395, "ext": "r", "lang": "R", "max_stars_repo_path": "R/discRD-local-random.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/discRD-local-random.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/discRD-local-random.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": 33.7148594378, "max_line_length": 73, "alphanum_fraction": 0.6206075045, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5977249755951715}} {"text": "# ......................................................................................\n# .............. Cvičení 10. Úvod do testování hypotéz, jednovýběrové testy.............\n# ......................... 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# Od intervalových odhadů k testům hypotéz ####\n# * Co je to statistický test hypotéz? ####\n# Mějme následující:\n# - náhodná veličina X (například výška mužů)\n# - výběr z náhodné veličiny (měření výšky 30 mužů)\n# \n# Statistické testování hypotéz rozhoduje na základě získaných dat z náhodného výběru o\n# platnosti:\n# - $H_0$ - nulové hypotézy\n# - $H_A$ - alternativní hypotézy\n# \n# Například:\n# $H_0$: $\\mu_X = 175$\n# $H_A$: $\\mu_X > 175$\n# Jelikož se jedná o statistické rozhodnutí, vždy bude vázáno k nějaké hladnině\n# významnosti $\\alpha$. Vždy můžeme dospět pouze k 2 různým rozhodnutím:\n# - Zamítám $H_0$ ve prospěch $H_A$\n# - to znamená, že tvrdím, že $H_0$ neplatí\n# - toto rozhodnutí je s maximální chybou $\\alpha$ (hladina významnosti, chyba I.\n# druhu) - to znamená, že velikost této chyby jsme schopni ovlivnit\n# - Nezamítám $H_0$\n# - to znamená, že tvrdím, že vzhledem k získaným datům (výběr) nelze vyvrátit $H_0$\n# - toto rozhodnutí je s chybou $\\beta$ (chyba II. druhu), tato chyba není přímo\n# ovlivnitelná a záleží na typu použitého testu\n# \n# Jak testy hypotéz souvisí s intervalovými odhady a jak do nich vstupuje hladina\n# významnosti si ukážeme v další části.\n\n\n# * Intervalový odhad a hladina významnosti ####\n\n\ndata = readxl::read_excel(\"D:/_VSB/S8/PS/Beres/GitPS/CV10/data/uvod.xlsx\")\nhead(data)\n\noptions(repr.plot.width = 12) # šířka grafů v Jupyteru\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nboxplot(data$data)\nhist(data$data)\n\nmoments::skewness(data$data) # šikmost\nmoments::kurtosis(data$data) - 3 # špičatost\n\nshapiro.test(data$data)$p.value # test normality\n\nlength(data$data)\nmean(data$data)\nsd(data$data)\n\n# Vyrobíme 95% intervalový odhad střední hodnoty pomocí t-testu:\n\n\nt.test(data$data, alternative = \"two.sided\", conf.level = 0.95)$conf.int\n\n# Představme si nyní, že chceme testovat hypotézu:\n# $H_0$: $\\mu = 100$\n# $H_A$: $\\mu \\neq 100$\n# Jaké by bylo rozhodnutí vzhledem k spočtenému IO a tedy hladině významnosti $\\alpha =\n# 0.05$?\n\n\n# Představme si dále, že chceme testovat hypotézu:\n# $H_0$: $\\mu = 105$\n# $H_A$: $\\mu \\neq 105$\n# Jaké by bylo rozhodnutí vzhledem k spočtenému IO a tedy hladině významnosti $\\alpha =\n# 0.05$?\n\n\n# **To co jsme právě udělali se nazývá klasický test.**\n# Ukážeme si ještě klasické testy pro jednostranné alternativy.\n# $H_0$: $\\mu = 105$\n# $H_A$: $\\mu > 105$\n\n\nt.test(data$data, alternative = \"greater\", conf.level = 0.95)$conf.int\n\n# $H_0$: $\\mu = 105$\n# $H_A$: $\\mu < 105$\n\n\nt.test(data$data, alternative = \"less\", conf.level = 0.95)$conf.int\n\n# Všimněte si, že první z těchto jednostranných alternativ vedla k \"nezamítnutí\" $H_0$.\n# Je to z důvodu porovnávání nepravděpodobné $H_0$ s ještě méně pravděpodobnou $H_A$.\n# *** Čistý test významnosti a souvislost s IO ####\n# Alternativou ke klasickému testu (kde vytváříme IO - v terminologii klasických testů\n# tzv. obor přijetí a jeho doplněk do R kritický obor) je tzv. čistý test významnosti:\n\n\n# H_0: mu = 105\n# H_A: mu <> 105\nt.test(data$data, mu = 105, alternative = \"two.sided\")\n\nt.test(data$data, mu = 105, alternative = \"two.sided\")$p.value\n\n# Výsledkem čistého testu významnosti je p-hodnota. Na jejím základě rozhodujeme o\n# zamítnutí či nezamítnutí $H_0$.\n# p-hodnota se dá chápat jako nejvyšší možná hladina váznamnosti, taková aby naše\n# rozhodnutí bylo - nezamítám. Tedy IO/obor přijetí by obsahoval zkoumanou hodnotu:\n\n\n# H_0: mu = 105\n# H_A: mu <> 105\n\np.hod = t.test(data$data, mu = 105, alternative = \"two.sided\")$p.value\np.hod\n\nt.test(data$data, alternative = \"two.sided\", conf.level = 1 - p.hod)$conf.int\n\n# H_0: mu = 105\n# H_A: mu > 105\n\np.hod = t.test(data$data, mu = 105, alternative = \"greater\")$p.value\np.hod\n\nt.test(data$data, alternative = \"greater\", conf.level = 1 - p.hod)$conf.int\n\n# H_0: mu = 105\n# H_A: mu < 105\n\np.hod = t.test(data$data, mu = 105, alternative = \"less\")$p.value\np.hod\n\nt.test(data$data, alternative = \"less\", conf.level = 1 - p.hod)$conf.int\n\n# * Přehled testů ####\n# ** Míry polohy ####\n# Mírami polohy rozumíme údaj určující polohu dat, nehledě na tom jak jsou rozptýlená.\n# Pro data z normálního rozdělení můžeme odhadovat střední hodnotu, pro ostatní medián.\n# *** a) studentův t-test ####\n# - testujeme střední hodnotu\n# - data musejí pocházet z normálního rozdělení\n# - exploračně: šikmost a špičatost leží v (-2,2)\n# - exploračně: QQ graf má body přibližně na čáře\n# - exaktně: pomocí statistického testu, např. Shapiro-Wilk test\n# (shapiro.test(data))\n\n\n# H_0: mu = 100\n# H_A: mu <> 100\nt.test(data$data, mu = 100, alternative = 'two.sided')$p.value\n\n# H_0: mu = 100\n# H_A: mu > 100\nt.test(data$data, mu = 100, alternative = 'greater')$p.value\n\n# H_0: mu = 100\n# H_A: mu < 100\nt.test(data$data, mu = 100, alternative = 'less')$p.value\n\n# *** b) Wilcoxnův test ####\n# - testujeme medián\n# - data musejí pocházet ze symetrického rozdělení\n# - exploračně: šikmost leží v (-2,2)\n# - exploračně: histogram vypadá přibližně symetricky\n# - exaktně: pomocí statistického testu, např. balíček \"lawstat\", funkce\n# \"symmetry.test(data,boot=FALSE)\"\n\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 <> 100\nwilcox.test(data$data, mu = 100, alternative = 'two.sided')$p.value\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 > 100\nwilcox.test(data$data, mu = 100, alternative = 'greater')$p.value\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 < 100\nwilcox.test(data$data, mu = 100, alternative = 'less')$p.value\n\n# *** c) znaménkový test test ####\n# - testujeme medián\n# - výběr většího rozsahu (>10)\n# - vyžaduje knihovnu \"BSDA\"\n# - jakožto nejrobustnější test, se dá použít i na nespojitá data - např. pořadí v\n# nějakém seznamu\n\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 <> 100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'two.sided')$p.value\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 > 100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'greater')$p.value\n\n# H_0: X_0.5 = 100\n# H_A: X_0.5 < 100\nBSDA::SIGN.test(data$data, md = 100, alternative = 'less')$p.value\n\n# ** Míry variability ####\n# Mírami variability rozumíme údaj určující rozptýlenost/variabilitu dat, nehledě na\n# celkových hodnotách. Pro data z normálního rozdělení můžeme odhadovat směrodatnou\n# odchylku.\n# *** test směrodatné odchylky ####\n# - testujeme směrodatnou odchylku\n# - data musejí pocházet z normálního rozdělení\n# - exploračně: šikmost a špičatost leží v (-2,2)\n# - exploračně: QQ graf má body přibližně na čáře\n# - exaktně: pomocí statistického testu, např. Shapiro-Wilk test\n# (shapiro.test(data))\n# - vyžaduje balíček \"EnvStats\"\n# - funkce v Rku, porovnává rozptyl!!!\n\n\n# H_0: sigma = 10\n# H_A: sigma <> 10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'two.sided')$p.value\n\n# H_0: sigma = 10\n# H_A: sigma > 10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'greater')$p.value\n\n# H_0: sigma = 10\n# H_A: sigma < 10\nEnvStats::varTest(data$data, sigma.squared = 10*10, \n alternative = 'less')$p.value\n\n# * Pravděpodobnost výskytu u jednoho výběru ####\n# *** IO pravděpodobnosti ####\n# - testujeme pravděpodobnost\n# - vyžadujeme dostatečný počet dat: $n>\\frac{9}{p(1-p)}$\n# - Clopperův - Pearsonův odhad (binom.test)\n# - jako parametr nebere data, ale počet úspěchů a počet pozorování \n\n\npi = 0.3\ndata_bin = runif(n = 100, min = 0, max = 1) < pi\n\nn = length(data_bin)\nx = sum(data_bin)\nn\nx\n\n# H_0: pi = 0.2\n# H_A: pi <> 0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'two.sided')$p.value\n\n# H_0: pi = 0.2\n# H_A: pi > 0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'greater')$p.value\n\n# H_0: pi = 0.2\n# H_A: pi < 0.2\nbinom.test(x = x, n = n, p = 0.2, alternative = 'less')$p.value\n\n# Příklady ####\n# * Příklad 1. ####\n# Máme výběr 216 pacientů a změřili jsme jejich bílkovinné sérum (soubor\n# testy_jednovyberove.xlsx list bilk_serum). Ověřte, zda se průměrné bílkovinné sérum\n# (Albumin) všech pacientů tohoto typu (populační průměr µ) statisticky významně liší od\n# hodnoty 35 g/l.\n\n\n# Načtení dat z xlsx souboru (pomoci balíčku readxl)\nalbumin = readxl::read_excel(\"D:/_VSB/S8/PS/Beres/GitPS/CV10/data/testy_jednovyberove.xlsx\",\n sheet = \"bilk_serum\")\nhead(albumin)\n\ncolnames(albumin)=\"hodnoty\"\n\n# Explorační analýza\nboxplot(albumin$hodnoty)\nsummary(albumin$hodnoty)\n\nlength(albumin$hodnoty) # sd zaokrouhlujeme na 3 platné cifry\nsd(albumin$hodnoty) # sd a míry polohy zaokrouhlujeme na tisíciny\n\n# **Test na míru polohy**\n\n\n# Ověření normality - exploračně\nmoments::skewness(albumin$hodnoty) # šikmost\nmoments::kurtosis(albumin$hodnoty)-3 # špičatost\n\noptions(repr.plot.width = 12) # šířka grafů v Jupyteru\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nqqnorm(albumin$hodnoty)\nqqline(albumin$hodnoty)\nhist(albumin$hodnoty)\n\n# Pro konečné rozhodnutí o normalitě dat použijeme test normality.\n\n# Předpoklad normality ověříme Shapirovovým - Wilkovovým testem.\n# H0: Data jsou výběrem z normálního rozdělení.\n# Ha: Data nejsou výběrem z normálního rozdělení.\nshapiro.test(albumin$hodnoty)\n# p-value > 0.05 -> Na hl. významnosti 0,05 nelze předpoklad normality zamít.\n\n# normalita OK -> t.test\n\n# H0: mu = 35 g/l\n# Ha: mu <> 35 g/l\n\nt.test(albumin$hodnoty, mu=35, alternative = \"two.sided\")\n\n# p-value < 0.05 -> Na hl. významnosti 0,05 zamítáme nulovou hypotézu \n# ve prospěch hypotézy alternativní \n# Střední hodnota albuminu se statisticky významně liší od 35 g/l.\n\n# * Příklad 2. ####\n# V souboru testy_jednovyberove.xlsx list preziti jsou uvedeny doby přežití pro 100\n# pacientů s rakovinou plic léčených novým lékem. Z předchozích studií je známo, že\n# průměrné přežití takových pacientů bez podávání nového léku je 22,2 měsíce. Lze na\n# základě těchto dat usoudit, že nový lék prodlužuje přežití?\n\n\n# Načtení dat z xlsx souboru (pomoci balíčku readxl)\npreziti = readxl::read_excel(\"D:/_VSB/S8/PS/Beres/GitPS/CV10/data/testy_jednovyberove.xlsx\",\n sheet = \"preziti\") \nhead(preziti)\n\ncolnames(preziti)=\"hodnoty\"\n\n## Explorační analýza\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nboxplot(preziti$hodnoty)\nhist(preziti$hodnoty)\n\n# **Data obsahují OP -> můžeme je odstranit. Nebo si také všimnout, že se pravděpdobně\n# jedná o exponenciální rozdělení a OP tam ve skutečnosti nejsou (rozdělení se tak\n# prostě chová).**\n\n# Data obsahují odlehlá pozorování. Pomoci f-ce boxplot je umíme vypsat.\npom=boxplot(preziti$hodnoty, plot = FALSE)\npom$out\n# rozhodli-li jsme se pro odstranění odlehlých hodnot, pak \npreziti$hodnoty.bez=preziti$hodnoty # doporučujeme nepřepisovat původní data\npreziti$hodnoty.bez[preziti$hodnoty %in% pom$out]=NA\n\n## Explorační analýza pro data bez odlehlých pozorování\nboxplot(preziti$hodnoty.bez)\nsummary(preziti$hodnoty.bez,na.rm=TRUE)\n\nlength(na.omit(preziti$hodnoty.bez)) # sd zaokrouhlujeme na 3 platné cifry\nsd(preziti$hodnoty.bez,na.rm=TRUE) # sd a míry polohy zaokr. na desetiny\n\n# **Test o míře polohy (střední hodnotě / mediánu)**\n\n\n# Ověření normality - exploračně\nmoments::skewness(preziti$hodnoty.bez,na.rm=TRUE)\nmoments::kurtosis(preziti$hodnoty.bez,na.rm=TRUE)-3\n\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nqqnorm(preziti$hodnoty.bez)\nqqline(preziti$hodnoty.bez)\nhist(preziti$hodnoty.bez)\n\n# QQ - graf i hist. ukazují, že výběr pravd. není výběrem z norm. rozdělení.\n# Šikmost i špičatost odpovídá norm. rozdělení. \n# použijeme test normality.\n\n# Předpoklad normality ověříme Shapirovovým . Wilkovovým testem.\nshapiro.test(preziti$hodnoty.bez)\n# p-value < 0.05 -> Na hl. významnosti 0.05 zamítáme předpoklad normality \n\n# explorační posouzení symetrie - výše hist. a šikmost \n\n# Předpoklad symetrie - ověření testem\n# H0: data pocházejí ze symetrického rozdělení\n# HA: ~H0\n\nlawstat::symmetry.test(preziti$hodnoty.bez,boot=FALSE)\n# p-value < 0.05 -> Na hl. významnosti 0.05 zamítáme předpoklad symetrie \n\n# normalita zamítnuta -> symetrie zamítnuta -> Sign. test\n# H0: median = 22,2 měsíců\n# Ha: median > 22,2 měsíců\n\nBSDA::SIGN.test(preziti$hodnoty.bez, md=22.2,\n alternative=\"greater\", conf.level=0.95)\n\n# p-value > 0.05 -> Na hl. významnosti 0,05 nelze zamítnout nulovou hypotézu \n# Medián doby přežití není statisticky významně větší než 22,2 měsíců.\n\nmedian(preziti$hodnoty.bez, na.rm = TRUE)\n\n# H0: median = 22,2 měsíců\n# Ha: median < 22,2 měsíců\n\nBSDA::SIGN.test(preziti$hodnoty.bez, md=22.2,\n alternative=\"less\", conf.level=0.95)\n\n# * Příklad 3. ####\n# Automat vyrábí pístové kroužky o daném průměru. Výrobce udává, že směrodatná odchylka\n# průměru kroužku je 0,05 mm. K ověření této informace bylo náhodně vybráno 80 kroužků a\n# vypočtena směrodatná odchylka jejich průměru 0,04 mm. Lze tento rozdíl považovat za\n# statisticky významný ve smyslu zlepšení kvality produkce? Ověřte čistým testem\n# významnosti. Předpokládejte, že průměr pístových kroužků má normální rozdělení.\n\n\n# Test o směrodatné odchylce \n\n# Předpokládáme normalitu dat (dle zadání)\nn = 80 # rozsah souboru \ns = 0.04 # mm .... výběrová směrodatná odchylka (bodový odhad sm. odchylky)\n\n# H0: sigma = 0.05 mm\n# Ha: sigma < 0.05 mm\n\nx.obs = (n-1)*s^2/0.05^2\nx.obs\n\np.hodnota = pchisq(x.obs,n-1)\np.hodnota\n\n# p.hodnota < 0.05 -> Na hladině významnosti 0,05 zamítáme nulovou hypotézu \n# ve prospěch alternativní hypotézy\n# Směr. odchylka průměru kroužku je statisticky významně menší než 0,05 mm.\n\n# * Příklad 4. ####\n# Automat vyrábí pístové kroužky o daném průměru. Výrobce udává, že směrodatná odchylka\n# průměru kroužku je 0,05 mm. K ověření této informace bylo náhodně vybráno 80 kroužků a\n# byl změřen jejich průměr (soubor testy_jednovyberove.xlsx list krouzky). Lze zjištěné\n# výsledky považovat za statisticky významné ve smyslu zlepšení kvality produkce? Ověřte\n# čistým testem významnosti.\n\n\n# Načtení dat z xlsx souboru (pomoci balíčku readxl)\nkrouzky = readxl::read_excel(\"D:/_VSB/S8/PS/Beres/GitPS/CV10/data/testy_jednovyberove.xlsx\",\n sheet = \"krouzky\") \nhead(krouzky)\n\ncolnames(krouzky)=\"hodnoty\"\n\n## Explorační analýza\nboxplot(krouzky$hodnoty)\n\n# Data obsahují odlehlá pozorování. Pomoci f-ce boxplot je umíme vypsat.\npom = boxplot(krouzky$hodnoty, plot = FALSE)\npom$out\n# rozhodli-li jsme se pro odstranění odlehlých hodnot, pak \nkrouzky$hodnoty.bez = krouzky$hodnoty\nkrouzky$hodnoty.bez[krouzky$hodnoty %in% pom$out] = NA\n\n# Explorační analýza pro data bez odlehlých pozorování\nsummary(krouzky$hodnoty.bez,na.rm=TRUE)\nboxplot(krouzky$hodnoty.bez)\n\nlength(na.omit(krouzky$hodnoty.bez))# sd zaokrouhlujeme na 3 platné cifry\nsd(krouzky$hodnoty.bez,na.rm=TRUE) # sd a míry polohy zaokr. na tisíciny\n\n# Ověření normality - exploračně\nmoments::skewness(krouzky$hodnoty.bez,na.rm=TRUE)\nmoments::kurtosis(krouzky$hodnoty.bez,na.rm=TRUE)-3\n\npar(mfrow = c(1, 2)) # matice grafů 1x2\n\nqqnorm(krouzky$hodnoty.bez)\nqqline(krouzky$hodnoty.bez)\nhist(krouzky$hodnoty.bez)\n# Šikmost i špičatost odpovídá norm. rozdělení. \n# Pro konečné rozhodnutí o normalitě dat použijeme\n\n# test normality.\n# Předpoklad normality ověříme Shapirovovým . Wilkovovým testem.\nshapiro.test(krouzky$hodnoty.bez)\n# p-value > 0.05 -> Na hl. významnosti 0,05 nelze předpoklad norm. zamítnout \n\n# test na míru variability -> test o rozptylu\n\n# H0: sigma = 0,05 mm\n# Ha: sigma < 0,05 mm\nEnvStats::varTest(krouzky$hodnoty.bez, sigma.squared = 0.05^2,\n alternative = \"less\")\n\n# p-value < 0.05 -> Na hladině významnosti 0,05 zamítáme H0 ve prospěch Ha \n\n# Jak najít 95% intervalový odhad směrodatné odchylky?\npom = EnvStats::varTest(krouzky$hodnoty.bez, sigma.squared = 0.05^2,\n alternative = \"less\", conf.level=0.95)\n\nsqrt(pom$conf.int)\n\n# * Příklad 5. ####\n# Firma TT udává, že 1% jejich rezistorů nesplňuje požadovaná kritéria. V testované\n# dodávce 1000 ks bylo nalezeno 15 nevyhovujících rezistorů. Potvrzuje tento výsledek\n# tvrzení TT? Ověřte čistým testem významnosti.\n\n\nn = 1000 # rozsah výběru \nx = 15 # počet \"úspěchů\"\np = x/n # relativní četnost (bodový odhad pravděpodobnosti)\np \n\n# Ověření předpokladů\n9/(p*(1-p))\n# Dále předpokládáme n/N < 0.05, tj. že daná populace (rezistorů) má rozsah \n# alespoň 1000/0.05 = 1000*20 = 20 000 rezistorů\n\n## Clopperův - Pearsonův (exaktní) test\n## H0: pi = 0.01\n## Ha: pi <> 0.01\n\nbinom.test(x = x, n= n, p = 0.01, alternative=\"two.sided\")\n\n## Clopperův - Pearsonův (exaktní) test\n## H0: pi = 0.01\n## Ha: pi > 0.01\n\nbinom.test(x = x, n= n, p = 0.01, alternative=\"greater\")\n\n# Na hladině významnosti 0,05 nezamítáme H0 \n# Nelze očekávat, že podíl vadných rezistorů ve výrobě statisticky významně\n# převyšuje 1 %.\n\n\n\n", "meta": {"hexsha": "91a2ec0a8368b9b00f01a384261e09ff7dd46885", "size": 17101, "ext": "r", "lang": "R", "max_stars_repo_path": "CV10/cv10.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": "CV10/cv10.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": "CV10/cv10.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": 32.5114068441, "max_line_length": 92, "alphanum_fraction": 0.6962165955, "num_tokens": 7292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5974511525247399}} {"text": "#' Negative log likelihood function\n#'\n#' We're maximizing the likelihood function, so minimizing the negative log\n#' likelihood (which is the default in optim)\n#'\n#' @param par numeric vector of coefficients in ’x’ and theta\n#' @param .x design matrix of dimension ‘n * p’\n#' @param .y vector of observations of length ‘n’\n#' @param weights vector of weights of length ‘n’\n#' @param offset vector of coefficient offsets of length ‘n’\n#' @param verbose print debug messages\n#' @return negative log-likelihood of a set of paramters given the data\nnll = function(par, .x, .y, weights=rep(1, nrow(.x)), offset=rep(0, nrow(.x)),\n .verbose=FALSE) {\n beta = par[-length(par)]\n theta = exp(par[length(par)])\n mu = .x %*% beta + offset\n\n if (.verbose)\n message(paste(sprintf(\"%.2f\", par), collapse=\", \"))\n\n nb = suppressWarnings(stats::dnbinom(.y, mu=mu, size=theta, log=TRUE))\n nb[is.infinite(nb)] = sign(nb[is.infinite(nb)]) * 1000\n nb[is.na(nb)] = -mu[is.na(nb)] # penalize mu < 0\n -sum(weights * nb)\n}\n", "meta": {"hexsha": "2b2d75eca9f800f927a6d677d0ce27c1f456167e", "size": 1050, "ext": "r", "lang": "R", "max_stars_repo_path": "R/nll.r", "max_stars_repo_name": "mschubert/boundie", "max_stars_repo_head_hexsha": "f7911257acf9be1d3da3528980eee4da83e3e326", "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/nll.r", "max_issues_repo_name": "mschubert/boundie", "max_issues_repo_head_hexsha": "f7911257acf9be1d3da3528980eee4da83e3e326", "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/nll.r", "max_forks_repo_name": "mschubert/boundie", "max_forks_repo_head_hexsha": "f7911257acf9be1d3da3528980eee4da83e3e326", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8888888889, "max_line_length": 78, "alphanum_fraction": 0.6466666667, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5974024467415928}} {"text": "#CustomMath.r\n#A collection of relatively basic functions.\n\nMeanNA <- function(Vec) {\n #Replaces NA instances with their mean instead\n m <- mean(Vec, na.rm = TRUE)\n Vec[is.na(Vec)] <- m\n return(Vec)\n}\n\nGetWeight <- function(Vec,AddMean=FALSE) {\n #Takes a Vector, absolute value, then proportional linear deviance from 0.\n new <- abs(Vec)\n if(AddMean==1) new <- new + mean(new)\n if(sum(new)==0) new <- new + 1\n new <- new/sum(new)\n return(new)\n}\n\nCatch <- function(X,Tolerance=0) {\n #x is the ConoutRAW numeric, Tolerance is the length of the midpoint corresponding to .5 \n #The purpose here is to handle rounding for binary contracts\n if(X<(.5-(Tolerance/2))) return(0)\n else if(X>(.5+(Tolerance/2))) return(1)\n else return(.5)\n}\n\nInfluence <- function(Weight) {\n #Takes a normalized Vector (one that sums to 1), and computes relative strength of the indicators.\n #this is because by-default the conformity of each Author and Judge is expressed relatively.\n Expected <- rep(1/length(Weight),length(Weight))\n return( Weight / Expected)\n}\n\nReWeight <- function(Vec,exclude=is.na(Vec)) {\n #Get the relative influence of numbers, treat NA as influence-less\n out <- Vec\n out[exclude] <- 0\n out <- out/sum(out)\n return(out)\n}\n\nReverseMatrix <- function(Mat) {\n #Inverts a binary matrix\n return((Mat-1)*-1)\n}\n\nWeightedPrinComp <- function(X,Weights=ReWeight(rep(1,nrow(M))) ) {\n #Manually computes the statistical procedure known as Principal Components Analysis (PCA)\n #This version of the procedure is so basic, that it can also be thought of as merely a singular-value decomposition on a weighted covariance matrix.\n \n wCVM <- cov.wt(x=X,wt=Weights)\n \n L <- svd(wCVM$cov)$u[,1]\n S <- as.vector(scale(X,center=wCVM$center,scale= FALSE) %*% L)\n \n Out <- list(\"Scores\"=S,\"Loadings\"=L)\n return(Out)\n}", "meta": {"hexsha": "b62a767cb1d5a772cdb9513e2fa0febab1c7e8ee", "size": 1830, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/consensus/Old/CustomMath.r", "max_stars_repo_name": "endolith/Truthcoin", "max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 161, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z", "max_issues_repo_path": "lib/consensus/Old/CustomMath.r", "max_issues_repo_name": "endolith/Truthcoin", "max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z", "max_forks_repo_path": "lib/consensus/Old/CustomMath.r", "max_forks_repo_name": "endolith/Truthcoin", "max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z", "avg_line_length": 31.0169491525, "max_line_length": 150, "alphanum_fraction": 0.6928961749, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5973902328545225}} {"text": "#### 일원 분산분석(One-way ANOVA) #####\n\n# 01.데이터 불러오기 \nowa.df <- read.csv(\"Ch0903.교육역량분석.csv\", \n header=TRUE, \n na.strings = \".\")\n\nowa.df$학년 <- factor(owa.df$학년,\n levels = c(1:4),\n labels = c(\"1학년\",\"2학년\",\"3학년\",\"4학년\"))\n\nstr(owa.df)\nhead(owa.df)\n\n# 02.기본통계치 확인\nlibrary(psych)\ndescribeBy(owa.df$비교과운영, \n owa.df$학년, \n mat=T) # 합쳐서 하나의 표로 보여줄지, 따로 그룹별로 보여줄지 나타내는 옵션 \n\n\n# 03.그래프 그리기(박스그래프,히스토그램)\n# install.packages(\"ggplot2\")\n\nlibrary(ggplot2)\n\nggplot(owa.df, aes(x = 학년, y = 비교과운영)) + #aes 축\n geom_boxplot(outlier.colour=\"red\") + #이상치를 레드로 하라\n ggtitle(\"학년별 점수 차이\") +\n theme_classic() + # ggplot2 테마\n theme(title = element_text(color=\"darkblue\", size=20))\n\n# facet_grid(); 그룹으로 구분- 범주형 변수\n# facet_grid(.~); 수직\n# facet_grid(~.); 가로\n\nggplot(owa.df, aes(x=비교과운영)) + \n geom_histogram(binwidth=10) + \n facet_grid(.~ 학년) +\n ggtitle(\"매장별 만족도\") + \n theme_classic()\n\n# 04.통계분석\n# 등분산 검증\n# 이분산일때는 하단의 부록(Welch's ANOVA test) 참조\nbartlett.test(비교과운영 ~ 학년, data=owa.df)\n\n# barlett test는 정규분포에 민감하기 때문에 leveneTest 많이 사용\n# install.packages(\"car\")\nlibrary(car)\ncar::leveneTest(비교과운영 ~ 학년, data=owa.df) # 레벤의 검증은 library(car)에 있다. \n\n# 등분산일때 ANOVA분석\nowa.result <- aov(비교과운영 ~ 학년, data=owa.df) \n\nowa.result\n\nsummary(owa.result)\n\n# 부록: 이분산일때 Welch's ANOVA test\noneway.test(owa.df$비교과운영 ~ owa.df$학년, data=owa.df, \n var.equal = FALSE)\n\n\n# 사후검정(Multicamparison test )\n# Fisher LSD\npairwise.t.test(owa.df$비교과운영, \n owa.df$학년, \n data=owa.df, \n p.adj=\"non\") # 많이 않쓰임. 오차가 크기 때문에 \n\n# Bonferroni, Tukey HSD, Duncan LSR\npairwise.t.test(owa.df$비교과운영, \n owa.df$학년, \n data=owa.df, \n p.adj=\"bonf\") # 여기서비교하는 방법을 알려줌. 이것은 유의확률을 보여줌. 강남-강동 차이 있음 \n\n# Tukey HSD, Duncan LSR\nTukeyHSD(owa.result) # 결과값으로 바로 보여줌 (분산분석 결과치를 데이타프레임으로 저장하고 입력)\n\n\n\n\n# 학년으로 표현\n# install.packages(\"agricolae\")\nlibrary(agricolae)\n\n# console=TRUE: 결과를 화면에 표시\n# 학년=TRUE: 그룹으로 묶어서 표시, FALSE: 1:1로 비교하여 다 보여줌, 다른 것끼리 구분되는 것 \nLSD.test(owa.result, \n \"학년\", \n console = T, \n p.adj=\"bonf\")\nduncan.test(owa.result, \n \"학년\", \n group=T, \n console = T)\nscheffe.test(owa.result, \n \"학년\", \n group=T, \n console = T)\n\n\n\n\n# 05.통계결과 그래프\ntukeyPlot <- TukeyHSD(owa.result) # 그룹간 차이 비교\nplot(tukeyPlot) # 0을 거치고 있다는 것은 차이가 없다는 뜻임\n\n\n\n\n# 부록: 비모수통계분석 Kruskal Wallis H test \nkruskal.test(owa.df$비교과운영 ~ owa.df$학년, \n data=owa.df)\n# install.packages(\"userfriendlyscience\")\nlibrary(userfriendlyscience)\nposthocTGH(owa.df$비교과운영, \n owa.df$학년)\n\n\n# install.packages(\"nparcomp\") # 비모수 검정에서 다중 비교 방식 \nlibrary(nparcomp)\nresult = mctp(owa.df$비교과운영 ~ owa.df$학년, \n data=owa.df)\nsummary(result)\n", "meta": {"hexsha": "34f87266bc1005fa45e30e6ebbed41e8541ff4df", "size": 2813, "ext": "r", "lang": "R", "max_stars_repo_path": "ch09 - 분산분석 1/사례1.r", "max_stars_repo_name": "Lee-changyul/Rstudy_Lee", "max_stars_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch09 - 분산분석 1/사례1.r", "max_issues_repo_name": "Lee-changyul/Rstudy_Lee", "max_issues_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch09 - 분산분석 1/사례1.r", "max_forks_repo_name": "Lee-changyul/Rstudy_Lee", "max_forks_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1496062992, "max_line_length": 76, "alphanum_fraction": 0.5879843583, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5972547235974348}} {"text": "#' High-Dimensional Regularized Discriminant Analysis (HDRDA)\n#'\n#' Given a set of training data, this function builds the HDRDA classifier from\n#' Ramey, Stein, and Young (2017). Specially designed for small-sample,\n#' high-dimensional data, the HDRDA classifier incorporates dimension reduction\n#' and covariance-matrix shrinkage to enable a computationally efficient\n#' classifier.\n#'\n#' The HDRDA classifier utilizes a covariance-matrix estimator that is a convex\n#' combination of the covariance-matrix estimators used in the Linear\n#' Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA)\n#' classifiers. For each of the `K` classes given in `y`,\n#' \\eqn{(k = 1, \\ldots, K)}, we first define this convex combination as\n#' \\deqn{\\hat{\\Sigma}_k(\\lambda) = (1 - \\lambda) \\hat{\\Sigma}_k\n#' + \\lambda \\hat{\\Sigma},}\n#' where \\eqn{\\lambda \\in [0, 1]} is the _pooling_ parameter. We then\n#' calculate the covariance-matrix estimator\n#' \\deqn{\\tilde{\\Sigma}_k = \\alpha_k \\hat{\\Sigma}_k(\\lambda) + \\gamma I_p,}\n#' where \\eqn{I_p} is the \\eqn{p \\times p} identity matrix. The matrix\n#' \\eqn{\\tilde{\\Sigma}_k} is substituted into the HDRDA classifier. See Ramey et\n#' al. (2017) for more details.\n#'\n#' The matrix of training observations are given in `x`. The rows of\n#' `x` contain the sample observations, and the columns contain the features\n#' for each training observation. The vector of class labels given in `y`\n#' are coerced to a `factor`. The length of `y` should match the number\n#' of rows in `x`.\n#'\n#' The vector `prior` contains the _a priori_ class membership for\n#' each class. If `prior` is `NULL` (default), the class membership\n#' probabilities are estimated as the sample proportion of observations\n#' belonging to each class. Otherwise, `prior` should be a vector with the\n#' same length as the number of classes in `y`. The `prior`\n#' probabilities should be nonnegative and sum to one. The order of the prior\n#' probabilities is assumed to match the levels of `factor(y)`.\n#'\n#' @export\n#' @references Ramey, J. A., Stein, C. K., and Young, D. M. (2017),\n#' \"High-Dimensional Regularized Discriminant Analysis.\"\n#' \\url{https://arxiv.org/abs/1602.01182}.\n#' @references Friedman, J. H. (1989), \"Regularized Discriminant Analysis,\"\n#' Journal of American Statistical Association, 84, 405, 165-175.\n#' \\url{http://www.jstor.org/pss/2289860} (Requires full-text access).\n#' @inheritParams lda_diag\n#' @param y vector of class labels for each training observation\n#' @param lambda the HDRDA pooling parameter. Must be between 0 and 1,\n#' inclusively.\n#' @param gamma a numeric values used for the shrinkage parameter.\n#' @param shrinkage_type the type of covariance-matrix shrinkage to apply. By\n#' default, a ridge-like shrinkage is applied. If `convex` is given, then\n#' shrinkage similar to Friedman (1989) is applied. See Ramey et al. (2017) for\n#' details.\n#' @param prior vector with prior probabilities for each class. If `NULL`\n#' (default), then the sample proportion of observations belonging to each class\n#' equal probabilities are used. See details.\n#' @param tol a threshold for determining nonzero eigenvalues.\n#' @return `rda_high_dim` object that contains the trained HDRDA classifier\nrda_high_dim <- function(x, ...) {\n UseMethod(\"rda_high_dim\")\n}\n\n#' @rdname rda_high_dim\n#' @export\nrda_high_dim.default <- function(x, y, lambda = 1, gamma = 0,\n shrinkage_type = c(\"ridge\", \"convex\"), prior = NULL,\n tol = 1e-6, ...) {\n x <- pred_to_matrix(x)\n y <- outcome_to_factor(y)\n complete <- complete.cases(x) & complete.cases(y)\n x <- x[complete,,drop = FALSE]\n y <- y[complete]\n lambda <- as.numeric(lambda)\n gamma <- as.numeric(gamma)\n shrinkage_type <- match.arg(shrinkage_type)\n \n if (lambda < 0 || lambda > 1) {\n rlang::abort(\"The value for 'lambda' must be between 0 and 1, inclusively.\")\n }\n \n if (gamma < 0) {\n rlang::abort(\"The value for 'gamma' must be nonnegative.\")\n }\n \n obj <- regdiscrim_estimates(x = x, y = y, cov = FALSE, prior = prior, ...)\n x_centered <- center_data(x = x, y = y)\n K <- obj$num_groups\n \n # Computes the eigenvalue decomposition of the pooled sample covariance matrix\n # using the Fast SVD approach.\n cov_pool_eigen <- cov_eigen(x = x, y = y, pool = TRUE, fast = TRUE, tol = tol)\n \n obj$D_q <- cov_pool_eigen$values\n obj$U1 <- cov_pool_eigen$vectors\n obj$q <- length(obj$D_q)\n obj$shrinkage_type <- shrinkage_type\n obj$lambda <- lambda\n obj$gamma <- gamma\n \n if (shrinkage_type == \"ridge\") {\n alpha <- 1\n } else {\n # shinkage_family == \"convex\"\n alpha <- 1 - gamma\n }\n \n # Transforms the centered data\n XU <- x_centered %*% obj$U1\n \n # For each class, we calculate the following quantities necessary to train the\n # HDRDA classifier.\n # 1. \\Gamma_k\n # 2. Q_k\n # 3. W_k^{-1}\n for (k in seq_len(K)) {\n X_k <- x_centered[y == levels(y)[k], , drop=FALSE]\n n_k <- nrow(X_k)\n \n # Extracts the transformed, centered data\n # No need to calculate it for the classes individually\n XU_k <- XU[y == levels(y)[k], , drop=FALSE]\n \n # Transforms the sample mean to the lower dimension\n xbar_U1 <- crossprod(obj$U1, obj$est[[k]]$xbar)\n \n # In the special case that (lambda, gamma) = (0, 0), the improvements to\n # HDRDA's speed via the Sherman-Woodbury formula are not applicable because\n # Gamma = 0. In this case, we calculate W_inv directly. If the matrix is\n # singular, a slight amount of shrinkage is applied.\n if (lambda == 0 && gamma == 0) {\n W_k <- cov_mle(XU_k)\n W_inv <- try(solve_chol(W_k), silent=TRUE)\n \n if (inherits(W_inv, \"try-error\")) {\n W_k <- W_k + diag(0.001, nrow=nrow(W_k), ncol=ncol(W_k))\n W_inv <- solve_chol(W_k)\n }\n \n Gamma <- matrix(0, nrow=obj$q, ncol=obj$q)\n Q <- diag(n_k)\n } else {\n # Although 'Gamma_k' is a diagonal matrix, we store only its diagonal\n # elements.\n Gamma <- alpha * lambda * obj$D_q + gamma\n Gamma_inv <- diag(Gamma^(-1))\n \n # X_k %*% U_1 %*% Gamma^{-1} is computed repeatedly in the equations.\n # We compute the matrix once and use it where necessary to avoid\n # unnecessary computations.\n XU_Gamma_inv <- XU_k %*% Gamma_inv\n Q <- diag(n_k) + alpha * (1 - lambda) / n_k * tcrossprod(XU_Gamma_inv, XU_k)\n W_inv <- alpha * (1 - lambda) / n_k * crossprod(XU_Gamma_inv, solve(Q, XU_Gamma_inv))\n W_inv <- Gamma_inv - W_inv\n }\n \n obj$est[[k]]$n_k <- n_k\n obj$est[[k]]$alpha <- alpha\n obj$est[[k]]$XU <- XU_k\n obj$est[[k]]$xbar_U1 <- xbar_U1\n obj$est[[k]]$Gamma <- Gamma\n obj$est[[k]]$Q <- Q\n obj$est[[k]]$W_inv <- W_inv\n }\n \n # Creates an object of type 'rda_high_dim'\n obj$col_names <- colnames(x)\n obj <- new_discrim_object(obj, \"rda_high_dim\")\n \n obj\n}\n\n#' @inheritParams lda_diag\n#' @rdname rda_high_dim\n#' @importFrom stats model.frame model.matrix model.response\n#' @export\nrda_high_dim.formula <- function(formula, data, ...) {\n # The formula interface includes an intercept. If the user includes the\n # intercept in the model, it should be removed. Otherwise, errors and doom\n # happen.\n # To remove the intercept, we update the formula, like so:\n # (NOTE: The terms must be collected in case the dot (.) notation is used)\n formula <- no_intercept(formula, data)\n \n mf <- model.frame(formula = formula, data = data)\n .terms <- attr(mf, \"terms\")\n x <- model.matrix(.terms, data = mf)\n y <- model.response(mf)\n \n est <- rda_high_dim.default(x = x, y = y, ...)\n est$.terms <- .terms\n est <- new_discrim_object(est, class(est))\n est\n}\n\n#' Outputs the summary for a HDRDA classifier object.\n#'\n#' Summarizes the trained rda_high_dim classifier in a nice manner.\n#'\n#' @param x object to print\n#' @param ... unused\n#' @keywords internal\n#' @export\nprint.rda_high_dim <- function(x, ...) {\n cat(\"High-Dimensional Regularized Discriminant Analysis\\n\\n\")\n print_basics(x, ...)\n cat(\"\\nReduced dimension:\", x$q, \"\\n\")\n cat(\"Shrinkage type:\", x$shrinkage_type, \"\\n\")\n cat(\"Lambda:\", signif(x$lambda, 3), \"Gamma:\", signif(x$gamma, 3), \"\\n\")\n invisible(x)\n}\n\n#' Predicts the class membership of a matrix of unlabeled observations with a\n#' trained HDRDA classifier.\n#'\n#' For a given `rda_high_dim` object, we predict the class of each observation\n#' (row) of the the matrix given in `newdata`.\n#'\n#' @rdname rda_high_dim\n#' @inheritParams predict.lda_diag\n#' @export\n#' @param object Object of type `rda_high_dim` that contains the trained HDRDA\n#' classifier\n#' @param projected logical indicating whether `newdata` have already been\n#' projected to a q-dimensional subspace. This argument can yield large gains in\n#' speed when the linear transformation has already been performed.\n#' @return list with predicted class and discriminant scores for each of the K\n#' classes\npredict.rda_high_dim <- function(object, newdata, projected = FALSE, type = c(\"class\", \"prob\", \"score\"), ...) {\n type <- rlang::arg_match0(type, c(\"class\", \"prob\", \"score\"), arg_nm = \"type\")\n newdata <- process_newdata(object, newdata)\n \n scores <- sapply(object$est, function(class_est) {\n if (object$lambda == 0 && object$gamma == 0) {\n # Want: log(det(W_k)) = -log(det(W_k_inv))\n log_det <- -log_determinant(class_est$W_inv)\n } else {\n log_det <- log_determinant(class_est$Q)\n }\n \n if (projected) {\n # The newdata have already been projected. Yay for speed!\n # Center the 'newdata' by the projected class sample mean\n U1_x <- scale(newdata, center = class_est$xbar_U1, scale = FALSE)\n \n quad_forms <- diag(drop(tcrossprod(U1_x %*% class_est$W_inv, U1_x)))\n } else {\n # Center the 'newdata' by the class sample mean\n x_centered <- scale(newdata, center = class_est$xbar, scale = FALSE)\n \n U1_x <- crossprod(object$U1, t(x_centered))\n \n quad_forms <- apply(U1_x, 2, function(z) {\n quadform(class_est$W_inv, z)\n })\n }\n \n quad_forms + log_det - 2 * log(class_est$prior)\n })\n \n if (is.vector(scores)) {\n # When sapply above returns a vector, the naming is thrown off.\n # Hence, we rename it to the groups.\n names(scores) <- object$groups\n \n min_scores <- min_index(scores)\n posterior <- exp(-(scores - min(scores)))\n posterior <- posterior / sum(posterior)\n } else {\n min_scores <- apply(scores, 1, min_index)\n # Grabbed code to calculate 'posterior' from MASS:::predict.qda, which\n # handles numerical overflow unlike the more direct:\n # exp(scores) / (1 + exp(sum(scores)))\n posterior <- exp(-(scores - apply(scores, 1, min)))\n posterior <- posterior / rowSums(posterior)\n }\n \n if (type == \"prob\") {\n if (is.vector(posterior)) {\n posterior <- matrix(posterior, nrow = 1)\n colnames(posterior) <- object$groups\n }\n res <- as.data.frame(posterior)\n } else if (type == \"class\") {\n res <- with(object, factor(groups[min_scores], levels = groups))\n } else {\n if (is.vector(scores)) {\n scores <- matrix(scores, nrow = 1)\n colnames(scores) <- object$groups\n }\n res <- as.data.frame(scores)\n }\n res\n}\n\n#' Helper function to optimize the HDRDA classifier via cross-validation\n#'\n#' For a given data set, we apply cross-validation (cv) to select the optimal\n#' HDRDA tuning parameters.\n#'\n#' The number of cross-validation folds is given in `num_folds`.\n#'\n#' @export\n#' @importFrom dplyr arrange\n#' @inheritParams lda_diag\n#' @param y vector of class labels for each training observation\n#' @param num_folds the number of cross-validation folds.\n#' @param num_lambda The number of values of `lambda` to consider\n#' @param num_gamma The number of values of `gamma` to consider\n#' @param shrinkage_type the type of covariance-matrix shrinkage to apply. By\n#' default, a ridge-like shrinkage is applied. If `convex` is given, then\n#' shrinkage similar to Friedman (1989) is applied. See Ramey et al. (2017) for\n#' details.\n#' @param verbose If set to `TRUE`, summary information will be outputted\n#' as the optimal model is being determined.\n#' @param ... Options passed to [rda_high_dim()].\n#' @return list containing the HDRDA model that minimizes cross-validation as\n#' well as a `data.frame` that summarizes the cross-validation results.\nrda_high_dim_cv <- function(x, y, num_folds = 10, num_lambda = 21, num_gamma = 8,\n shrinkage_type=c(\"ridge\", \"convex\"), verbose=FALSE, ...) {\n x <- pred_to_matrix(x)\n y <- outcome_to_factor(y)\n complete <- complete.cases(x) & complete.cases(y)\n x <- x[complete,,drop = FALSE]\n y <- y[complete]\n shrinkage_type <- match.arg(shrinkage_type)\n \n cv_folds <- cv_partition(y = y, num_folds = num_folds)\n \n # The grid of tuning parameters\n # We sort the grid by model preference. Models with lambda = 0 are most\n # preferred because they assume that the covariance matrices are equal. This\n # preference is further based on model parsimony.\n seq_lambda <- seq(0, 1, length = num_lambda)\n \n if (shrinkage_type == \"ridge\") {\n seq_gamma <- c(0, 10^seq.int(-2, num_gamma - 4))\n } else {\n # shrinkage_type == \"convex\"\n seq_gamma <- seq(0, 1, length = num_gamma)\n }\n \n tuning_grid <- expand.grid(lambda = seq_lambda, gamma = seq_gamma)\n tuning_grid <- dplyr::arrange(tuning_grid, lambda, gamma)\n \n cv_errors <- sapply(seq_along(cv_folds), function(fold_i) {\n if (verbose) {\n cat(\"CV Fold: \", fold_i, \" of \", num_folds, \"\\n\")\n }\n fold <- cv_folds[[fold_i]]\n train_x <- x[fold$training, ]\n train_y <- y[fold$training]\n test_x <- x[fold$test, ]\n test_y <- y[fold$test]\n \n hdrda_out <- rda_high_dim(x = train_x, y = train_y, lambda = 1, gamma = 0, ...)\n \n # Projects the test data to the q-dimensional subspace.\n # No need to do this for each lambda/gamma pair.\n # NOTE: It's not centered yet.\n test_x <- test_x %*% hdrda_out$U1\n \n # For each value of lambda and gamma, we train the HDRDA classifier,\n # classify the test observations, and record the number of classification\n # errors.\n fold_errors <- mapply(function(lambda, gamma) {\n errors <- try({\n # Updates Gamma, Q, and W_inv for each class in hdrda_out\n # If an error is thrown, we return 'NA'.\n hdrda_updated <- update_rda_high_dim(hdrda_out, lambda, gamma)\n # Call to predict.rda_high_dim is explicit to pass R CMD CHECK.\n sum(predict.rda_high_dim(hdrda_updated, test_x, projected = TRUE)$class != test_y)\n }, silent = TRUE)\n \n errors\n }, tuning_grid$lambda, tuning_grid$gamma)\n fold_errors\n })\n cv_errors <- rowSums(cv_errors)\n error_rate <- cv_errors / nrow(x)\n \n cv_summary <- cbind(tuning_grid, cv_errors, error_rate)\n \n optimal <- which.min(cv_errors)\n lambda <- tuning_grid$lambda[optimal]\n gamma <- tuning_grid$gamma[optimal]\n \n # Trains a classifier based on optimal model\n hdrda_out <- rda_high_dim(x=x, y=y, lambda=lambda, gamma=gamma,\n shrinkage_type=shrinkage_type)\n \n # Adds optimal parameters and cv_summary to classifier object\n hdrda_out$lambda <- lambda\n hdrda_out$gamma <- gamma\n hdrda_out$cv_summary <- cv_summary\n class(hdrda_out) <- c(\"hdrda_cv\", \"rda_high_dim\")\n \n hdrda_out\n}\n\n#' Plots a heatmap of cross-validation error grid for a HDRDA classifier object.\n#'\n#' Uses [ggplot2::ggplot2()] to plot a heatmap of the training error\n#' grid.\n#'\n#' @param x object to plot\n#' @param ... unused\n#' @export\n#' @importFrom ggplot2 ggplot aes scale_fill_gradient labs scale_x_discrete\n#' @importFrom ggplot2 scale_y_discrete theme labs geom_tile element_blank\nplot.rda_high_dim_cv <- function(x, ...) {\n cv_summary <- x$cv_summary\n cv_summary <- within(cv_summary, {\n lambda <- round(lambda, 3)\n gamma <- round(gamma, 3)\n })\n \n # Fixes NOTE from R CMD CHECK\n # \"no visible binding for global variable 'error_rate'\"\n error_rate <- 1\n \n p <- ggplot(cv_summary, aes(factor(gamma), factor(lambda)))\n p <- p + geom_tile(aes(fill=error_rate), colour=\"white\")\n p <- p + scale_fill_gradient(low=\"white\",\n high=\"steelblue\",\n name=\"CV Error Rate\")\n p <- p + labs(x=expression(gamma), y=expression(lambda))\n p <- p + scale_x_discrete(expand=c(0, 0))\n p <- p + scale_y_discrete(expand=c(0, 0))\n p <- p + theme(axis.ticks=element_blank())\n p\n}\n\n#' Helper function to update tuning parameters for the HDRDA classifier\n#'\n#' This function updates some of the quantities in the HDRDA classifier based on\n#' updated values of `lambda` and `gamma`. The update can greatly\n#' expedite cross-validation to examine a large grid of values for `lambda`\n#' and `gamma`.\n#'\n#' @param obj a `rda_high_dim` object\n#' @param lambda a numeric value between 0 and 1, inclusively\n#' @param gamma a numeric value (nonnegative)\n#' @return a `rda_high_dim` object with updated estimates\nupdate_rda_high_dim <- function(obj, lambda = 1, gamma = 0) {\n # In the special case that (lambda, gamma) = (0, 0), the improvements to\n # HDRDA's speed via the Sherman-Woodbury formula are not applicable because\n # Gamma = 0. In this case, we calculate W_inv directly.\n if (lambda == 0 && gamma == 0) {\n Gamma <- matrix(0, nrow=obj$q, ncol=obj$q)\n } else {\n # NOTE: alpha_k is constant across all classes, so that alpha_k = alpha_1\n # for all k. As a result, Gamma and Gamma_inv are constant across all k. We\n # compute both before looping through all K classes.\n Gamma <- obj$est[[1]]$alpha * lambda * obj$D_q + gamma\n Gamma_inv <- diag(Gamma^(-1))\n }\n \n for (k in seq_len(obj$num_groups)) {\n n_k <- obj$est[[k]]$n_k\n if (lambda == 0 && gamma == 0) {\n Q <- diag(n_k)\n \n W_k <- cov_mle(obj$est[[k]]$XU)\n W_inv <- try(solve_chol(W_k), silent=TRUE)\n if (inherits(W_inv, \"try-error\")) {\n W_k <- W_k + diag(0.001, nrow=nrow(W_k), ncol=ncol(W_k))\n W_inv <- solve_chol(W_k)\n }\n }\n else {\n # X_k %*% U_1 %*% Gamma^{-1} is computed repeatedly in the equations.\n # We compute the matrix once and use it where necessary to avoid\n # unnecessary computations.\n XU_Gamma_inv <- obj$est[[k]]$XU %*% Gamma_inv\n Q <- diag(n_k) +\n obj$est[[k]]$alpha * (1 - lambda) / n_k * tcrossprod(XU_Gamma_inv, obj$est[[k]]$XU)\n \n W_inv <- obj$est[[k]]$alpha * (1 - lambda) / n_k *\n crossprod(XU_Gamma_inv, solve(Q, XU_Gamma_inv))\n W_inv <- Gamma_inv - W_inv\n }\n obj$est[[k]]$Gamma <- Gamma\n obj$est[[k]]$Q <- Q\n obj$est[[k]]$W_inv <- W_inv\n }\n obj$lambda <- lambda\n obj$gamma <- gamma\n obj\n}\n", "meta": {"hexsha": "9921cc0dfad0ebd975ba488dcc624c52a53a000a", "size": 18697, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rda-high-dim.r", "max_stars_repo_name": "topepo/sparsediscrim", "max_stars_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:44:00.000Z", "max_issues_repo_path": "R/rda-high-dim.r", "max_issues_repo_name": "topepo/sparsediscrim", "max_issues_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:02:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:00:06.000Z", "max_forks_repo_path": "R/rda-high-dim.r", "max_forks_repo_name": "topepo/sparsediscrim", "max_forks_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_forks_repo_licenses": ["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.2351738241, "max_line_length": 111, "alphanum_fraction": 0.6606407445, "num_tokens": 5292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5971022676999347}} {"text": "library(FinancialMath)\n\n# liczba dotad splaconych rat\nlba_splaconych_rat <- 174\n\n# wektor liczby dni w miesiacu: rok zwykly\ndni_w_roku <- c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n\n# wektor liczby dni w miesiacu: rok przestepny\ndni_w_roku_p <- replace(dni_w_roku, dni_w_roku==28, 29)\n\n# wektor liczby dni w miesiacu dla kolejnej raty\nwek_dni_w_mies <- c(dni_w_roku[7:12], rep(c(dni_w_roku, dni_w_roku_p, dni_w_roku, dni_w_roku), length.out=353))\n\n# wektor liczby dni w roku dla kolejnej raty\nwek_dni_w_roku <- c(rep(365, times=6), rep(rep(c(365,366,365,365), each=12), length.out=353))\n\n# na podstawie § 11 ust 7 rok liczy zawsze 365 dni\ndni_w_roku_sum <- sum(dni_w_roku)\n\n# wektory z wysokoscia rat pobranych przez mBank\nraty_pobrane <- rep(c(479.42, 334.69, 306.84, 306.83, 306.84, 318.53, 330.45, 342.35, 332.86, 327.42, 316.68, 290.48), times=c(1,1,1,1,1,2,6,20,10,6,55,70))\n\n# wczytanie danych z kursami walut\nkursy_walut <- read.csv('~/R/mBank/kursy_walut.csv', header = TRUE)\n\n# daty ksiegowania rat\ndata_ksiegowania <- as.vector(kursy_walut$data)\n\n\n##########################################\n#\n# rata #1\n#\n##########################################\nkapital_poczatkowy <- 72161.65\noprocentowanie <- 3.45\npoz_lba_rat <- 359\ndni_w_mcu <- c(\"cze\" = 23, \"lip\" = 31)\n##########################################\ncat(\"----------- rata #1 -----------\\n\")\n\n# wyliczenie raty kapitalowo-odsetkowej wylacznie w miesiacu lipcu\noprocentowanie <- oprocentowanie / 100\nrata_calkowita <- amort.period(Loan = kapital_poczatkowy, n = poz_lba_rat, i = oprocentowanie, ic = 12, pf = 12)\nrata_calkowita <- round(rata_calkowita[2], digits = 2)\n\n# wyliczenie raty odsetkowej: suma odsetek w miesiącach czerwiec oraz lipiec\nrata_odsetkowa <- dni_w_mcu / dni_w_roku_sum * kapital_poczatkowy * oprocentowanie\ncat(\"rata_odsetkowa[1] =\", round(sum(rata_odsetkowa), digits = 2), \"\\n\")\n\n# wyliczenie raty kapitalowej\nrata_kapitalowa <- rata_calkowita - round(as.vector(rata_odsetkowa[\"lip\"]), digits = 2)\ncat(\"rata_kapitalowa[1] =\", rata_kapitalowa, \"\\n\")\n\n# kapital pozostajacy do splaty po racie #1\nkapital <- kapital_poczatkowy - rata_kapitalowa\ncat(\"kapital_do_splaty[1] =\", kapital, \"\\n\\n\")\n\nharmonogram <- data.frame(termin_splaty = data_ksiegowania[1], \n kwota_kapitalu = as.vector(rata_kapitalowa),\n kwota_odsetek = round(sum(rata_odsetkowa), digits = 2),\n kwota_raty_lacznie = rata_calkowita + round(as.vector(rata_odsetkowa[\"cze\"]), digits = 2),\n saldo_zadluzenia_po_splacie_raty = kapital, \n nadplata = 0)\n\n\n\n\n\n##########################################\n#\n# rata #2\n#\n##########################################\noprocentowanie <- c(3.45,2.45)\noprocentowanie_mB <- 3.75 # oprocentowanie ustalone przez mBank\ndni_oprocentowania <- c(1,30) # jeden dzień z oprocentowaniem 3,45% oraz 30 dni z oprocentowaniem 2,45%\npoz_lba_rat <- 358\n##########################################\ncat(\"----------- rata #2 -----------\\n\")\n\n# wyliczenie raty calkowitej\noprocentowanie <- oprocentowanie / 100\ndni_oprocentowania <- dni_oprocentowania / dni_w_roku_sum\nrata_calkowita <- amort.period(Loan = kapital, n = poz_lba_rat, i = oprocentowanie[1], ic = 12, pf = 12)\nrata_calkowita <- round(rata_calkowita[2], digits = 2)\n\n# wyliczenie raty odsetkowej\nrata_odsetkowa <- sum(kapital * oprocentowanie * dni_oprocentowania)\nrata_odsetkowa <- round(rata_odsetkowa, digits = 2)\ncat(\"rata_odsetkowa[2] =\", rata_odsetkowa, \"\\n\")\n\n# wyliczenie raty kapitalowej\nrata_kapitalowa <- rata_calkowita - rata_odsetkowa\ncat(\"rata_kapitalowa[2] =\", rata_kapitalowa, \"\\n\")\n\n# kapital pozostajacy do splaty po racie #2\nkapital_mB <- kapital\nkapital <- kapital - rata_kapitalowa\ncat(\"kapital_do_splaty[2] =\", kapital, \"\\n\")\n\n# wyliczenie nadplaty\noprocentowanie_mB <- oprocentowanie_mB / 100\nrata_calkowita_mB <- amort.period(Loan = kapital_mB, n = poz_lba_rat, i = oprocentowanie_mB, ic = 12, pf = 12)\nrata_calkowita_mB <- round(rata_calkowita_mB[2], digits = 2)\nnadplata <- rata_calkowita_mB - rata_calkowita\ncat(\"nadplata[2] =\", nadplata, \"\\n\\n\")\n\nharmonogram <- rbind(harmonogram, data.frame(termin_splaty = data_ksiegowania[2],\n kwota_kapitalu = rata_kapitalowa,\n kwota_odsetek = rata_odsetkowa,\n kwota_raty_lacznie = rata_calkowita,\n saldo_zadluzenia_po_splacie_raty = kapital, \n nadplata = nadplata))\n\n\n\n\n##########################################\n#\n# rata #3 i kolejne\n#\n##########################################\noprocentowanie = 2.45\npoz_lba_rat <- 357\n##########################################\ncat(\"---------- rata #3 + ----------\\n\")\n\n# wyliczenie raty calkowitej\noprocentowanie <- oprocentowanie / 100\nrata_calkowita <- amort.period(Loan = kapital, n = poz_lba_rat, i = oprocentowanie, ic = 12, pf = 12)\nrata_calkowita <- round(rata_calkowita[2], digits = 2)\ncat(\"rata_calkowita =\", rata_calkowita, \"\\n\\n\")\n\n# wyliczenie pozostalej czesci harmonogramu\nfor(rata in 3:359) {\n rata_odsetkowa <- round(kapital * oprocentowanie * wek_dni_w_mies[rata] / dni_w_roku_sum, digits = 2)\n rata_kapitalowa <- rata_calkowita - rata_odsetkowa\n kapital <- kapital - rata_kapitalowa\n \n harmonogram <- rbind(harmonogram, data.frame(termin_splaty = data_ksiegowania[rata],\n kwota_kapitalu = rata_kapitalowa,\n kwota_odsetek = rata_odsetkowa,\n kwota_raty_lacznie = rata_calkowita,\n saldo_zadluzenia_po_splacie_raty = kapital, \n nadplata = raty_pobrane[rata] - rata_calkowita))\n}\n\ncat(\"----- stan na 01.01.2021 -----\\n\")\nsplacony_kapital <- sum(harmonogram$kwota_kapitalu[1:lba_splaconych_rat])\nkapital_do_splaty <- kapital_poczatkowy - splacony_kapital\ncat(\"splacony_kapital =\", splacony_kapital, \"\\n\")\ncat(\"kapital_do_splaty =\", kapital_do_splaty, \"\\n\")\n\n\n\n\n##########################################\n#\n# wyliczenie nadplaty\n#\n##########################################\n# raty 1 do 82 liczone po kursie mBanku\nnadplata_PLN_mBank <- round(harmonogram$nadplata[1:82] * kursy_walut$kurs.mBank[1:82], digits = 2)\n\n# od raty 83 splata bezposrednio w CHF, nadplata liczona po kursie srednim NBP\nnadplata_PLN_NBP <- round(harmonogram$nadplata[83:lba_splaconych_rat] * kursy_walut$kurs.NBP[83:lba_splaconych_rat], digits = 2)\n\nnadplata_PLN <- c(nadplata_PLN_mBank, nadplata_PLN_NBP)\ncat(\"nadplata =\", sum(nadplata_PLN, na.rm=TRUE), \"PLN\\n\")\n", "meta": {"hexsha": "30898745b15956842afaeb6c82380dd759b062f0", "size": 6822, "ext": "r", "lang": "R", "max_stars_repo_path": "kredyt.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": "kredyt.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": "kredyt.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": 39.6627906977, "max_line_length": 156, "alphanum_fraction": 0.6180005863, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5970019202368908}} {"text": "#' Global Distance Metric Learning\r\n#'\r\n#' Performs Global Distance Metric Learning (GDM) on the given data, learning a diagonal matrix.\r\n#'\r\n#' Put GdmDiag function details here.\r\n#'\r\n#' @param data \\code{n * d} data matrix. \\code{n} is the number of data points,\r\n#' \\code{d} is the dimension of the data.\r\n#' Each data point is a row in the matrix.\r\n#' @param simi \\code{n * 2} matrix describing the similar constrains.\r\n#' Each row of matrix is serial number of a similar pair in the original data.\r\n#'\t\t\t\tFor example, pair(1, 3) represents the first observation is similar the 3th observation in the original data.\r\n#' @param dism \\code{n * 2} matrix describing the dissimilar constrains as \\code{simi}.\r\n#'\t\t\t\tEach row of matrix is serial number of a dissimilar pair in the original data.\r\n#' @param C0 numeric, the bound of similar constrains.\r\n#' @param threshold numeric, the threshold of stoping the learning iteration.\r\n#'\r\n#' @return list of the GdmDiag results:\r\n#' \\item{newData}{GdmDiag transformed data}\r\n#' \\item{diagonalA}{suggested Mahalanobis matrix}\r\n#' \\item{dmlA}{matrix to transform data, square root of diagonalA }\r\n#' \\item{error}{the precision of obtained distance metric by Newton-Raphson optimization }\r\n#'\r\n#' For every two original data points (x1, x2) in newData (y1, y2):\r\n#'\r\n#' \\eqn{(x2 - x1)' * A * (x2 - x1) = || (x2 - x1) * B ||^2 = || y2 - y1 ||^2}\r\n#'\r\n#' @keywords GDM global distance metirc learning transformation mahalanobis metric\r\n#'\r\n#' @note Be sure to check whether the dimension of original data and constrains' format are valid for the function.\r\n#'\r\n#' @author Gao Tao <\\url{http://www.gaotao.name}>\r\n#'\r\n#' @export GdmDiag\r\n#' @import MASS\r\n#'\r\n#' @references\r\n#' Steven C.H. Hoi, W. Liu, M.R. Lyu and W.Y. Ma (2003).\r\n#' Distance metric learning, with application to clustering with side-information.\r\n# in \\emph{Proc. NIPS}.\r\n#'\r\n\r\n#' @examples\r\n#' \\dontrun{\r\n#' set.seed(602)\r\n#' library(MASS)\r\n#' library(scatterplot3d)\r\n#'\r\n#' # generate simulated Gaussian data\r\n#' k = 100\r\n#' m <- matrix(c(1, 0.5, 1, 0.5, 2, -1, 1, -1, 3), nrow =3, byrow = T)\r\n#' x1 <- mvrnorm(k, mu = c(1, 1, 1), Sigma = m)\r\n#' x2 <- mvrnorm(k, mu = c(-1, 0, 0), Sigma = m)\r\n#' data <- rbind(x1, x2)\r\n#'\r\n#' # define similar constrains\r\n#' simi <- rbind(t(combn(1:k, 2)), t(combn((k+1):(2*k), 2)))\r\n#'\r\n#' temp <- as.data.frame(t(simi))\r\n#' tol <- as.data.frame(combn(1:(2*k), 2))\r\n#'\r\n#' # define disimilar constrains\r\n#' dism <- t(as.matrix(tol[!tol %in% simi]))\r\n#'\r\n#' # transform data using GdmDiag\r\n#' result <- GdmDiag(data, simi, dism)\r\n#' newData <- result$newData\r\n#' # plot original data\r\n#' color <- gl(2, k, labels = c(\"red\", \"blue\"))\r\n#' par(mfrow = c(2, 1), mar = rep(0, 4) + 0.1)\r\n#' scatterplot3d(data, color = color, cex.symbols = 0.6,\r\n#'\t\t\t xlim = range(data[, 1], newData[, 1]),\r\n#'\t\t\t ylim = range(data[, 2], newData[, 2]),\r\n#'\t\t\t zlim = range(data[, 3], newData[, 3]),\r\n#'\t\t\t main = \"Original Data\")\r\n#' # plot GdmDiag transformed data\r\n#' scatterplot3d(newData, color = color, cex.symbols = 0.6,\r\n#'\t\t\t xlim = range(data[, 1], newData[, 1]),\r\n#'\t\t\t ylim = range(data[, 2], newData[, 2]),\r\n#'\t\t\t zlim = range(data[, 3], newData[, 3]),\r\n#'\t\t\t main = \"Transformed Data\")\r\n#' }\r\n#'\r\nGdmDiag <- function(data, simi, dism, C0 = 1, threshold = 0.001) {\r\n\t\tfudge = 0.000001\r\n\t\treduction = 2\r\n\t\tdata <- as.matrix(data)\r\n\t\tsimi <- as.matrix(simi)\r\n\t\tdism <- as.matrix(dism)\r\n\t\tN <- dim(data)[1]\r\n\t\td <- dim(data)[2]\r\n\t\ta <- matrix(rep(1, d), nrow = d)# initial diagonal A in the form of column vector\r\n\t\t# dij <- mat.or.vec(1, d)\r\n\r\n\t\tnew.simi <- unique(t(apply(simi, 1, sort)))\r\n\t\tnew.dism <- unique(t(apply(dism, 1, sort)))\r\n\r\n\t\t######### contraints\r\n\t\tdist1.dism <- data[new.dism[, 1], ] - data[new.dism[, 2], ]\r\n\t\tdist.ij <- sqrt((dist1.dism^2) %*% a)\r\n\t\tsum.dist <- sum(dist.ij)\r\n\t\ttemp <- cbind(dist1.dism^2, dist.ij)\r\n\t\tderi1.ij <-0.5 * temp[, 1:d]/(temp[, d + 1] + (temp[, d + 1] == 0) * fudge)\r\n\t\tsum.deri1 <- t(apply(deri1.ij, 2, sum))\r\n\t\tderi2.ij <- t(apply(dist1.dism, 1, function(x) outer(x, x)))\r\n\t\ttemp1 <- cbind(deri2.ij, dist.ij^3)\r\n\t\tderi2.ij <- -0.25 * temp1[, 1:(d^2)]/(temp1[, d^2 + 1] + (temp1[, d^2 + 1] == 0) * fudge)\r\n\t\tsum.deri2 <- matrix(apply(deri2.ij, 2, sum), ncol = d, byrow = TRUE)\r\n\r\n\t\tfD <- log(sum.dist)\r\n\t\tfD.1d <- sum.deri1/sum.dist\r\n\t\tfD.2d <- sum.deri2/sum.dist - crossprod(sum.deri1, sum.deri1)/(sum.dist^2)\r\n\r\n\t\t####### objection is part of contraints\r\n\t\t# fD <- log(sum.dist)\r\n\t\t######################################\r\n\t\tdist1.dism <- data[new.dism[, 1], ] - data[new.dism[, 2], ]\r\n\t\td.sum <- t(apply(dist1.dism^2, 2, sum))\r\n\t\tdist1.simi <- data[new.simi[, 1], ] - data[new.simi[, 2], ]\r\n\t\ts.sum <- t(apply(dist1.simi^2, 2, sum))\r\n\r\n\t\t# S1 <- mat.or.vec(N, N)\r\n\t\t# D1 <- mat.or.vec(N, N)\r\n\r\n\t\t# dism <- rbind(dism, dism[, c(2, 1)]) #\r\n\t\t# Dism <- rbind(Dism, Dism[, c(2, 1)])\r\n\t\t# S1[dism] <- 1\r\n\t\t# D1[Dism] <- 1\r\n\r\n\t\terror <- 1\r\n\t\twhile (error > threshold) {\r\n\t\t\tobj.initial <- as.numeric(s.sum %*% a) + C0 * fD\r\n\t\t\tfS.1d <- s.sum\r\n\r\n\t\t\tgradient <- fS.1d - C0 * fD.1d\r\n\t\t\thessian <- -C0 * fD.2d + fudge * diag(1, d)\r\n\t\t\tinvhessian <- solve(hessian)\r\n\t\t\tcstep <- invhessian %*% t(gradient)\r\n\r\n\t\t\tlambda <- 1\r\n\t\t\tatemp <- a - lambda * cstep\r\n\t\t\tatemp[atemp < 0] <- 0\r\n\r\n\t\t\tfDo <- log(sum(sqrt((dist1.dism^2) %*% atemp)))\r\n\t\t\tobj <- as.numeric(s.sum %*% atemp) + C0 * fDo\r\n\t\t\tobj.previous <- obj * 1.1\r\n\r\n\t\t\twhile (obj < obj.previous) {\r\n\t\t\t\tlambda.previous <- lambda\r\n\t\t\t\tobj.previous <- obj\r\n\t\t\t\ta.previous = atemp\r\n\t\t\t\tlambda <- lambda/reduction\r\n\t\t\t\tatemp <- a - lambda * cstep\r\n\t\t\t\tatemp[atemp < 0] <- 0\r\n\t\t\t\tfDo1 <- log(sum(sqrt((dist1.dism^2) %*% atemp)))\r\n\t\t\t\tobj <- as.numeric(s.sum %*% atemp) + C0 * fDo1\r\n\t\t\t}\r\n\t\ta <- a.previous\r\n\t\terror <- abs((obj.previous - obj.initial)/obj.previous)\r\n\t\t}\r\n\t\tdiagonalA <- diag(as.numeric(a))\r\n\t\tdmlA <- sqrt(diagonalA)\r\n\t\tnewData <- data %*% dmlA\r\n\r\n\t\treturn(list(\"newData\" = newData, \"diagonalA\" = diagonalA, \"dmlA\" = dmlA, \"error\" = error))\r\n}\r\n", "meta": {"hexsha": "649ae4bf9bc575e15526087636b7074b202313cf", "size": 6026, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gdmd.r", "max_stars_repo_name": "cran/dml", "max_stars_repo_head_hexsha": "503600d5a5c1a6c5a601bb9e898cb10e28159184", "max_stars_repo_licenses": ["MIT"], "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/gdmd.r", "max_issues_repo_name": "cran/dml", "max_issues_repo_head_hexsha": "503600d5a5c1a6c5a601bb9e898cb10e28159184", "max_issues_repo_licenses": ["MIT"], "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/gdmd.r", "max_forks_repo_name": "cran/dml", "max_forks_repo_head_hexsha": "503600d5a5c1a6c5a601bb9e898cb10e28159184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-15T13:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-15T13:59:33.000Z", "avg_line_length": 36.0838323353, "max_line_length": 116, "alphanum_fraction": 0.5811483571, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5969708557981829}} {"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(xts)\nlibrary(Quandl)\n\n# Read in spot fx rates\nfxspot.tickers <- c(\"CURRFX/USDEUR\", \"CURRFX/USDJPY\", \"CURRFX/USDCHF\")\nfxspot.raw <- Quandl(fxspot.tickers[1], type=\"xts\")\nfor (i in 2:length(fxspot.tickers)) {\n fxspot.temp <- Quandl(fxspot.tickers[i], type=\"xts\")\n fxspot.raw <- merge(fxspot.raw, fxspot.temp)\n}\ncolnames(fxspot.raw) <- c(\"USDEUR.spot\", \"USDJPY.spot\", \"USDCHF.spot\")\n\n# Read in future fx rates\nfxfut.tickers <- c(\"CHRIS/CME_EC1\", \"CHRIS/CME_JY1\", \"CHRIS/CME_SF1\")\nfxfut.raw <- Quandl(fxfut.tickers[1], type=\"xts\")\nfor (i in 2:length(fxfut.tickers)) {\n fxfut.temp <- Quandl(fxfut.tickers[i], type=\"xts\")\n fxfut.raw <- merge(fxfut.raw, fxfut.temp)\n}\ncolnames(fxfut.raw) <- c(\"USDEUR.fut\", \"USDJPY.fut\", \"USDCHF.fut\")\n\n# Read in 3M USD deposit futures\nusd.3m.raw <- Quandl(\"CHRIS/CME_ED1\", type=\"xts\")[,\"Settle\"]\neur.3m.raw <- Quandl(\"CHRIS/LIFFE_I1\", type=\"xts\")[,\"Settle\"]\njpy.3m.raw <- Quandl(\"CHRIS/CME_EY1\", type=\"xts\")[,\"Settle\"]\nchf.3m.raw <- Quandl(\"CHRIS/LIFFE_S1\", type=\"xts\")[,\"Settle\"]\nchf.3m.raw[\"20150122\"] <- 101.08 # Fix 1st data error\nchf.3m.raw[\"20150508\"] <- 100.83 # Fix 2nd data error\ndeposits3m.raw <- cbind(usd.3m.raw, eur.3m.raw, jpy.3m.raw, chf.3m.raw)\ndeposits3m <- (100-deposits3m.raw)/100 # convert futures prices to yield\ncolnames(deposits3m) <- c(\"3MUSDLIBOR\", \"3MCHFLIBOR\", \"3MJPYTIBOR\", \"3MEURIBOR\")\n\nalldata.full <- cbind(fxspot.raw, deposits3m, fxfut.raw)\nalldata <- alldata.full[\"2013/\"]\n\n# here some calculations have to happen...\n", "meta": {"hexsha": "d29fa607cd85ef51949d06d0dfc886495d5f144e", "size": 1788, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch18-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/ch18-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/ch18-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": 41.5813953488, "max_line_length": 80, "alphanum_fraction": 0.6957494407, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.5967417708035401}} {"text": "#' Calculate the Jaccard statistic for two sets of intervals.\n#'\n#' Quantifies the extent of overlap between to sets of intervals in terms of\n#' base-pairs. Groups that are shared between input are used to calculate the statistic\n#' for subsets of data.\n#'\n#' @details The Jaccard statistic takes values of `[0,1]` and is measured as:\n#'\n#' \\deqn{ J(x,y) = \\frac{\\mid x \\bigcap y \\mid}\n#' {\\mid x \\bigcup y \\mid} =\n#' \\frac{\\mid x \\bigcap y \\mid}\n#' {\\mid x \\mid + \\mid y \\mid -\n#' \\mid x \\bigcap y \\mid} }\n#'\n#' @param x [ivl_df]\n#' @param y [ivl_df]\n#'\n#' @template stats\n#'\n#' @family interval statistics\n#'\n#' @return\n#' tibble with the following columns:\n#'\n#' - `len_i` length of the intersection in base-pairs\n#' - `len_u` length of the union in base-pairs\n#' - `jaccard` value of jaccard statistic\n#' - `n_int` number of intersecting intervals between `x` and `y`\n#'\n#' If inputs are grouped, the return value will contain one set of values per group.\n#'\n#' @seealso\n#' \\url{http://bedtools.readthedocs.org/en/latest/content/tools/jaccard.html}\n#'\n#' @examples\n#' genome <- read_genome(valr_example('hg19.chrom.sizes.gz'))\n#'\n#' x <- bed_random(genome, seed = 1010486)\n#' y <- bed_random(genome, seed = 9203911)\n#'\n#' bed_jaccard(x, y)\n#'\n#' # calculate jaccard per chromosome\n#' bed_jaccard(dplyr::group_by(x, chrom),\n#' dplyr::group_by(y, chrom))\n#'\n#' @export\nbed_jaccard <- function(x, y) {\n x <- check_interval(x)\n y <- check_interval(y)\n\n groups_shared <- shared_groups(x, y)\n\n x <- bed_merge(x)\n y <- bed_merge(y)\n\n res_intersect <- bed_intersect(x, y)\n\n if (!is.null(groups_shared)) {\n x <- group_by(x, !!! syms(groups_shared))\n y <- group_by(y, !!! syms(groups_shared))\n\n res_intersect <- group_by(res_intersect, !!! syms(groups_shared))\n }\n\n res_intersect <- summarize(\n res_intersect,\n sum_overlap = sum(as.numeric(.overlap)),\n n_int = as.numeric(n())\n )\n\n res_x <- mutate(x, .size = end - start)\n res_x <- summarize(res_x, sum_x = sum(as.numeric(.size)))\n\n res_y <- mutate(y, .size = end - start)\n res_y <- summarize(res_y, sum_y = sum(as.numeric(.size)))\n\n if (!is.null(groups_shared)) {\n res <- left_join(res_intersect, res_x, by = as.character(groups_shared))\n res <- left_join(res, res_y, by = as.character(groups_shared))\n\n res <- mutate(res, sum_xy = sum_x + sum_y)\n group_cols <- select(res, !!! syms(groups_shared))\n\n res <- transmute(\n res,\n len_i = sum_overlap,\n len_u = sum_xy,\n jaccard = sum_overlap / (sum_xy - sum_overlap),\n n = n_int\n )\n\n res <- bind_cols(group_cols, res)\n } else {\n n_i <- res_intersect$sum_overlap\n n_u <- res_x$sum_x + res_y$sum_y\n\n jaccard <- n_i / (n_u - n_i)\n\n res <- tibble(\n len_i = n_i,\n len_u = n_u,\n jaccard = jaccard,\n n = res_intersect$n_int\n )\n }\n\n res\n}\n", "meta": {"hexsha": "0a612fa2441665f68c0961bd2aeb455bec27b12b", "size": 2940, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bed_jaccard.r", "max_stars_repo_name": "jimhester/valr", "max_stars_repo_head_hexsha": "73d229911e2ff31c7c733d00c5ee6c4be955d03b", "max_stars_repo_licenses": ["MIT"], "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/bed_jaccard.r", "max_issues_repo_name": "jimhester/valr", "max_issues_repo_head_hexsha": "73d229911e2ff31c7c733d00c5ee6c4be955d03b", "max_issues_repo_licenses": ["MIT"], "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/bed_jaccard.r", "max_forks_repo_name": "jimhester/valr", "max_forks_repo_head_hexsha": "73d229911e2ff31c7c733d00c5ee6c4be955d03b", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 87, "alphanum_fraction": 0.6153061224, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.596673636995588}} {"text": "#' @title\n#' Generate simulation data\n#'\n#' @description\n#' This function generates simulation data for the nested reduced-rank\n#' regression under the multivariate functional regression scenario.\n#' With user-specified model dimensions and ranks,\n#' this function first generates functional multivariate predictors and\n#' responses and then transform the functional regression problem into a\n#' conventional finite-dimensional regression problem through basis expansion\n#' and truncation. The B-spline basis is used to conduct basis expansion.\n#'\n#' @usage\n#' NRRR.sim(n, ns, nt, r, rx, ry, jx, jy, p, d,\n#' s2n, rho_X, rho_E, Sigma = \"CorrAR\")\n#'\n#' @param n sample size.\n#' @param ns number of time points at which the predictor trajectory is observed.\n#' @param nt number of time points at which the response trajectory is observed.\n#' @param r rank of the local reduced-rank structure.\n#' @param rx number of latent predictors.\n#' @param ry number of latent responses.\n#' @param jx number of basis functions to expand the predictor trajectory.\n#' @param jy number of basis functions to expand the response trajectory.\n#' @param p number of predictors.\n#' @param d number of responses.\n#' @param s2n a positive number to specify the signal to noise ratio.\n#' @param rho_X a scalar between 0 and 1 to specify the correlation strength among covariates.\n#' @param rho_E a scalar between 0 and 1 to specify the correlation strength among random errors.\n#' @param Sigma the correlation structure. Two options are available,\n#' \"CorrAR\": autoregressive,\n#' \"CorrCS\": compound symmetry.\n#'\n#'\n#' @return The function returns a list:\n#' \\item{Ag}{the matrix U.}\n#' \\item{Bg}{the matrix V.}\n#' \\item{Al}{the matrix A.}\n#' \\item{Bl}{the matrix B.}\n#' \\item{C}{the coefficient matrix C.}\n#' \\item{Alstar}{A* in equation (7) of the NRRR paper.}\n#' \\item{Blstar}{B* in equation (7) of the NRRR paper.}\n#' \\item{Cstar}{\\eqn{(U \\otimes I_jy)A* B*^T(V \\otimes I_jx)^T} in equation (7) of the NRRR paper.}\n#' \\item{tseq}{a sequence of time points at which the response trajectory is observed.}\n#' \\item{psi}{the set of basis functions to expand the response trajectory.}\n#' \\item{Jpsi}{the correlation matrix of psi. Jpsihalf is (Jpsi)^(1/2).}\n#' \\item{sseq}{a sequence of time points at which the predictor trajectory is observed.}\n#' \\item{phi}{the set of basis functions to expand the predictor trajectory.}\n#' \\item{Jphi}{the correlation matrix of phi.}\n#' \\item{E}{the random error matrix.}\n#' \\item{Y}{an array of dimension \\code{(n, d, nt)}, i.e., the generated response observations.}\n#' \\item{X}{an array of dimension \\code{(n, p, ns)}, i.e., the generated predictor observations.}\n#' \\item{Ytrue}{an array of dimension \\code{(n, d, nt)}. The response observations without random errors.}\n#' \\item{Yest}{the response matrix used in NRRR estimation, and is of dimension n-by-jy*d.}\n#' \\item{Xest}{the design matrix used in NRRR estimation, and is of dimension n-by-jx*p.}\n#' @examples\n#' library(NRRR)\n#' simDat <- NRRR.sim(n = 100, ns = 200, nt = 200, r = 5, rx = 3, ry = 3,\n#' jx = 15, jy = 15, p = 10, d = 6, s2n = 1, rho_X = 0.5,\n#' rho_E = 0, Sigma = \"CorrAR\")\n#' simDat$Ag\n#' @importFrom stats runif rnorm sd\n#' @importFrom splines bs\n#' @importFrom MASS mvrnorm\n#' @export\nNRRR.sim <- function(n,ns,nt,r,rx,ry,jx,jy,p,d,s2n,rho_X,rho_E,Sigma=\"CorrAR\"){\n\n #require(MASS)\n #require(splines)\n if(p < rx) stop(\"rx cannot be greater than p\")\n if(d < ry) stop(\"ry cannot be greater than d\")\n\n ### generate X(s) and Y(t)\n # generate uniformly distributed time points for x(s)\n sseq <- sort(stats::runif(ns,0,1))\n # generate basis functions\n phi <- splines::bs(c(0,sseq),df = jx)[-1,]\n # compute Jphi\n Jphi <- matrix(nrow=jx,ncol=jx,0)\n sdiff <- (sseq - c(0,sseq[-ns]))\n for(s in 1:ns) Jphi <- Jphi + phi[s,]%*%t(phi[s,])*sdiff[s]\n\n # generate X(s)\n if (Sigma == \"CorrAR\") {\n Sigma <- CorrAR\n } else {\n Sigma <- CorrCS\n }\n Xsigma <- Sigma(p*jx,rho_X)\n Xi <- MASS::mvrnorm(n,rep(0,p*jx),Xsigma)\n X <- array(dim=c(n,p,ns),NA)\n for(s in 1:ns){\n Phis <- kronecker(diag(nrow=p,ncol=p),t(phi[s,]))\n for(i in 1:n){\n X[i,,s] <- Phis%*%Xi[i,]\n }\n }\n\n #####Bg (V) matrix, p times rx\n Bg <- qr.Q(qr(matrix(nrow=p,ncol=rx,stats::rnorm(p*rx))))\n #####Ag (U) matrix, d times ry\n Ag <- qr.Q(qr(matrix(nrow=d,ncol=ry,stats::rnorm(d*ry))))\n #####Blstar (B^*) matrix, jx*rx times r\n Blstar <- matrix(nrow=jx*rx, ncol=r, stats::rnorm(jx*rx*r))\n #####Alstar (A^*) matrix, jy*ry times r\n Alstar <- matrix(nrow=jy*ry, ncol=r, stats::rnorm(jy*ry*r))\n #####The coefficient matrix to generate Y(t)\n Cstar <- kronecker(Ag,diag(jy))%*%Alstar%*%t(Blstar)%*%kronecker(t(Bg),diag(jx))\n\n\n # Integrated X\n Xint <- matrix(nrow=p*jx,ncol=n,0)\n sdiff <- (sseq - c(0,sseq[-ns]))\n for(s in 1:ns){\n Xint <- Xint + kronecker(diag(nrow=p,ncol=p),phi[s,])%*%t(X[,,s])*sdiff[s]\n }\n\n # True signal Ytrue(t)\n # generate uniformly distributed time points for y(t)\n tseq <- sort(stats::runif(nt,0,1))\n # generate basis function\n psi <- splines::bs(c(0,tseq),df = jy)[-1,]\n Ytrue <- array(dim=c(n,d,nt),NA)\n Y0 <- Cstar%*%Xint\n for(t in 1:nt){\n Psit <- kronecker(diag(nrow=d,ncol=d),t(psi[t,]))\n Ytrue[,,t] <- t(Psit%*%Y0)\n }\n\n\n # The error matrix, n times d*jy\n sigma <- stats::sd(as.vector(Y0))/s2n\n E <- matrix(nrow=n,ncol=d*jy, stats::rnorm(n*d*jy,0,sigma))\n\n\n # The response matrix Y(t)\n Y <- array(dim=c(n,d,nt),NA)\n for(t in 1:nt){\n Psit <- kronecker(diag(nrow=d,ncol=d),t(psi[t,]))\n for(i in 1:n){\n Y[i,,t] <- Ytrue[i,,t]+Psit%*%E[i,]\n }\n }\n\n\n # compute Jpsi\n Jpsi <- matrix(nrow=jy,ncol=jy,0)\n tdiff <- (tseq - c(0,tseq[-nt]))\n for(t in 1:nt) Jpsi <- Jpsi + psi[t,]%*%t(psi[t,])*tdiff[t]\n eJpsi <- eigen(Jpsi)\n Jpsihalf <- eJpsi$vectors%*%diag(sqrt(eJpsi$values))%*%t(eJpsi$vectors)\n Jpsihalfinv <- eJpsi$vectors%*%diag(1/sqrt(eJpsi$values))%*%t(eJpsi$vectors)\n\n\n ### Process the data for estimation\n Xa <- array(dim=c(n,p,jx),NA)\n sdiff <- (sseq - c(0,sseq[-ns]))\n for(i in 1:n){\n for(l in 1:p){\n for(j in 1:jx){\n Xa[i,l,j] <- sum(phi[,j]*X[i,l,]*sdiff) # integrate over s\n }\n }\n }\n\n Ya <- array(dim=c(n,d,jy),NA)\n tdiff <- (tseq - c(0,tseq[-nt]))\n psistar <- psi%*%Jpsihalfinv\n for(k in 1:d){\n for(i in 1:n){\n for(j in 1:jy){\n Ya[i,k,j] <- sum(psistar[,j]*Y[i,k,]*tdiff) # integrate over t\n }\n }\n }\n\n # Y and X matrices for estimation\n Yest <- Ya[,,1]\n for(j in 2:jy) Yest <- cbind(Yest,Ya[,,j])\n Xest <- Xa[,,1]\n for(j in 2:jx) Xest <- cbind(Xest,Xa[,,j])\n\n\n # C matrix in estimation\n Alstaradj <- kronecker(diag(ry),Jpsihalf)%*%Alstar\n alindex <- rep(1:jy,ry)\n Al <- Alstaradj[order(alindex),]\n blindex <- rep(1:jx,rx)\n Bl <- Blstar[order(blindex),]\n C <- kronecker(diag(jx),Bg)%*%Bl%*%t(Al)%*%kronecker(diag(jy),t(Ag))\n\n\n list(Ag=Ag,Bg=Bg,Alstar=Alstar,Blstar=Blstar,Cstar=Cstar,\n Al=Al, Bl=Bl, C=C,\n sseq=sseq,psi=psi,Jpsi=Jpsi,Jpsihalf=Jpsihalf,\n tseq=tseq,phi=phi,Jphi=Jphi,\n E=E,\n Y=Y,X=X,Ytrue=Ytrue,\n Yest=Yest,Xest=Xest)\n\n}\n\n", "meta": {"hexsha": "829a1501fb19ca214ccb5eb6430c06dfd3269571", "size": 7227, "ext": "r", "lang": "R", "max_stars_repo_path": "R/getData_NRRR.r", "max_stars_repo_name": "xliu-stat/NRRR", "max_stars_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/getData_NRRR.r", "max_issues_repo_name": "xliu-stat/NRRR", "max_issues_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/getData_NRRR.r", "max_forks_repo_name": "xliu-stat/NRRR", "max_forks_repo_head_hexsha": "e51d9df7500b287f8c4daa8839f4cc1782525cef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6009852217, "max_line_length": 108, "alphanum_fraction": 0.6257091463, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5966736221514842}} {"text": "# cod North Sea\n\nfirstAge<-1\nmaxAge<-20 \nnSeasons<-4\nFbarAge<-c(2,4) # expanded relative to normal\n\ndicardLength<-40 # Knife edge selection for discard \n\n#################\n\n\nf.season<-1\nl.season<-nSeasons\n\n#### Natural moratlity \nM<-c(0.8,0.35,0.25,rep(0.2,maxAge-firstAge)) # annual values\nM<-rep(M/nSeasons,each=nSeasons) # quarterly values, assume equaly split\npropMat<-c(0.01,0.05,0.23,0.62,0.86,rep(1,maxAge-firstAge)) # annual values\npropMat<-rep(propMat,each=nSeasons)\n\n\n#### von Bertalanffy growth parameters\nK<-0.219\nloo<-126\nCV<-0.15 # CV of length distribution within an age\n\nvonBertalanffy<-function(tid,loo,K,t0=0) {\n return(loo*(1-exp(-K*(tid-t0))))\n}\n\n\n#### length weight relation. Fishbase North Sea Netherlands\na<-0.0068E-3\nb<-3.101\nlw<-function(len){a*len^b}\n#########\n\n# first try, No fishing\nage<-seq(firstAge,maxAge,1/nSeasons)\nage<-age[1:(length(age)-1)]\nage\nM<-M[1:length(age)]\npropMat<-propMat[1:length(age)]\n\nlen<-vonBertalanffy(tid=age,loo=loo,K=K)\nW<-lw(len)\nN<-M #copy structure\nN[1]<-1\nfor (i in 2:length(N)) N[i]<-N[i-1]*exp(-M[i])\nbiomass<-N*W\nSSB<-biomass*propMat\n\nnox<-2; noy<-2;\n newplot(dev='screen',nox,noy);\noptAge<-age[which(biomass==max(biomass))]\n\nplot(age,len,ylab=\"cm\",main='Length at age')\nabline(v=optAge)\nplot(age,W,ylab=\"kg\", main=\"Weight at age\")\nabline(v=optAge)\nplot(age,N,ylab=\" \", main=\"Stock number at age\")\nabline(v=optAge)\n\nplot(age,biomass,ylab=\"kg\", main=\"TSB and SSB at age\")\nlines(age,SSB)\nabline(v=optAge)\n\n#############################\n\n# \"North Sea Cod\" data from Niels Madsen\nmesh<-c(70,80,90,100,110,120,130,140,150)\nL50<-c(21.22,24.99,28.75,32.52,36.28,40.05,43.81,47.58,51.35)\nSR<-c(3.98,4.69,5.40,6.10,6.81,7.52,8.22,8.93,9.64)\nselection<-data.frame(mesh=mesh,L50=L50,SR=SR)\n# plot(mesh,L50); abline(lm(L50~mesh))\n# plot(mesh,SR); abline(lm(SR~mesh))\nL50par<-lm(L50~mesh, data=selection)\nSRpar<-lm(SR~mesh, data=selection)\nselection<-data.frame(L50a=L50par$coefficients[1],L50b=L50par$coefficients[2],SRa=SRpar$coefficients[1],SRb=SRpar$coefficients[2])\n\nmeshSelection<-function(mesh,len) {\n L50<-selection$L50a[1]+mesh*selection$L50b[1]\n SR<- selection$SRa[1]+mesh*selection$SRb[1]\n S1<-L50*log(3)/(SR/2)\n S2<-S1/L50\n SL<-1/(1+exp(S1-S2*len))\n return (list(SL,L50))\n}\n\nl<-seq(10,100) # fish length in cm\ncol<-1\nfirstMesh<-70\na<- meshSelection(mesh=firstMesh,len=l)\nplot(l,a[[1]],type='l',col=col,xlab=\"length (cm)\",ylab=\"selection\")\nabline(h=0.5)\nabline(v=a[[2]],col=col)\ntext(a[[2]],0.55,formatC(firstMesh,width=3,digits=3),col=col)\nfor (mesh in (seq(firstMesh+20,200,20))) {\n col<-col+1\n a<-meshSelection(mesh=mesh,len=l)\n lines(l,a[[1]],col=col)\n text(a[[2]],0.55,formatC(mesh,width=3,digits=3),col=col)\n abline(v=a[[2]],col=col)\n}\n\n##########################\n\n\n YPR<-function(EffortMult=1,len=len, mesh=mesh,minSize=40)\n# Yield Per Recruit function using size dependent F, where F(a,length)=SL(length)*effort\n# effortMult is effort multiplier\n# len is length at age vector\n# mesh is mesh size of trawl\n# minSize is minimum landing size, Knife edge select: below means discard, above means landed\n# Return values:\n# yield: landed weigth per recruir\n# discard: discarded weight per recruit\n# meanWLanded: mean weight of landed fish\n# Fbar: average F over specified ages \n {\n Fmort<-meshSelection(mesh,len)[[1]]*EffortMult\n \n N<-Fmort # copy structure\n N[]<-0\n N[1]<-1\n \n Z<-M+Fmort\n \n Z[is.na(Z)]<-0\n C<-Z #copy structure\n for (t in (2:length(Z))) {\n N[t]<-N[t-1]*exp(-Z[t]) # exponential decay\n }\n #plot(age,N)\n Nbar<-N*(1-exp(-Z))/Z # average N within time step\n #lines(age,Nbar)\n C<-Nbar*Fmort # total catch numbers\n Clanded<-C # copy structure\n Clanded[lenminimum size)\n mw<-sum(Clanded*W)/sum(Clanded)\n Cdiscard<-C # copy structure\n Cdiscard[len>=minSize]<-0;\n\n deadM<-Nbar*M # number dead of natural causes\n dead<-deadM+C # total number dead\n\n yield<-sum(Clanded*W) # yield weight\n discard<-sum(Cdiscard*W) # discarded weight\n\n # TSB and SSB in start of the first season\n TSB<-matrix(N,nrow=nSeasons)[1,]*matrix(W,nrow=nSeasons)[1,]\n SSB<-sum(TSB*matrix(propMat,nrow=nSeasons)[1,])\n TSB<-sum(TSB)\n \n C<-apply(matrix(C,nrow=nSeasons),2,sum) #sum into C at age\n dead<-apply(matrix(dead,nrow=nSeasons),2,sum) # sum total dead at age\n Z<-apply(matrix(Z,nrow=nSeasons),2,sum) #age Z\n Fmort<-Z*C/dead # annual F at age \n #print(Fmort)\n Fbar<-mean(Fmort[FbarAge[1]:FbarAge[2]])\n return(list(yield=yield,meanWLanded=mw,discard=discard,Fbar=Fbar,TSB=TSB,SSB=SSB))\n }\n\n YPR(EffortMult=0.1,len=len, mesh=90,minSize=dicardLength)\n\n\n # the next exercise is to check the model and to define the range of effort multiplier (myMult)\n myMult<-seq(0.0,0.5,0.001)\n myMesh<-seq(40,180,20)\n design<-data.frame(myMesh=rep(myMesh,length(myMult)),myMult=rep(myMult,each=length(myMesh)))\n \na<- by(design,list(design$myMesh,design$myMult),function(x) {\n YPR(EffortMult=x$myMult,len=len, mesh=x$myMesh,minSize=dicardLength)\n })\n \nb<-data.frame(as.matrix(design),matrix(unlist(a),ncol=6,byrow = T))\nnames(b)<-list(\"myMesh\", \"myMult\", \"Yield\" , \"meanWLanded\" , \"discard\" , \"Fbar\", \"TSB\",\"SSB\" )\n\n#b<-b[order(b$myMesh,b$myMult),]\n\n\n\nlevelplot(Yield~myMesh*myMult, data=b,xlab=\"Mesh size (mm)\",ylab=\"effort multiplier\",main=\"Yield per recruit\",contour=T)\n\nlevelplot(Yield~myMesh*Fbar, data=b,xlab=\"Mesh size (mm)\",ylab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''),main=\"Yield per recruit\",contour=T)\n\nxyplot( Yield~Fbar|as.factor(paste (formatC(myMesh,,wid=3,flag=\"0\"),'mm')), data=b,ylab='Yield (kg)', xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''),xlim=c(0,1))\n\nxyplot( Yield~Fbar, data=b, xlim=c(0,1),ylab='Yield (kg) per recruit', xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''))\n\nxyplot( discard~Fbar, data=b, xlim=c(0,1),ylab='Discard (kg) per recruit',xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''))\n\n\nxyplot( SSB~Fbar, data=b, xlim=c(0,1),ylab='SSB (kg) per recruit',xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''))\n\nxyplot( TSB~Fbar, data=b, xlim=c(0,1),ylab='TSB (kg) per recruit',xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''))\n\nxyplot( meanWLanded~Fbar, data=b, xlim=c(0,1),ylab=\"mean landings weight (kg)\",xlab=paste(\"Fbar( \",FbarAge[1],\"-\",FbarAge[2],\")\",sep=''))\n\n", "meta": {"hexsha": "319e3e4686505c6cb0aa342772765d45f080c38a", "size": 6556, "ext": "r", "lang": "R", "max_stars_repo_path": "SMS_R_prog/r_prog_less_frequently_used/vonbarte.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/vonbarte.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/vonbarte.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": 32.6169154229, "max_line_length": 172, "alphanum_fraction": 0.6433801098, "num_tokens": 2387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5965148218172394}} {"text": "# rho_xy.r\n# computes correlation between events; \n# r stands for response and R for reinforcer\n# ==========================================================================\n# Inputs: \n# t_ev: matrix of 2x2 with [time,event]\n# R: id of first event (e.g., reinforcer)\n# r: id of second event (e.g., response)\n# sec_mult: resolution of the correlation. For example, if tvec\n# is in seconds and we want to compute correlation in milliseconds,\n# we must put sec_mult = 1000.\n# bin_res: resolution of bin. If we want to compute correlation in bins of \n# 200 millisenconds, put bin_res = 200\n# NOTE:\n# This function depends on get_bins \n# ==========================================================================\n\nrho.rR <- function(t_ev,r,R,sec_mult,bin_res){\n \n # The max time at which subject get a reinforfer\n max_t <- max(t_ev[t_ev[,2] == R,1]) * sec_mult\n \n # vector of events \n v_events <- c(r,R)\n \n # Matrix of 3 columns for bins and frecuencies of events in those bins\n m_rR <- \n seq(0, max_t, bin_res) %>% \n seq_along() %>%\n data.frame(bin_r = .,\n r = NA,\n R = NA)\n \n for(j in 1:2){\n \n e <- v_events[j]\n event_bins <- t_ev[which(t_ev[ ,2] == e), 1] * sec_mult %>% \n get_bins(.,1,max_t,bin_res)\n \n \n for(i in 1:nrow(m_rR)){\n \n sum <- sum(m_rR[i,1] == event_bins)\n m_rR[i, j + 1] <- sum # j + 1 because m_rR have 3 columns\n \n }\n }\n \n cor(m_rR[ ,2],m_rR[ ,3])\n}\n\n", "meta": {"hexsha": "f3c8d53190f34f8a1996972321a6c2f06f7e9a85", "size": 1487, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/r/rho_xy.r", "max_stars_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_stars_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/r/rho_xy.r", "max_issues_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_issues_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/r/rho_xy.r", "max_forks_repo_name": "jealcalat/Generalization_decrement_data-analysis", "max_forks_repo_head_hexsha": "5115fcd2749598ee3f8d07886f129738439f809a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5961538462, "max_line_length": 77, "alphanum_fraction": 0.5332885003, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5964957698177988}} {"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.\n\nprincipal.start <- 30e6 # pool principal\nn.peryr <- 12 # monthly = 12 payments per year\nT <- 30 # 30-year mortgage\nr <- 0.0625 # 6.25%\nt <- 1:(n.peryr*T)\n\n## tranche info\nattach.pts <- list(a=0.22, b=0.14, c=0.05, z=0)\nprincipal <- list(a=24e6,b=3e6,c=3e6,z=0)\ninterestbase <- list(a=(1-attach.pts$a)*principal.start,\n b=(attach.pts$a-attach.pts$b)*principal.start,\n c=(attach.pts$b-attach.pts$c)*principal.start,\n z=(attach.pts$c-attach.pts$z)*principal.start)\n\n## calculate level monthly payment\npmt.level <- principal.start*r/(n.peryr*(1-1/(1+r/n.peryr)^(n.peryr*T)))\n\n## 100% PSA prepayment: rate up to 6% annual at 30 months\npsa.speed <- 100 # 100% PSA\nmax.rate <- psa.speed/100*0.06\nseasoned.month <- 30 # at 30 months, PSA says mortgages are seasoned\nprepay.rate <- c(seq(max.rate/seasoned.month, max.rate, max.rate/seasoned.month),\n rep(max.rate, n.peryr*T-seasoned.month))\nprepay.monthly.survival <- (1-prepay.rate)^(1/n.peryr)\nprepay.monthly.rate <- 1-prepay.monthly.survival\n\n## In production code, this would be more elegant; however,\n## a for loop shows the intuition better than other approaches\n### Use fullword.variables for pool payments...\nnum.pmts <- n.peryr*T\nprincipal.left <- c(principal.start, rep(0,num.pmts-1))\npmt.perperiod <- c(pmt.level, rep(0,num.pmts-1))\npmt.interest <- rep(0, num.pmts)\npmt.principal <- rep(0, num.pmts)\npmt.prepays <- rep(0, num.pmts)\n### ... and use abbr.vars (abbreviated) for tranche payments\npmt.prin.a <- pmt.prin.b <- pmt.prin.c <- rep(0, num.pmts)\npmt.int.a <- pmt.int.b <- pmt.int.c <- pmt.int.z <- rep(0, num.pmts)\nstop.loop <- FALSE\nfor (i in 1:num.pmts) {\n ## determine pool cashflows\n pmt.interest[i] <- principal.left[i]*r/n.peryr\n pmt.principal[i] <- pmt.perperiod[i] - pmt.interest[i]\n if (pmt.principal[i] > principal.left[i]) {\n ## do not repay more than principal remaining\n pmt.principal[i] <- principal.left[i]\n ## stop the loop; pool is paid off!\n stop.loop <- TRUE\n } else {\n ## do not prepay more than principal remaining after normal payment\n pmt.prepays[i] <- (principal.left[i]-pmt.principal[i])*prepay.monthly.rate[i]\n if ((pmt.principal[i] + pmt.prepays[i]) > principal.left[i]) {\n pmt.prepays[i] <- principal.left[i] - pmt.principal[i]\n ## stop the loop; pool is paid off!\n stop.loop <- TRUE\n }\n }\n ## allocate payments to tranches\n prin.to.allocate <- pmt.principal[i]+pmt.prepays[i]\n prinleft.a <- principal$a - sum(pmt.prin.a)\n prinleft.b <- principal$b - sum(pmt.prin.b)\n prinleft.c <- principal$c - sum(pmt.prin.c)\n ## Scale interest payments by fraction not repaid*interestbase\n ## Remaining interest will get allocated to principal repayment\n ## and then deferrred interest on the z tranche\n pmt.int.a[i] <- prinleft.a/principal$a*interestbase$a*r/n.peryr\n pmt.int.b[i] <- prinleft.b/principal$b*interestbase$b*r/n.peryr\n pmt.int.c[i] <- prinleft.c/principal$c*interestbase$c*r/n.peryr\n prin.to.allocate <- prin.to.allocate + pmt.interest[i] -\n pmt.int.a[i] - pmt.int.b[i] - pmt.int.c[i]\n ## A is first in line for principal (Andropov is the name to say)\n if (prinleft.a > 0) {\n pmt.prin.a[i] <- min(prinleft.a, prin.to.allocate)\n prin.to.allocate <- prin.to.allocate - pmt.prin.a[i]\n }\n ## The letter B is next in line (for principal, Brezhnev's dead so he'll do just fine)\n if (prinleft.b > 0 & prin.to.allocate > 0) {\n pmt.prin.b[i] <- min(prinleft.b, prin.to.allocate)\n prin.to.allocate <- prin.to.allocate - pmt.prin.b[i]\n }\n ## The letter C is next for principal (C is for Chernenko)\n if (prinleft.c > 0 & prin.to.allocate > 0) {\n pmt.prin.c[i] <- min(prinleft.c, prin.to.allocate)\n prin.to.allocate <- prin.to.allocate - pmt.prin.c[i]\n }\n ## Finally, if any cashflows are left, they go to the Z tranche\n if (prin.to.allocate > 0)\n pmt.int.z[i] <- prin.to.allocate\n\n ## prepare for next iteration of loop\n if (i < num.pmts) {\n principal.left[i+1] <- principal.left[i] - pmt.principal[i] - pmt.prepays[i]\n pmt.perperiod[i+1] <- pmt.perperiod[i]*prepay.monthly.survival[i]\n }\n \n if (stop.loop)\n break\n}\n\nareaplot(t,data.frame(pmt.int.c,pmt.int.b,pmt.int.a,\n pmt.prin.a,pmt.prin.b,pmt.prin.c,pmt.int.z),\n col=c(\"green\",\"yellow\",\"lightblue\",\"blue\",\"orange\",\"darkgreen\",\"red\"),\n ylab=\"\", border=FALSE)\ntext(100, 150000, \"A\", cex=2, col=\"white\")\ntext(210, 60000, \"B\", cex=2)\ntext(255, 40000, \"C\", cex=2, col=\"white\")\ntext(310, 20000, \"Z\", cex=2)\n", "meta": {"hexsha": "4b872cbc22a79c0ac11ea798d5829776b15780d0", "size": 5016, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch23-cmo.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-cmo.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-cmo.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": 43.6173913043, "max_line_length": 90, "alphanum_fraction": 0.6337719298, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5964859097427799}} {"text": "S30AAJ Example Program Results\n\nBlack-Scholes-Merton formula\nEuropean Call :\n Spot = 55.0000\n Volatility = 0.3000\n Rate = 0.1000\n Dividend = 0.0000\n\n Strike Expiry Option Price\n 58.0000 0.7000 5.9198\n 58.0000 0.8000 6.5506\n 60.0000 0.7000 5.0809\n 60.0000 0.8000 5.6992\n 62.0000 0.7000 4.3389\n 62.0000 0.8000 4.9379\n", "meta": {"hexsha": "32fc47773153904cffc9583958963da83f6ed18e", "size": 394, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/s30aaje.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/s30aaje.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/s30aaje.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": 23.1764705882, "max_line_length": 36, "alphanum_fraction": 0.5837563452, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5963751366091455}} {"text": "library(dplyr)\nlibrary(readr)\nlibrary(forcats)\nlibrary(ggplot2)\nlibrary(causaleffect)\nlibrary(igraph)\nlibrary(tensorA)\nsource(glue::glue(\"{here::here()}/helper_functions.r\"))\nsource(glue::glue(\"{here::here()}/get_expression.r\"))\nlibrary(data.tree)\nlibrary(latex2exp)\n\ng <- graph.formula(\n y -+ x\n, y -+ z\n, x -+ z\n)\nplot(g)\n\neffect <- causal.effect(\n y = \"y\"\n, x = \"z\"\n, G = g\n, primes = TRUE\n, simp = TRUE\n, prune = TRUE\n, expr = FALSE\n)\ncat(get.expression(effect), \"\\n\")\n\ncat(get.operation(effect), \"\\n\")\nTeX(glue::glue(\"${get.expression(effect)}$\"))\n\ng <- graph.formula(\n smoke -+ tar\n, tar -+ cancer\n, hidden -+ smoke\n, hidden -+ cancer\n)\nplot(g)\n\neffect <- causal.effect(\n y = \"cancer\"\n, x = \"smoke\"\n, G = g\n, primes = TRUE\n, simp = TRUE\n, prune = TRUE\n, expr = FALSE\n)\ncat(get.expression(effect, primes = TRUE), \"\\n\")\n\neffect_tree <- convert_probability_to_data_tree(effect)\n\n# UC Berkeley data\n\ng <- graph.formula(\n Gender -+ Admit\n, Dept -+ Gender\n, Dept -+ Admit\n)\nplot(g)\n\neffect <- causal.effect(\n y = \"Admit\"\n, x = c(\"Gender\")\n, G = g\n, primes = TRUE\n, simp = TRUE\n, prune = TRUE\n, expr = FALSE\n)\nget.expression(effect)\neffect_tree <- convert_probability_to_data_tree(effect)\n\ndata(UCBAdmissions) \n\nUCBAdmissions_tensor <- UCBAdmissions %>% {\n out <- to.tensor(as.vector(.), dim(.), ndimnames = dimnames(.))\n dimnames(out) <- dimnames(.)\n return(out)\n}\nUCBAdmissions_tensor\n\nUCBAdmissions_tensor %>% {\nterm_1 <- conditional_probability.tensor(\n .\n, var_set = \"Admit\"\n, cond_set = c(\"Gender\", \"Dept\")\n)\nterm_2 <- conditional_probability.tensor(\n .\n, var_set = \"Dept\"\n)\nterm_1 %e% term_2\n}\n\nmargin.tensor(UCBAdmissions_tensor, i = c(\"Admit\", \"Gender\", \"Dept\"))\nUCBAdmissions_tensor %>% ftable\n\n# Adapt the get.expression function to tensor operations\n# Write tests for each of the possibilities:\n# Just a single probability statement\n# A single conditional probability statement\n# A product of two distributions\n# A einstien summation\n# A division\n# A remaining do() (throws error; unidentifiable)\n# Something with primes in it\n# An initial test to make sure it returns a function which acts on tensors, and\n# throws a warning when the input tensor has the wrong indices\n", "meta": {"hexsha": "a9b5845b7c7575bc549f89fb589b3658088c7472", "size": 2192, "ext": "r", "lang": "R", "max_stars_repo_path": "dev_sandbox.r", "max_stars_repo_name": "johnchower/tensoreffect", "max_stars_repo_head_hexsha": "6df3417447d9019634e85dec30c070b1dd74d4fc", "max_stars_repo_licenses": ["MIT"], "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_sandbox.r", "max_issues_repo_name": "johnchower/tensoreffect", "max_issues_repo_head_hexsha": "6df3417447d9019634e85dec30c070b1dd74d4fc", "max_issues_repo_licenses": ["MIT"], "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_sandbox.r", "max_forks_repo_name": "johnchower/tensoreffect", "max_forks_repo_head_hexsha": "6df3417447d9019634e85dec30c070b1dd74d4fc", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 79, "alphanum_fraction": 0.6870437956, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5954414086065274}} {"text": "## --------------------\n## --------------------\n## --------------------\n## This file contains the functions for implementing the Lee-Carter Model. \n## --------------------\n## --------------------\n## --------------------\n\nLC <- function(X, n.pc) {\n\n ## this function adopt codes from the demorgraphy package, X is the data matrix\n ## row is age group\n ## column is year\n\n ax <- apply(X, 1, mean, na.rm = TRUE) # ax is mean of X by column\n\n cX <- sweep(X, 1, ax) ## make sum(kt) = 0\n\n svd.mx <- svd(cX)\n\n\n\n kt <- matrix(NA, nrow = n.pc, ncol = ncol(X))\n\n bx <- matrix(NA, nrow = nrow(X), ncol = n.pc)\n\n for (i in seq(1, n.pc)) {\n sumu <- sum(svd.mx$u[, i])\n\n ## to make sum(bx)=1\n\n bx[, i] <- svd.mx$u[, i] / sumu\n\n kt[i, ] <- svd.mx$d[i] * svd.mx$v[, i] * sumu\n }\n\n fitted <- sweep(bx %*% kt, 1, -ax)\n svd_d <- svd(X)$d\n return(list(bx = bx, kt = kt, rowmean = ax, fitted = fitted, d = svd_d))\n}\n\n# predict the Lee-Carter model, Using RWWD (random walk with drift) model\n\nLC.predict <- function(X, n.pred, n.pc) {\n tmp <- LC(X, n.pc = n.pc)\n\n kt.pred <- matrix(NA, nrow = n.pc, ncol = n.pred)\n\n for (i in seq(1, n.pc)) {\n rw.fit <- forecast::rwf(tmp$kt[i, ], drift = TRUE)\n\n kt.pred[i, ] <- tmp$kt[i, length(tmp$kt[i, ])] + seq(1, n.pred) * rw.fit$model$par$drift\n }\n\n return(sweep(tmp$bx %*% kt.pred, 1, -tmp$rowmean))\n}\n\nLC.forecast <- function(tnsr, n.pred, n.pc, year) {\n cs1 <- LC.predict(tnsr[1, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n c1 <- LC.predict(tnsr[2, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n rs1 <- LC.predict(tnsr[3, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n inf1 <- LC.predict(tnsr[4, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n ext1 <- LC.predict(tnsr[5, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n oth1 <- LC.predict(tnsr[6, , 1:(dim(tnsr)[3] - year)]@data, n.pred, n.pc)\n m_tensor <- array(NA, dim = c(6, 19, n.pred))\n\n m_tensor[1, , ] <- cs1\n m_tensor[2, , ] <- c1\n m_tensor[3, , ] <- rs1\n m_tensor[4, , ] <- inf1\n m_tensor[5, , ] <- ext1\n m_tensor[6, , ] <- oth1\n ###\n\n return(as.tensor(m_tensor))\n}\n\nLC.fit <- function(tnsr, n.pc, year) {\n cs1 <- LC(tnsr[1, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n c1 <- LC(tnsr[2, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n rs1 <- LC(tnsr[3, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n inf1 <- LC(tnsr[4, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n ext1 <- LC(tnsr[5, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n oth1 <- LC(tnsr[6, , 1:(dim(tnsr)[3] - year)]@data, n.pc)$fitted\n m_tensor <- array(NA, dim = c(6, 19, dim(tnsr)[3] - year))\n\n m_tensor[1, , ] <- cs1\n m_tensor[2, , ] <- c1\n m_tensor[3, , ] <- rs1\n m_tensor[4, , ] <- inf1\n m_tensor[5, , ] <- ext1\n m_tensor[6, , ] <- oth1\n ###\n\n return(as.tensor(m_tensor))\n}\n\n\n################# cross_validation\n\nLC.cv <- function(tnsr, year, k = 5, leave_test = TRUE) {\n if (leave_test) {\n tnsr <- tnsr[, , 1:(dim(tnsr)[3] - year)]\n }\n ### training data\n train_ls <- list()\n for (i in 1:k) {\n train_ls[[i]] <- tnsr[, , 1:(dim(tnsr)[3] - i + 1 - year)]\n }\n ### validating data\n validate_ls <- list()\n for (i in 1:k) {\n validate_ls[[i]] <- tnsr[, , (dim(tnsr)[3] - i + 2 - year):(dim(tnsr)[3] - i + 1)]\n }\n ### record minMSE\n minMSE <- 999999\n mincomponent <- 1\n for (i in 1:19) {\n ### record each component statistics\n temp <- NULL\n for (j in 1:k) {\n temp <- c(temp, fnorm(lcforecast(train_ls[[j]], n.pred = year, n.pc = i, year = 0) - validate_ls[[j]]))\n }\n if (mean(temp) < minMSE) {\n minMSE <- mean(temp)\n mincomponent <- i\n }\n }\n return(list(optimal_component = mincomponent, min_MSE = minMSE))\n}", "meta": {"hexsha": "b02621b0166f6ee70c2640077e7374cc691b7025", "size": 3882, "ext": "r", "lang": "R", "max_stars_repo_path": "Lee-Carter.r", "max_stars_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_stars_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lee-Carter.r", "max_issues_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_issues_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lee-Carter.r", "max_forks_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_forks_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8615384615, "max_line_length": 115, "alphanum_fraction": 0.4997424008, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5954381293271119}} {"text": "# Calculate SD of monthly mean temperatures from CMIP5\n# For 1986-2005 and 2081-2100\n\nsource('analysis/image.scale.r') # for plotting color bar on image\nrequire(ncdf4)\nrequire(RColorBrewer)\nrequire(raster)\n\n# read in rcp85 temperatures\ninfile <- nc_open('data/cmip5/tas_Amon_modmean_rcp85_ave.nc') # multi-model mean for each month 1861-2100. near-surface air.\n\t#print(infile)\n\tlst <- ncvar_get(infile, 'tas') # lst lon x lat x time (144x72x2880)\n\tdim(lst)\n\tdimnames(lst) <- list(lon=1:144, lat=1:72, time=1:2880)\n\tdimnames(lst)[[1]] <- infile$var[['tas']]$dim[[1]]$vals # add lon\n\tdimnames(lst)[[2]] <- infile$var[['tas']]$dim[[2]]$vals # add lat\n\tdimnames(lst)[[3]] <- infile$var[['tas']]$dim[[4]]$vals # add time\n\tnc_close(infile)\n\t\ninfile <- nc_open('data/cmip5/tos_Omon_modmean_rcp85_ave.nc') # multi-model mean for each month 1861-2100. sea.\n\t#print(infile)\n\tsst <- ncvar_get(infile, 'tos') # lon x lat x time (288x144x2880)\n\tdim(sst)\n\tdimnames(sst) <- list(lon=1:288, lat=1:144, time=1:2880)\n\tdimnames(sst)[[1]] <- infile$var[['tos']]$dim[[1]]$vals # add lon\n\tdimnames(sst)[[2]] <- infile$var[['tos']]$dim[[2]]$vals # add lat\n\tdimnames(sst)[[3]] <- infile$var[['tos']]$dim[[4]]$vals # add time\n\tnc_close(infile)\n\t\n# Mask out ocean from tas\nsearast <- raster(t(!is.na(sst[,,1]))[ncol(sst):1,], xmn=0, xmx=360, ymn=-90, ymx=90)\nlandrast <- raster(t(!is.na(lst[,,1]))[ncol(lst):1,], xmn=0, xmx=360, ymn=-90, ymx=90)\nseamask <- round(resample(searast, landrast, method='bilinear')) # includes areas 50% land as land (floor): 0 is land, 1 is ocean\nseamask <- t(as.matrix(seamask)) # rearrange again to match lst\nseamask <- seamask[,ncol(seamask):1]\nseamask[seamask==1] <- NA # turn ocean to NA\n\nlst2 <- lst\nfor(i in 1:dim(lst)[3]){\n\tlst2[,,i] <- lst[,,i] + seamask # turns ocean to NAs\n}\n\t\t\n# Detrend historical and future time-periods within each grid cell\ndt <- function(x){\n\tif(all(!is.na(x))){\n\t\tresid(lm(x ~ I(1:length(x))))\n\t} else {\n\t\treturn(rep(NA, length(x)))\n\t}\n}\nmohist1 <- (1986-1861)*12\nmohist2 <- (2005-1861)*12+11\nlstdthist <- apply(lst2[,,mohist1:mohist2], MARGIN=c(1,2), FUN=dt) # dimensions now time x lon x lat\nsstdthist <- apply(sst[,,mohist1:mohist2], MARGIN=c(1,2), FUN=dt)\n\nmofut1 <- (2081-1861)*12\nmofut2 <- (2100-1861)*12+11\nlstdtfut <- apply(lst2[,,mofut1:mofut2], MARGIN=c(1,2), FUN=dt)\nsstdtfut <- apply(sst[,,mofut1:mofut2], MARGIN=c(1,2), FUN=dt)\n\n# SD (seasonality)\nlst_sdhist <- apply(lstdthist, MARGIN=c(2,3), FUN=sd)\nsst_sdhist <- apply(sstdthist, MARGIN=c(2,3), FUN=sd)\n\t\nlst_sdfut <- apply(lstdtfut, MARGIN=c(2,3), FUN=sd)\nsst_sdfut <- apply(sstdtfut, MARGIN=c(2,3), FUN=sd)\n\n\n# Plot of SD historical, SD future, and difference of SDs (tas)\nzlims1 <- range(c(lst_sdhist, lst_sdfut), na.rm=TRUE)\nbks1 <- seq(floor(zlims1[1]), ceiling(zlims1[2]),by=1)\ncols1 <- colorRampPalette(brewer.pal(9, \"OrRd\"))(length(bks1)-1)\nzlims2 <- range(lst_sdfut - lst_sdhist, na.rm=TRUE)\nbks2 <- seq(-ceiling(max(abs(zlims2))),ceiling(max(abs(zlims2))),by=1)\ncols2 <- colorRampPalette(brewer.pal(9, \"RdBu\"))(length(bks2)-1)\nmais <- c(0.2, 0.3, 0.3, 0.1)\n\nquartz(height=4, width=10)\n# pdf(height=4, width=10, file='figures/seasonality_tas_cmip5_hist&fut_map_rcp85.pdf')\nlayout(matrix(c(1,2,3,6,4,5), nrow=2, ncol=3, byrow=FALSE), heights=c(3,1))\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), lst_sdhist, col=cols1, breaks=bks1, main='1986-2005')\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims1, col=cols1, breaks=bks1, horiz=TRUE, xlab='SD historical')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), lst_sdfut, col=cols1, breaks=bks1, main='2081-2100')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), lst_sdfut-lst_sdhist, col=cols2, breaks=bks2, main='(2081-2100) minus (1986-2005)')\t\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims2, col=cols2, breaks=bks2, horiz=TRUE, xlab='SD difference')\n\t\ndev.off()\n\n\n# Plot of SD historical, SD future, and difference of SDs (tos)\nzlims1 <- range(c(sst_sdhist, sst_sdfut), na.rm=TRUE)\nbks1 <- seq(floor(zlims1[1]), ceiling(zlims1[2]),by=1)\ncols1 <- colorRampPalette(brewer.pal(9, \"OrRd\"))(length(bks1)-1)\nzlims2 <- range(sst_sdfut - sst_sdhist, na.rm=TRUE)\nbks2 <- seq(-ceiling(max(abs(zlims2))),ceiling(max(abs(zlims2))),by=1)\ncols2 <- colorRampPalette(brewer.pal(9, \"RdBu\"))(length(bks2)-1)\nmais <- c(0.2, 0.3, 0.3, 0.1)\n\nquartz(height=4, width=10)\n# pdf(height=4, width=10, file='figures/seasonality_tos_cmip5_hist&fut_map_rcp85.pdf')\nlayout(matrix(c(1,2,3,6,4,5), nrow=2, ncol=3, byrow=FALSE), heights=c(3,1))\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), sst_sdhist, col=cols1, breaks=bks1, main='1986-2005')\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims1, col=cols1, breaks=bks1, horiz=TRUE, xlab='SD historical')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), sst_sdfut, col=cols1, breaks=bks1, main='2081-2100')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), sst_sdfut-sst_sdhist, col=cols2, breaks=bks2, main='(2081-2100) minus (1986-2005)')\t\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims2, col=cols2, breaks=bks2, horiz=TRUE, xlab='SD difference')\n\t\ndev.off()\n\n\n# Plot of SD historical, SD future, and ratio of SDs (tas)\nzlims1 <- range(c(lst_sdhist, lst_sdfut), na.rm=TRUE)\nbks1 <- seq(floor(zlims1[1]), ceiling(zlims1[2]),by=1)\ncols1 <- colorRampPalette(brewer.pal(9, \"OrRd\"))(length(bks1)-1)\nzlims2 <- range(log(lst_sdfut/lst_sdhist), na.rm=TRUE)\nbks2 <- seq(-ceiling(max(abs(zlims2))),ceiling(max(abs(zlims2))),by=0.1)\ncols2 <- colorRampPalette(brewer.pal(9, \"RdBu\"))(length(bks2)-1)\nmais <- c(0.2, 0.3, 0.3, 0.1)\n\nquartz(height=4, width=10)\n# pdf(height=4, width=10, file='figures/seasonality_tas_cmip5_hist-futratio_map_rcp85.pdf')\nlayout(matrix(c(1,2,3,6,4,5), nrow=2, ncol=3, byrow=FALSE), heights=c(3,1))\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), lst_sdhist, col=cols1, breaks=bks1, main='1986-2005')\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims1, col=cols1, breaks=bks1, horiz=TRUE, xlab='SD historical')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), lst_sdfut, col=cols1, breaks=bks1, main='2081-2100')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(lst)[[1]]), y=as.numeric(dimnames(lst)[[2]]), log(lst_sdfut/lst_sdhist), col=cols2, breaks=bks2, main='log((2081-2100) / (1986-2005))')\t\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims2, col=cols2, breaks=bks2, horiz=TRUE, xlab='SD difference')\n\t\ndev.off()\n\n\n# Plot of SD historical, SD future, and ratio of SDs (tos)\nzlims1 <- range(c(sst_sdhist, sst_sdfut), na.rm=TRUE)\nbks1 <- seq(floor(zlims1[1]), ceiling(zlims1[2]),by=1)\ncols1 <- colorRampPalette(brewer.pal(9, \"OrRd\"))(length(bks1)-1)\n#zlims2 <- range(log(sst_sdfut/sst_sdhist), na.rm=TRUE)\nzlims2 <- c(-3,3) # force narrow\nbks2 <- c(-30, seq(-ceiling(max(abs(zlims2))),ceiling(max(abs(zlims2))),by=0.1), 30)\ncols2 <- colorRampPalette(brewer.pal(9, \"RdBu\"))(length(bks2)-1)\nmais <- c(0.2, 0.3, 0.3, 0.1)\n\nquartz(height=4, width=10)\n# pdf(height=4, width=10, file='figures/seasonality_tos_cmip5_hist-futratio_map_rcp85.pdf')\nlayout(matrix(c(1,2,3,6,4,5), nrow=2, ncol=3, byrow=FALSE), heights=c(3,1))\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), sst_sdhist, col=cols1, breaks=bks1, main='1986-2005')\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims1, col=cols1, breaks=bks1, horiz=TRUE, xlab='SD historical')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), sst_sdfut, col=cols1, breaks=bks1, main='2081-2100')\n\npar(mai=mais)\nimage(x=as.numeric(dimnames(sst)[[1]]), y=as.numeric(dimnames(sst)[[2]]), log(sst_sdfut/sst_sdhist), col=cols2, breaks=bks2, main='(2081-2100) minus (1986-2005)')\t\n\tpar(mar=c(3,1,1,1))\n\timage.scale(zlim=zlims2, col=cols2, breaks=bks2, horiz=TRUE, xlab='SD difference')\n\t\ndev.off()", "meta": {"hexsha": "c92fd1cc926e77edea1711073ef7a15cb0f70a33", "size": 7997, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/change_in_sd_cmip5.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/change_in_sd_cmip5.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/change_in_sd_cmip5.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": 44.6759776536, "max_line_length": 164, "alphanum_fraction": 0.6850068776, "num_tokens": 3260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.59504979057012}} {"text": "#' Shrinkage-mean-based Diagonal Linear Discriminant Analysis (SmDLDA) from\n#' Tong, Chen, and Zhao (2012)\n#'\n#' Given a set of training data, this function builds the Shrinkage-mean-based\n#' Diagonal Linear Discriminant Analysis (SmDLDA) classifier from Tong, Chen,\n#' and Zhao (2012). The SmDLDA classifier incorporates a Lindley-type shrunken\n#' mean estimator into the DLDA classifier from Dudoit et al. (2002). For more\n#' about the DLDA classifier, see [lda_diag()].\n#'\n#' The DLDA classifier belongs to the family of Naive Bayes classifiers, where\n#' the distributions of each class are assumed to be multivariate normal and to\n#' share a common covariance matrix.\n#'\n#' The DLDA classifier is a modification to the well-known LDA classifier, where\n#' the off-diagonal elements of the pooled sample covariance matrix are assumed\n#' to be zero -- the features are assumed to be uncorrelated. Under multivariate\n#' normality, the assumption uncorrelated features is equivalent to the\n#' assumption of independent features. The feature-independence assumption is a\n#' notable attribute of the Naive Bayes classifier family. The benefit of these\n#' classifiers is that they are fast and have much fewer parameters to estimate,\n#' especially when the number of features is quite large.\n#'\n#' The matrix of training observations are given in `x`. The rows of `x`\n#' contain the sample observations, and the columns contain the features for each\n#' training observation.\n#'\n#' The vector of class labels given in `y` are coerced to a `factor`.\n#' The length of `y` should match the number of rows in `x`.\n#'\n#' An error is thrown if a given class has less than 2 observations because the\n#' variance for each feature within a class cannot be estimated with less than 2\n#' observations.\n#'\n#' The vector, `prior`, contains the _a priori_ class membership for\n#' each class. If `prior` is NULL (default), the class membership\n#' probabilities are estimated as the sample proportion of observations belonging\n#' to each class. Otherwise, `prior` should be a vector with the same length\n#' as the number of classes in `y`. The `prior` probabilities should be\n#' nonnegative and sum to one.\n#'\n#' @export\n#'\n#' @inheritParams lda_diag\n#' @return `lda_shrink_mean` object that contains the trained SmDLDA classifier\n#'\n#' @references Tong, T., Chen, L., and Zhao, H. (2012), \"Improved Mean\n#' Estimation and Its Application to Diagonal Discriminant Analysis,\"\n#' Bioinformatics, 28, 4, 531-537.\n#' \\url{http://bioinformatics.oxfordjournals.org/content/28/4/531.long}\n#' @references Dudoit, S., Fridlyand, J., & Speed, T. P. (2002). \"Comparison of\n#' Discrimination Methods for the Classification of Tumors Using Gene Expression\n#' Data,\" Journal of the American Statistical Association, 97, 457, 77-87.\n#' @examples\n#' library(modeldata)\n#' data(penguins)\n#' pred_rows <- seq(1, 344, by = 20)\n#' penguins <- penguins[, c(\"species\", \"body_mass_g\", \"flipper_length_mm\")]\n#' smdlda_out <- lda_shrink_mean(species ~ ., data = penguins[-pred_rows, ])\n#' predicted <- predict(smdlda_out, penguins[pred_rows, -1], type = \"class\")\n#'\n#' smdlda_out2 <- lda_shrink_mean(x = penguins[-pred_rows, -1], y = penguins$species[-pred_rows])\n#' predicted2 <- predict(smdlda_out2, penguins[pred_rows, -1], type = \"class\")\n#' all.equal(predicted, predicted2)\nlda_shrink_mean <- function(x, ...) {\n UseMethod(\"lda_shrink_mean\")\n}\n\n#' @rdname lda_shrink_mean\n#' @export\nlda_shrink_mean.default <- function(x, y, prior = NULL, ...) {\n x <- pred_to_matrix(x)\n y <- outcome_to_factor(y)\n complete <- complete.cases(x) & complete.cases(y)\n x <- x[complete,,drop = FALSE]\n y <- y[complete]\n\n obj <- diag_estimates(x = x, y = y, prior = prior, pool = TRUE,\n est_mean = \"tong\")\n\n # Creates an object of type 'lda_shrink_mean'\n obj$col_names <- colnames(x)\n obj <- new_discrim_object(obj, \"lda_shrink_mean\")\n\n obj\n}\n\n#' @inheritParams lda_diag\n#' @rdname lda_shrink_mean\n#' @importFrom stats model.frame model.matrix model.response\n#' @export\nlda_shrink_mean.formula <- function(formula, data, prior = NULL, ...) {\n # The formula interface includes an intercept. If the user includes the\n # intercept in the model, it should be removed. Otherwise, errors and doom\n # happen.\n # To remove the intercept, we update the formula, like so:\n # (NOTE: The terms must be collected in case the dot (.) notation is used)\n formula <- no_intercept(formula, data)\n\n mf <- model.frame(formula = formula, data = data)\n .terms <- attr(mf, \"terms\")\n x <- model.matrix(.terms, data = mf)\n y <- model.response(mf)\n\n est <- lda_shrink_mean.default(x = x, y = y, prior = prior)\n est$.terms <- .terms\n est <- new_discrim_object(est, class(est))\n est\n}\n\n#' Outputs the summary for a SmDLDA classifier object.\n#'\n#' Summarizes the trained SmDLDA classifier in a nice manner.\n#'\n#' @param x object to print\n#' @param ... unused\n#' @keywords internal\n#' @export\nprint.lda_shrink_mean <- function(x, ...) {\n cat(\"Shrinkage-Mean-Based Diagonal LDA\\n\\n\")\n print_basics(x, ...)\n invisible(x)\n}\n\n#' SmDLDA prediction of the class membership of a matrix of new observations.\n#'\n#' The SmDLDA classifier is a modification to LDA, where the off-diagonal\n#' elements of the pooled sample covariance matrix are set to zero.\n#'\n#' @rdname lda_shrink_mean\n#' @export\n#' @inheritParams predict.lda_diag\n\npredict.lda_shrink_mean <- function(object, newdata, type = c(\"class\", \"prob\", \"score\"), ...) {\n type <- rlang::arg_match0(type, c(\"class\", \"prob\", \"score\"), arg_nm = \"type\")\n newdata <- process_newdata(object, newdata)\n\n scores <- apply(newdata, 1, function(obs) {\n sapply(object$est, function(class_est) {\n with(class_est, sum((obs - xbar)^2 / object$var_pool) + log(prior))\n })\n })\n \n if (type == \"prob\") {\n # Posterior probabilities via Bayes Theorem\n means <- lapply(object$est, \"[[\", \"xbar\")\n covs <- replicate(n=object$num_groups, object$var_pool, simplify=FALSE)\n priors <- lapply(object$est, \"[[\", \"prior\")\n res <- posterior_probs(x = newdata, means = means, covs = covs, priors = priors)\n res <- as.data.frame(res)\n \n } else if (type == \"class\") {\n res <- score_to_class(scores, object)\n } else {\n res <- t(scores)\n res <- as.data.frame(res)\n }\n res\n}\n", "meta": {"hexsha": "2152c0ab27dfc7a73f675395350764458deeb8c0", "size": 6293, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lda-shrink-mean.r", "max_stars_repo_name": "topepo/sparsediscrim", "max_stars_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:44:00.000Z", "max_issues_repo_path": "R/lda-shrink-mean.r", "max_issues_repo_name": "topepo/sparsediscrim", "max_issues_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:02:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:00:06.000Z", "max_forks_repo_path": "R/lda-shrink-mean.r", "max_forks_repo_name": "topepo/sparsediscrim", "max_forks_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_forks_repo_licenses": ["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.5786163522, "max_line_length": 97, "alphanum_fraction": 0.7041156841, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5950497892787515}} {"text": "\ngetMaxAlphaFilters <- function(g, max.vertices){\n el = get.data.frame(g)\n a = unique(data.frame(node=c(el$from,el$to), alpha=c(el$alpha,el$alpha)))\n a = a[order(a$alpha),]\n a = a[!duplicated(a$node),]\n if(nrow(a) <= max.vertices) {\n max.alpha = 1\n delete.vertices = c()\n } else {\n max.alpha = a$alpha[max.vertices]\n if(max.alpha == a$alpha[max.vertices+1]) max.alpha = max.alpha - 0.000000001\n delete.vertices = na.omit(a$node[(max.vertices+1):nrow(a)])\n delete.edges = which(el$from %in% delete.vertices | el$to %in% delete.vertices)\n }\n list(max.alpha=max.alpha, delete.edges=delete.edges)\n}\n\nfilterVerticesByAlpha <- function(g, max.vertices, use.original.alpha){\n filters = getMaxAlphaFilters(g, max.vertices)\n \n if(filters$max.alpha < max(E(g)$alpha)) {\n message(paste('Used cutoff alpha', filters$max.alpha, 'to keep number of vertices under', max.vertices))\n if(use.original.alpha){\n message(paste('(For the edges the threshold assigned in the alpha parameter is still used)'))\n \n g = delete.edges(g, filters$delete.edges)\n } else {\n g = delete.edges(g, which(E(g)$alpha >= filters$max.alpha)) \n }\n }\n g\n}\n\n\n\n#' Extract the backbone of a network.\n#' \n#' Based on the following paper: Serrano, M. Á., Boguñá, M., & Vespignani, A. (2009). Extracting the multiscale backbone of complex weighted networks. Proceedings of the National Academy of Sciences, 106(16), 6483-6488.\n#' \n#' @param g A graph in the `Igraph` format.\n#' @param alpha The threshold for the alpha. Can be interpreted similar to a p value (see paper for clarrification). \n#' @param direction direction = 'none' can be used for both directed and undirected networks, and is (supposed to be) the disparity filter proposed in Serrano et al. (2009) is used. By setting to 'in' or 'out', the alpha is only calculated for out or in edges. This is an experimental use of the backbone extraction (so beware!) but it seems a logical application. \n#' @param delete.isolates If TRUE, vertices with degree 0 (i.e. no edges) are deleted.\n#' @param max.vertices Optional. Set a maximum number of vertices for the network to be produced. The alpha is then automatically lowered to the point that only the given number of vertices remains connected (degree > 0). This can be usefull if the purpose is to make an interpretation friendly network. See e.g., http://jcom.sissa.it/archive/14/01/JCOM_1401_2015_A01 \n#' @param use.original.alpha if max.vertices is not NULL, this determines whether the lower alpha for selecting the top vertices is also used as a threshold for the edges, or whether the original value given in the alpha parameter is used.\n#' @return A graph in the Igraph format\n#' @export\ngetBackboneNetwork <- function(g, alpha=0.05, direction='none', delete.isolates=T, max.vertices=NULL, use.original.alpha=T, k.is.Nvertices=F){\n if (igraph::has.multiple(g)) stop('The semnet implementation of backbone extraction does not support parallel edges (i.e. having multiple edges between the same nodes with the same direction). If summing multiple edges is OK with you, you can use Igraphs simplify() function')\n \n if(direction == 'none') E(g)$alpha = backbone.alpha(g, k.is.Nvertices)\n if(direction == 'in') E(g)$alpha = backbone.indegree.alpha(g, k.is.Nvertices)\n if(direction == 'out') E(g)$alpha = backbone.outdegree.alpha(g, k.is.Nvertices)\n g = delete.edges(g, which(E(g)$alpha >= alpha))\n if(!is.null(max.vertices) & ecount(g) > 0) g = filterVerticesByAlpha(g, max.vertices, use.original.alpha)\n if(delete.isolates) g = delete.vertices(g, which(degree(g) == 0))\n if(ecount(g) == 0) {\n warning(\"No significant edges (backbone) remain!! Accept it (or lower the backbone_alpha)\")\n return(g)\n }\n g\n}\n\n\n\ncalcAlpha <- function(mat, weightsum, k){\n mat@x = mat@x / weightsum[mat@i+1]\n mat@x = (1 - mat@x)^(k[mat@i+1]-1)\n mat@x[is.na(mat@x)] = 1\n mat\n}\n\n#' Calculate the alpha values that can be used to extract the backbone of a network.\n#' \n#' Based on the following paper: Serrano, M. Á., Boguñá, M., & Vespignani, A. (2009). Extracting the multiscale backbone of complex weighted networks. Proceedings of the National Academy of Sciences, 106(16), 6483-6488.\n#' \n#' @param g A graph in the `Igraph` format.\n#' @return A vector of alpha values, which matches the edges. Can thus easily be made an edge attribute: E(g)$alpha = backbone.alpha(g)\n#' @export\nbackbone.alpha <- function(g, k.is.Nvertices=F){\n if (igraph::has.multiple(g)) stop('The semnet implementation of backbone extraction does not support parallel edges (i.e. having multiple edges between the same nodes with the same direction). If summing multiple edges is OK with you, you can use Igraphs simplify() function')\n \n mat = get.adjacency(g, attr='weight')\n edgelist_ids = get.edgelist(g, names=F)\n \n if(!is.directed(g)) {\n mat[lower.tri(mat)] = 0 # prevents counting edges double in symmetric matrix (undirected graph)\n weightsum_ij = weightsum_ji = Matrix::rowSums(mat) + Matrix::colSums(mat)\n k_ij = k_ji = if(k.is.Nvertices) nrow(mat) else Matrix::rowSums(mat>0) + Matrix::colSums(mat>0)\n } else {\n weightsum_ij = Matrix::rowSums(mat)\n weightsum_ji = Matrix::colSums(mat)\n k_ij = if(k.is.Nvertices) nrow(mat) else Matrix::rowSums(mat>0)\n k_ji = if(k.is.Nvertices) ncol(mat) else Matrix::colSums(mat>0)\n }\n alpha_ij = calcAlpha(mat, weightsum_ij, k_ij)[edgelist_ids] # alpha from the perspective of the 'from' node.\n alpha_ji = Matrix::t(calcAlpha(Matrix::t(mat), weightsum_ji, k_ji))[edgelist_ids] # alpha from the perspective of the 'to' node.\n ifelse(alpha_ij < alpha_ji, alpha_ij, alpha_ji) # select lowest alpha, because an edge can be 'significant' from the perspective of both the 'from' and 'to' node. \n \n}\n\n#' Calculate the alpha values that can be used to extract the backbone of a network, for only the out.degree\n#' \n#' Based on the following paper: Serrano, M. Á., Boguñá, M., & Vespignani, A. (2009). Extracting the multiscale backbone of complex weighted networks. Proceedings of the National Academy of Sciences, 106(16), 6483-6488.\n#' \n#' @param g A graph in the `Igraph` format.\n#' @return A vector of alpha values, which matches the edges. Can thus easily be made an edge attribute: E(g)$alpha = backbone.alpha(g)\n#' @export\nbackbone.outdegree.alpha <- function(g, k.is.Nvertices=F){\n if (igraph::has.multiple(g)) stop('The semnet implementation of backbone extraction does not support \n parallel edges (i.e. having multiple edges between the same nodes \n with the same direction). If summing multiple edges into single \n weighted edges is OK with you, you can use Igraphs simplify() function')\n \n mat = get.adjacency(g, attr='weight')\n weightsum = Matrix::rowSums(mat)\n k = if(k.is.Nvertices) nrow(mat) else Matrix::rowSums(mat > 0)\n edgelist_ids = get.edgelist(g, names=F)\n calcAlpha(mat, weightsum, k)[edgelist_ids]\n}\n\n#' Calculate the alpha values that can be used to extract the backbone of a network, for only the in.degree\n#' \n#' Based on the following paper: Serrano, M. Á., Boguñá, M., & Vespignani, A. (2009). Extracting the multiscale backbone of complex weighted networks. Proceedings of the National Academy of Sciences, 106(16), 6483-6488.\n#' \n#' @param g A graph in the `Igraph` format.\n#' @return A vector of alpha values, which matches the edges. Can thus easily be made an edge attribute: E(g)$alpha = backbone.alpha(g)\n#' @export\nbackbone.indegree.alpha <- function(g, k.is.Nvertices=F){\n if (igraph::has.multiple(g)) stop('The semnet implementation of backbone extraction does not support parallel edges (i.e. having multiple edges between the same nodes with the same direction). If summing multiple edges is OK with you, you can use Igraphs simplify() function')\n \n mat = get.adjacency(g, attr='weight')\n weightsum = Matrix::colSums(mat)\n k = if(k.is.Nvertices) nrow(mat) else Matrix::colSums(mat > 0)\n edgelist_ids = get.edgelist(g, names=F)\n Matrix::t(calcAlpha(Matrix::t(mat), weightsum, k))[edgelist_ids]\n}\n", "meta": {"hexsha": "08df637d2e8f683318c4ec9213b6f3685e0fff6c", "size": 8130, "ext": "r", "lang": "R", "max_stars_repo_path": "R/network_backbone_extraction.r", "max_stars_repo_name": "kasperwelbers/semnet", "max_stars_repo_head_hexsha": "e7106ab2c96b12ae52224fb10bbb1521959d38f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-04-15T09:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T08:51:39.000Z", "max_issues_repo_path": "R/network_backbone_extraction.r", "max_issues_repo_name": "kasperwelbers/semnet", "max_issues_repo_head_hexsha": "e7106ab2c96b12ae52224fb10bbb1521959d38f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-04-25T19:33:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-12T15:13:23.000Z", "max_forks_repo_path": "R/network_backbone_extraction.r", "max_forks_repo_name": "kasperwelbers/semnet", "max_forks_repo_head_hexsha": "e7106ab2c96b12ae52224fb10bbb1521959d38f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-04-02T13:52:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T16:23:45.000Z", "avg_line_length": 58.4892086331, "max_line_length": 368, "alphanum_fraction": 0.7061500615, "num_tokens": 2194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.594821060692642}} {"text": "################################################################################\r\n# Part of the R/EpiILM package\r\n#\r\n# AUTHORS:\r\n# Waleed Almutiry ,\r\n# Vineetha Warriyar. K. V. , and\r\n# Rob Deardon \r\n#\r\n# Algorithm based on:\r\n# Deardon R, Brooks, S. P., Grenfell, B. T., Keeling, M. J., Tildesley,\r\n# M. J., Savill, N. J., Shaw, D. J., Woolhouse, M. E. (2010).\r\n# Inference for individual level models of infectious diseases in large\r\n# populations. Statistica Sinica, 20, 239-261.\r\n#\r\n# Free software under the terms of the GNU General Public License, version 2,\r\n# a copy of which is available at http://www.r-project.org/Licenses/.\r\n################################################################################\r\n\r\npred.epi <- function (object, xx, criterion , n.samples, burnin = NULL, tmin = NULL, Sformula = NULL, Tformula = NULL, showProgressBar = interactive()) {\r\n\r\n\tif (!is(object, \"epidata\")) {\r\n\t\tstop(\"The object of the epidemic data must be in a class of \\\"epidata\\\"\", call. = FALSE)\r\n\t}\r\n\r\n\tif (!is(xx, \"epimcmc\")) {\r\n\t\tstop(\"The object of the MCMC samples must be in a class of \\\"epimcmc\\\"\", call. = FALSE)\r\n\t}\r\n\r\n\tn <- length(object$inftime)\r\n\r\n\tif (is.null(burnin)) {\r\n\t\tburnin <- 1\r\n\t}\r\n\r\n\tif (is.null(tmin)){\r\n\t\ttmin = 1\r\n\t}\r\n\r\n\tt_end <- max(object$inftime)\r\n\r\n\tns <- xx$n.sus.par\r\n\tnt <- xx$n.trans.par\r\n\tni <- xx$n.ker.par\r\n\r\n if (object$type == \"SIR\") {\r\n infperiod = object$remtime - object$inftime\r\n } else {\r\n infperiod = NULL\r\n }\r\n\r\n\r\n\tmcmcout_posterior <- matrix(xx$Fullsample[sample(seq(burnin,length(xx$Fullsample[,1])), n.samples, replace = FALSE), ],\r\n nrow = n.samples,\r\n ncol = ncol(xx$Fullsample))\r\n\r\n\tnewinftime <- replace(object$inftime, object$inftime > tmin, 0)\r\n\tout1 <- vector(mode = \"list\", length = n.samples)\r\n\r\n\tif (is.null(object$contact)) {\r\n\r\n\t\tx <- object$XYcoordinates[,1]\r\n\t\ty <- object$XYcoordinates[,2]\r\n\r\n\t\tif (all((nt == 0) & (ns + ni) == ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\"generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t pb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t setTxtProgressBar(pb, i)\r\n\t\t }\r\n\r\n\t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n\t\t\t\tsus.par = c(mcmcout_posterior[i, 1: ns]),\r\n\t\t\t\tbeta = c(mcmcout_posterior[i, (ns + 1): (ns + ni)]),\r\n\t\t\t\tx = x, y = y, inftime = newinftime, infperiod = infperiod)\r\n\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\t\t} else if (all((nt > 0) & (ns + nt + ni) == ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n\t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n\t\t\t\tsus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n\t\t\t\tbeta = c(mcmcout_posterior[i, (ns+nt+1): (ns+nt+ni)]),\r\n\t\t\t\tx = x, y = y, inftime = newinftime, infperiod = infperiod)\r\n\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\r\n\t\t} else if (all((nt == 0) & (ns + ni) < ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n\t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n\t\t\t\tsus.par = c(mcmcout_posterior[i, 1: ns]), trans.par = 1,\r\n\t\t\t\tbeta = c(mcmcout_posterior[i, (ns + 1): (ns + ni)]),\r\n\t\t\t\tspark = mcmcout_posterior[i, (ns + ni + 1)],\r\n\t\t\t\tx = x, y = y, inftime = newinftime, infperiod = infperiod)\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\r\n\t\t} else if (all((nt > 0) & (ns + nt + ni) < ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n\t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n\t\t\t\tsus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n\t\t\t\tbeta = c(mcmcout_posterior[i, (ns+nt+1): (ns+nt+ni)]),\r\n\t\t\t\tspark = c(mcmcout_posterior[i, (ns+nt+ni+1)]),\r\n\t\t\t\tx = x, y = y, inftime = newinftime, infperiod = infperiod)\r\n\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t} else {\r\n\r\n\t\tcontact <- object$contact\r\n\r\n\t\tif (all((nt == 0) & (ns + ni) == ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n if (ni != 0) {\r\n \t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n \t\t\t\tsus.par = c(mcmcout_posterior[i, 1: ns]),\r\n \t\t\t\tbeta = c(mcmcout_posterior[i, (ns + 1): (ns + ni)]),\r\n \t\t\t\tcontact = contact, inftime = newinftime, infperiod = infperiod)\r\n } else if (ni == 0) {\r\n \t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n \t\t\t\tsus.par = c(mcmcout_posterior[i, 1: ns]),\r\n \t\t\t\tcontact = contact, inftime = newinftime, infperiod = infperiod)\r\n }\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\r\n\t\t} else if (all((nt > 0) & (ns + nt + ni) == ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n if (ni != 0) {\r\n \t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n \t\t\t\tsus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n \t\t\t\tbeta = c(mcmcout_posterior[i, (ns+nt+1): (ns+nt+ni)]),\r\n \t\t\t\tcontact = contact, inftime = newinftime, infperiod = infperiod)\r\n } else if (ni == 0) {\r\n out1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n sus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n contact = contact, inftime = newinftime, infperiod = infperiod)\r\n }\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\r\n\t\t} else if (all((nt == 0) & (ns + ni) < ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n if (ni != 0) {\r\n \t\t\t\tout1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n \t\t\t\tsus.par = c(mcmcout_posterior[i, 1: ns]),\r\n \t\t\t\tbeta = c(mcmcout_posterior[i, (ns + 1): (ns + ni)]),\r\n \t\t\t\tspark = mcmcout_posterior[i, (ns + ni + 1)],\r\n \t\t\t\tcontact = contact, inftime = newinftime, infperiod = infperiod)\r\n } else if (ni == 0) {\r\n out1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, tmin = tmin,\r\n sus.par = c(mcmcout_posterior[i, 1: ns]),\r\n spark = mcmcout_posterior[i, (ns + ni + 1)],\r\n contact = contact, inftime = newinftime, infperiod = infperiod)\r\n }\r\n\t\t\t}\r\n\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\r\n\t\t} else if (all((nt > 0) & (ns + nt + ni) < ncol(xx$Fullsample)) == TRUE) {\r\n\r\n\t\t\tcat(\" generate\", n.samples, \"epidemics \\n\")\r\n\t\t\tif (showProgressBar) {\r\n\t\t\tpb <- txtProgressBar(min = 0, max = n.samples, style = 3)\r\n\t\t\t}\r\n\t\t\tupdate.step <- max(5, floor(n.samples/100))\r\n\r\n\t\t\tfor (i in 1:n.samples) {\r\n\r\n\t\t\t\tif (showProgressBar && i %% update.step == 0) {\r\n\t\t\t\t\tsetTxtProgressBar(pb, i)\r\n\t\t\t\t}\r\n\r\n if (ni != 0) {\r\n out1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n sus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n beta = c(mcmcout_posterior[i, (ns+nt+1): (ns+nt+ni)]),\r\n spark = c(mcmcout_posterior[i, (ns+nt+ni+1)]),\r\n contact = contact, inftime = newinftime, infperiod = infperiod)\r\n } else if (ni == 0) {\r\n out1[[i]] <- epidata(type = object$type, n = n, tmax = t_end, Sformula = Sformula, Tformula = Tformula, tmin = tmin,\r\n sus.par = c(mcmcout_posterior[i, 1:ns]), trans.par = c(mcmcout_posterior[i, (ns+1): (ns+nt)]),\r\n spark = c(mcmcout_posterior[i, (ns+nt+ni+1)]),\r\n contact = contact, inftime = newinftime, infperiod = infperiod)\r\n }\r\n\t\t\t}\r\n\t\t\tif (showProgressBar) {\r\n\t\t\t\tclose(pb)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tif (criterion == \"newly infectious\") {\r\n\r\n\t\tcrit <- matrix(0, ncol = t_end, nrow = n.samples)\r\n\r\n\t\tfor (j in 1:n.samples) {\r\n\t\t\tnewinf <- rep(0)\r\n\t\t\tfor (i in 1: t_end) {\r\n\t\t\t\tnewinf[i] <- sum(out1[[j]]$inftime == i)\r\n\t\t\t}\r\n\t\t\tcrit[j,] <- newinf\r\n\t\t}\r\n\r\n\r\n\r\n\t\tcrit_true <- rep(0)\r\n\t\tfor (i in 1: t_end) {\r\n\t\t\tcrit_true[i] <- length(object$inftime[object$inftime == i])\r\n\t\t}\r\n\r\n\t\tresult <- list(type = object$type, criterion = criterion, crit.sim = crit, crit.obs = crit_true, tmin = tmin, tmax = t_end, n.samples = n.samples)\r\n\r\n\t} else if (criterion == \"epidemic length\") {\r\n\r\n\r\n\t\tif (object$type == \"SI\") {\r\n\r\n\t\t\tcrit <- NULL\r\n\r\n\t\t\tfor (j in 1:n.samples) {\r\n\t\t\t\tcrit[j] <- max(out1[[j]]$inftime) - min(out1[[j]]$inftime)\r\n\t\t\t}\r\n\r\n\t\t\tcrit_true <- max(object$inftime) - min(object$inftime)\r\n\r\n\t\t} else if (object$type == \"SIR\") {\r\n\r\n\t\t\tcrit <- NULL\r\n\r\n\t\t\tfor (j in 1:n.samples) {\r\n\t\t\t\tcrit[j] <- max(out1[[j]]$remtime) - min(out1[[j]]$inftime)\r\n\t\t\t}\r\n\r\n\t\t\tcrit_true <- max(object$remtime) - min(object$inftime)\r\n\r\n\t\t}\r\n\t\t\tresult <- list(type = object$type, criterion = criterion, crit.sim = crit, crit.obs = crit_true, tmin = tmin, tmax = t_end, n.samples = n.samples)\r\n\r\n\r\n\t\t\t} else if (criterion == \"peak time\") {\r\n\r\n\t\t if (object$type == \"SI\") {\r\n\r\n\t\t crit <- NULL\r\n\r\n\t\t for (j in 1:n.samples) {\r\n\r\n\t\t oot <- out1[[j]]$inftime[which(out1[[j]]$inftime!=0)]\r\n\r\n\t\t dff <- as.data.frame(table(oot))\r\n\r\n\t\t res <- dff[which(dff[, 2] == max(dff[, 2])), 1]\r\n\r\n\t\t if (length(res) > 1) {\r\n\r\n\t\t crit[j] <- max(as.numeric(as.character(res)))\r\n\r\n\t\t } else {\r\n\r\n\t\t crit[j] <- as.numeric(as.character(res))\r\n\r\n\t\t }\r\n\r\n\t\t }\r\n\r\n\t\t oot <- object$inftime[which(object$inftime!=0)]\r\n\r\n\t\t dff <- as.data.frame(table(oot))\r\n\r\n\t\t crit_true <- max(as.numeric(as.character(dff[which(dff[, 2] == max(dff[, 2])), 1])))\r\n\r\n\t\t result <- list(type = object$type, criterion = criterion, crit.sim = crit, crit.obs = crit_true, tmin = tmin, tmax = t_end, n.samples = n.samples)\r\n\r\n\t\t } else if (object$type == \"SIR\") {\r\n\r\n\t\t crit_inf <- NULL\r\n\r\n\t\t crit_rem <- NULL\r\n\r\n\t\t for (j in 1:n.samples) {\r\n\r\n\t\t oot <- out1[[j]]$inftime[which(out1[[j]]$inftime!=0)]\r\n\r\n\t\t oot1 <- out1[[j]]$remtime[which(out1[[j]]$remtime!=0)]\r\n\r\n\t\t dff <- as.data.frame(table(oot))\r\n\r\n\t\t dff1 <- as.data.frame(table(oot1))\r\n\r\n\t\t res <- dff[which(dff[, 2] == max(dff[, 2])), 1]\r\n\r\n\t\t res1<- dff1[which(dff1[, 2] == max(dff1[, 2])), 1]\r\n\r\n\t\t if (length(res) > 1) {\r\n\r\n\t\t crit_inf[j] <- max(as.numeric(as.character(res)))\r\n\r\n\t\t } else {\r\n\r\n\t\t crit_inf[j] <- as.numeric(as.character(res))\r\n\r\n\t\t }\r\n\r\n\t\t if (length(res1) > 1) {\r\n\r\n\t\t crit_rem[j] <- max(as.numeric(as.character(res1)))\r\n\r\n\t\t } else {\r\n\r\n\t\t crit_rem[j] <- as.numeric(as.character(res1))\r\n\r\n\t\t }\r\n\r\n\t\t }\r\n\r\n\t\t oot <- object$inftime[which(object$inftime!=0)]\r\n\r\n\t\t oot1 <- object$remtime[which(object$remtime!=0)]\r\n\r\n\t\t dff <- as.data.frame(table(oot))\r\n\r\n\t\t dff1 <- as.data.frame(table(oot1))\r\n\r\n\t\t crit_true_inf <- max(as.numeric(as.character(dff[which(dff[, 2] == max(dff[, 2])), 1])))\r\n\r\n\t\t crit_true_rem <- max(as.numeric(as.character(dff1[which(dff1[, 2] == max(dff1[, 2])), 1])))\r\n\r\n\t\t result <- list(type = object$type, criterion = criterion, crit.sim = list(crit_inf, crit_rem),\r\n\t\t crit.obs = list(crit_true_inf, crit_true_rem), tmin = tmin, tmax = t_end, n.samples = n.samples)\r\n\r\n\t\t }\r\n\r\n\r\n\t\t }\r\n\r\n\t\t class(result) <- \"pred.epi\"\r\n\r\n\t\t result\r\n\r\n}\r\n\r\nplot.pred.epi <- function (x, ...) {\r\n\r\n\tif (!is(x, \"pred.epi\")) {\r\n\t\tstop(\"The object must be in a class of \\\"pred.epi\\\"\", call. = FALSE)\r\n\t}\r\n\r\n\tif (x$criterion == \"newly infectious\") {\r\n\r\n\t\tlowerq <- NULL\r\n\t\tupperq <- NULL\r\n\r\n\t\tfor (i in 1: x$tmax) {\r\n\t\t\tlowerq[i] <- quantile(x$crit.sim[,i], 0.025)\r\n\t\t\tupperq[i] <- quantile(x$crit.sim[,i], 0.975)\r\n\t\t}\r\n\r\n\t\ttime <- rep(1: x$tmax)\r\n\t\tmx <- max(upperq)\r\n\t\tmn <- min(lowerq)\r\n\r\n\t\tplot (time, x$crit.obs, xlim = c(min(time), max(time)), ylim = c(mn, mx),\r\n\t\t\tylab = \"Newly infections\", xlab =\" Time\", xaxt = \"n\", col = \"black\", type = \"o\", pch = 20)\r\n\r\n\t\taxis(1, at = 1:max(time))\r\n\r\n\t\tfor (i in 1: x$n.samples) {\r\n lines(time[x$tmin:x$tmax], x$crit.sim[i,x$tmin:x$tmax], col = \"grey\", lwd = 0.2)\r\n\t\t}\r\n\r\n lines(time[x$tmin:x$tmax], apply(x$crit.sim[,x$tmin:x$tmax], 2, mean), lty = 1, ...)\r\n lines(time, x$crit.obs, col = \"black\", type = \"o\", pch = 20, lwd = 2)\r\n\r\n\t\taxis(1, at = 1:max(time))\r\n\t\tlines(time[x$tmin:x$tmax], lowerq[x$tmin:x$tmax], lty = 2, ...)\r\n\t\tlines(time[x$tmin:x$tmax], upperq[x$tmin:x$tmax], lty = 2, ...)\r\n\r\n\t} else if (x$criterion == \"epidemic length\") {\r\n\r\n\t\thist(x$crit.sim, main = \"\", xlab = \"The length of epidemic\", ylab = \"Time\", ...)\r\n\t\tabline(v = quantile(x$crit.sim, c(0.025, 0.975)), col = \"red\", lty = 2)\r\n\t\tabline(v = mean(x$crit.sim), col = \"red\")\r\n\t\tabline(v = x$crit.obs, col = \"blue\")\r\n\r\n\t} else if (x$criterion == \"peak time\") {\r\n\r\n\t\tif(x$type == \"SI\") {\r\n\r\n\t\t\thist(x$crit.sim, main = \"\", xlab = \"The time of the peak of infection times\", ylab = \"Time\", ...)\r\n\t\t\tabline(v = quantile(x$crit.sim, c(0.025, 0.975)), col = \"red\", lty = 2)\r\n\t\t\tabline(v = mean(x$crit.sim), col = \"red\")\r\n\t\t\tabline(v = x$crit.obs, col = \"blue\")\r\n\r\n\t\t} else if (x$type == \"SIR\") {\r\n\r\n par(mfrow = c(1, 2))\r\n\r\n\t\t\thist(x$crit.sim[[1]], main = \"\", xlab = \"The time of the peak of infection times\", ylab = \"Time\", ...)\r\n\t\t\tabline(v = quantile(x$crit.sim[[1]], c(0.025, 0.975)), col = \"red\", lty = 2)\r\n\t\t\tabline(v = mean(x$crit.sim[[1]]), col = \"red\")\r\n\t\t\tabline(v = x$crit.obs[[1]], col = \"blue\")\r\n\r\n\t\t\thist(x$crit.sim[[2]], main = \"\", xlab = \"The time of the peak of removal times\", ylab = \"Time\", ...)\r\n\t\t\tabline(v = quantile(x$crit.sim[[2]], c(0.025, 0.975)), col = \"red\", lty = 2)\r\n\t\t\tabline(v = mean(x$crit.sim[[2]]), col = \"red\")\r\n\t\t\tabline(v = x$crit.obs[[2]], col = \"blue\")\r\n\r\n\t\t}\r\n\t}\r\n}\r\n", "meta": {"hexsha": "0370c6154d6f9c74eb2a71fed349db4410686d58", "size": 16092, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pred.epi.r", "max_stars_repo_name": "waleedalmutiry/EpiILM", "max_stars_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_stars_repo_licenses": ["Intel"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-30T03:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:15:25.000Z", "max_issues_repo_path": "R/pred.epi.r", "max_issues_repo_name": "waleedalmutiry/EpiILM", "max_issues_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/pred.epi.r", "max_forks_repo_name": "waleedalmutiry/EpiILM", "max_forks_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-01T20:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T17:44:20.000Z", "avg_line_length": 31.7396449704, "max_line_length": 155, "alphanum_fraction": 0.5352348993, "num_tokens": 5243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5946196762651256}} {"text": "#'@title calcPropPwr\n#'\n#'@description Calculates ship power (kW) using the propeller law.\n#'\n#' @param totalInstalledPwr Total installed main engine power (vector of\n#' numericals, kW) (maximum\n#' continuous rated power)\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param refSpeed Reference speed of the ship (service speed or maximum speed)\n#' (vector of numericals, m/s)\n#' @param serviceMargin A service margin to account for weather and sea effects:\n#' \\itemize{\\item At-sea operations = 15 (Default) \\item Coastal operations = 10}\n#' Can supply either a vector of numericals, a single number, or rely on the default\n#' @param n Exponential relationship applied to the ship speed ratio (dimensionless).\n#' Default = 3. This argument is not vectorized, so supply a single number or rely\n#' on the default\n#' @param refSpeedType Indicates if the reference speed is service speed or\n#' maximum speed: \\itemize{\n#' \\item \"serviceSpeed (Default)\"\n#' \\item \"maxSpeed\"}\n#' Can supply either a vector of strings, a single value, or rely on the default.\n#'\n#'@return power (vector of numericals, kW)\n#'\n#'@details\n#' Ship speed and actual draft are typically obtained from sources such as AIS\n#' messages or ship records.\n#'\n#' serviceMargin = 10 or 15, based on IMO (Prpic Orsic and Faltinsen, 2012).\n#' 15 indicates 15\\% increased resistance in at-sea water conditions, and 10\n#' indicates 10\\% increased resistance in coastal water conditions.\n#'\n#' Note that service margin is treated as an added resistance here\n#' (instead of as a reduced efficiency) to maintain consistency with the other\n#' power models used in this library. (See MAN, 2011).\n#'\n#'@references\n#'\\href{https://nepis.epa.gov/Exe/ZyPURL.cgi?Dockey=P1005ZGH.TXT}{EPA. 2009.\n#'\"Regulatory impact analysis: Control of emissions air pollution from category\n#'3 marine diesel engines.\" Ann Arbor, MI: Office of Transportation and Air\n#'Quality. US Environmental Protection Agency.}\n#'\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calcAdmPwr}}\n#'\\item \\code{vignette(\"OverviewOfPowerModels\", package=\"ShipPowerModel\")}\n#'\\item \\code{vignette(\"Propeller.Law.Example\", package=\"ShipPowerModel\")}\n#'}\n#'\n#'@examples\n#'calcPropPwr(totalInstalledPwr = 9363,\n#' shipSpeed = seq(10,14,1),\n#' refSpeed = 15,\n#' serviceMargin = 15,\n#' n = 3)\n#'\n#'@export\n\n\ncalcPropPwr <- function(totalInstalledPwr, shipSpeed, refSpeed, serviceMargin=15, n=3,refSpeedType = \"serviceSpeed\"){\n\n #The propeller law method requires the the reference speed to be maximum speed, to be consistent with the other terms\n #Convert service speed to maximum speed by assuming service speed is 94% of maximum speed\n refSpeed<-ifelse(tolower(refSpeedType) == \"servicespeed\",\n refSpeed/0.94,\n refSpeed\n )#end ifelse\n\n power <- ifelse(shipSpeed==0,\n 0,\n (totalInstalledPwr*\n pmin(1,#set maximum power to 100%\n pmax(.02,#limit minimum power to 2%\n (shipSpeed/refSpeed)^(n)*\n ((100+serviceMargin)/100)\n )\n )\n )\n )#end ifelse\n return(power)\n}\n", "meta": {"hexsha": "1fbcbb7a81d5665392b029363405b8c665459cbc", "size": 3533, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcPropPwr.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/calcPropPwr.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/calcPropPwr.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": 41.0813953488, "max_line_length": 119, "alphanum_fraction": 0.6691197283, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5943676365456947}} {"text": "#### 반복측정 분산분석(Repeated Measures ANOVA) #####\n\n# 01.데이터 불러오기 \nrma.df <- read.csv(\"Ch0902.RMA.csv\", \n header=TRUE, \n na.strings = \".\")\nstr(rma.df)\nView(rma.df)\nrma.df$time <- factor(rma.df$time,\n levels=c(1:3),\n labels=c(\"사전\",\"3개월\",\"6개월\") )\n\n\n\n\n\n\n\n# 02.기본통계치 확인\nlibrary(psych)\ndescribeBy(rma.df$score, rma.df$time, mat=T)\n\n\n\n\n\n\n\n# 03.그래프 그리기(박스그래프,히스토그램)\nboxplot(score ~ time, \n data=rma.df, \n ylab=\"score\", \n xlab=\"time\")\n\n\n\n\n\n\n\n\n# 04.통계분석\n# 다변량 분석을 이용한 구형성(sphericity)검정: Mauchly’s test. 분산의 동질성 검정 방법 레빈 기법 활용한 것과 같은 논리 \n # 매트릭스를 만들어서 해야 한다. 어려우니 잘 따라서 하자. (두번하면 대응표본이지만, 세번하면 분산분석임) \n # 현재 데이터 구조를 바꾸어야 하기 때문에\n\nlibrary(car)\nrma.matrix <- cbind(rma.df$score[rma.df$time==\"사전\"], # 따로따로 뽑아서 옆으로 합쳐라\n rma.df$score[rma.df$time==\"3개월\"], \n rma.df$score[rma.df$time==\"6개월\"])\nhead(rma.matrix)\n\nrma.model.lm <- lm(rma.matrix ~ 1) # ~1 : 데이터를 하나로 묶기\ntime.f <- factor(c(\"사전\",\"3개월\",\"6개월\")) # 시간을 적자 (실제 사용할 때에는 여기만 변경해 주면 된다)\noptions(contrasts=c(\"contr.sum\", \"contr.poly\"))\nrma.result.mt <- Anova(rma.model.lm, #Anova 대문자\n idata=data.frame(time.f),\n idesign=~time.f, \n type=\"III\")\n\nsummary(rma.result.mt, multivariate=F)\n\n\n\n\n\n\n# 일변량 ANOVA 검정\nrma.result <- aov(score ~ time+Error(id/time), \n data=rma.df)\nsummary(rma.result)\n\noptions(\"scipen\" = 20)\n\n\n\n\n# 다중비교 (Multicamparison test) - t-value 포함\n# install.packages(\"multcomp\")\nlibrary(multcomp)\nresult.lm <- lm(score ~ time, data=rma.df)\ntukey.result <- glht(result.lm, linfct=mcp(time='Tukey'))\nsummary(tukey.result)\nplot(tukey.result)\n\n\n\n\n\n\n\n# 부록: 사후검정(기본함수사용): Tukey HSD\ntukey.result <- aov(rma.df$score ~ rma.df$time, data=rma.df)\nTukeyHSD(tukey.result)\nplot(TukeyHSD(tukey.result))\n\n", "meta": {"hexsha": "3c18156c7056ab56d806a31d8ee44b72c7762ae9", "size": 1878, "ext": "r", "lang": "R", "max_stars_repo_path": "ch09 - 분산분석 1/02.반복측정 분산분석(Repeated Measures ANOVA).r", "max_stars_repo_name": "Lee-changyul/Rstudy_Lee", "max_stars_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch09 - 분산분석 1/02.반복측정 분산분석(Repeated Measures ANOVA).r", "max_issues_repo_name": "Lee-changyul/Rstudy_Lee", "max_issues_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch09 - 분산분석 1/02.반복측정 분산분석(Repeated Measures ANOVA).r", "max_forks_repo_name": "Lee-changyul/Rstudy_Lee", "max_forks_repo_head_hexsha": "837a88d6cb4c0e223b42ca18dc5a469051b48533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3608247423, "max_line_length": 82, "alphanum_fraction": 0.5692225772, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5943163120292334}} {"text": "#' Diagonal Linear Discriminant Analysis (DLDA)\n#'\n#' Given a set of training data, this function builds the Diagonal Linear\n#' Discriminant Analysis (DLDA) classifier, which is often attributed to Dudoit\n#' et al. (2002). The DLDA classifier belongs to the family of Naive Bayes\n#' classifiers, where the distributions of each class are assumed to be\n#' multivariate normal and to share a common covariance matrix.\n#'\n#' The DLDA classifier is a modification to the well-known LDA classifier, where\n#' the off-diagonal elements of the pooled sample covariance matrix are assumed\n#' to be zero -- the features are assumed to be uncorrelated. Under multivariate\n#' normality, the assumption uncorrelated features is equivalent to the\n#' assumption of independent features. The feature-independence assumption is a\n#' notable attribute of the Naive Bayes classifier family. The benefit of these\n#' classifiers is that they are fast and have much fewer parameters to estimate,\n#' especially when the number of features is quite large.\n#'\n#' The matrix of training observations are given in `x`. The rows of `x`\n#' contain the sample observations, and the columns contain the features for each\n#' training observation.\n#'\n#' The vector of class labels given in `y` are coerced to a `factor`.\n#' The length of `y` should match the number of rows in `x`.\n#'\n#' An error is thrown if a given class has less than 2 observations because the\n#' variance for each feature within a class cannot be estimated with less than 2\n#' observations.\n#'\n#' The vector, `prior`, contains the _a priori_ class membership for\n#' each class. If `prior` is NULL (default), the class membership\n#' probabilities are estimated as the sample proportion of observations belonging\n#' to each class. Otherwise, `prior` should be a vector with the same length\n#' as the number of classes in `y`. The `prior` probabilities should be\n#' nonnegative and sum to one.\n#'\n#' @export\n#'\n#' @param x Matrix or data frame containing the training data. The rows are the \n#' sample observations, and the columns are the features. Only complete data are \n#' retained. \n#' @param y Vector of class labels for each training observation. Only complete \n#' data are retained. \n#' @param prior Vector with prior probabilities for each class. If NULL\n#' (default), then equal probabilities are used. See details.\n#' @return The model fitting function returns the fitted classifier. The \n#' `predict()` method returns either a vector (`type = \"class\"`) or a data \n#' frame (all other `type` values).\n#' @references Dudoit, S., Fridlyand, J., & Speed, T. P. (2002). \"Comparison of\n#' Discrimination Methods for the Classification of Tumors Using Gene Expression\n#' Data,\" Journal of the American Statistical Association, 97, 457, 77-87.\n#' @examples\n#' library(modeldata)\n#' data(penguins)\n#' pred_rows <- seq(1, 344, by = 20)\n#' penguins <- penguins[, c(\"species\", \"body_mass_g\", \"flipper_length_mm\")]\n#' dlda_out <- lda_diag(species ~ ., data = penguins[-pred_rows, ])\n#' predicted <- predict(dlda_out, penguins[pred_rows, -1], type = \"class\")\n#'\n#' dlda_out2 <- lda_diag(x = penguins[-pred_rows, -1], y = penguins$species[-pred_rows])\n#' predicted2 <- predict(dlda_out2, penguins[pred_rows, -1], type = \"class\")\n#' all.equal(predicted, predicted2)\nlda_diag <- function(x, ...) {\n UseMethod(\"lda_diag\")\n}\n\n#' @importFrom stats complete.cases\n#' @rdname lda_diag\n#' @export\nlda_diag.default <- function(x, y, prior = NULL, ...) {\n x <- pred_to_matrix(x)\n y <- outcome_to_factor(y)\n complete <- complete.cases(x) & complete.cases(y)\n x <- x[complete,,drop = FALSE]\n y <- y[complete]\n\n obj <- diag_estimates(x = x, y = y, prior = prior, pool = TRUE)\n\n # Creates an object of type 'lda_diag' \n # Use columns that pass filters\n obj$col_names <- names(obj$est[[1]]$xbar)\n obj <- new_discrim_object(obj, \"lda_diag\")\n\n obj\n}\n\n#' @param formula A formula of the form `groups ~ x1 + x2 + ...` That is,\n#' the response is the grouping factor and the right hand side specifies the\n#' (non-factor) discriminators.\n#' @param data data frame from which variables specified in `formula` are\n#' preferentially to be taken.\n#' @rdname lda_diag\n#' @importFrom stats model.frame model.matrix model.response\n#' @export\nlda_diag.formula <- function(formula, data, prior = NULL, ...) {\n # The formula interface includes an intercept. If the user includes the\n # intercept in the model, it should be removed. Otherwise, errors and doom\n # happen.\n # To remove the intercept, we update the formula, like so:\n # (NOTE: The terms must be collected in case the dot (.) notation is used)\n formula <- no_intercept(formula, data)\n\n mf <- model.frame(formula = formula, data = data)\n .terms <- attr(mf, \"terms\")\n x <- model.matrix(.terms, data = mf)\n y <- model.response(mf)\n\n est <- lda_diag.default(x = x, y = y, prior = prior)\n est$.terms <- .terms\n est <- new_discrim_object(est, class(est))\n est\n}\n\n#' Outputs the summary for a DLDA classifier object.\n#'\n#' Summarizes the trained DLDA classifier in a nice manner.\n#'\n#' @param x object to print\n#' @param ... unused\n#' @export\n#' @keywords internal\nprint.lda_diag <- function(x, ...) {\n cat(\"Diagonal LDA\\n\\n\")\n \n print_basics(x, ...)\n invisible(x)\n}\n\n#' DLDA prediction of the class membership of a matrix of new observations.\n#'\n#' The DLDA classifier is a modification to LDA, where the off-diagonal elements\n#' of the pooled sample covariance matrix are set to zero.\n#'\n#' @rdname lda_diag\n#' @export\n#' @param object Fitted model object\n#' @param newdata Matrix or data frame of observations to predict. Each row \n#' corresponds to a new observation.\n#' @param type Prediction type: either `\"class\"`, `\"prob\"`, or `\"score\"`. \n#' @param ... additional arguments (not currently used).\npredict.lda_diag <- function(object, newdata, type = c(\"class\", \"prob\", \"score\"), ...) {\n type <- rlang::arg_match0(type, c(\"class\", \"prob\", \"score\"), arg_nm = \"type\")\n newdata <- process_newdata(object, newdata)\n\n scores <- apply(newdata, 1, function(obs) {\n sapply(object$est, function(class_est) {\n with(class_est, sum((obs - xbar)^2 / object$var_pool) + log(prior))\n })\n })\n\n if (type == \"prob\") {\n # Posterior probabilities via Bayes Theorem\n means <- lapply(object$est, \"[[\", \"xbar\")\n covs <- replicate(n = object$num_groups, object$var_pool, simplify = FALSE)\n priors <- lapply(object$est, \"[[\", \"prior\")\n res <- posterior_probs(x = newdata, means = means, covs = covs, priors = priors)\n res <- as.data.frame(res)\n } else if (type == \"class\") {\n res <- score_to_class(scores, object)\n } else {\n res <- t(scores)\n res <- as.data.frame(res)\n }\n res\n}\n", "meta": {"hexsha": "64fe16b312b52117acf6b2c1c7495c7336024817", "size": 6695, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lda-diag.r", "max_stars_repo_name": "topepo/sparsediscrim", "max_stars_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:44:00.000Z", "max_issues_repo_path": "R/lda-diag.r", "max_issues_repo_name": "topepo/sparsediscrim", "max_issues_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-26T12:02:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:00:06.000Z", "max_forks_repo_path": "R/lda-diag.r", "max_forks_repo_name": "topepo/sparsediscrim", "max_forks_repo_head_hexsha": "60198a54e0ced0afa3909121eea55321dd04c56f", "max_forks_repo_licenses": ["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.5757575758, "max_line_length": 88, "alphanum_fraction": 0.701120239, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5942536326214121}} {"text": "# Estimate Z from catch curves using 4 year moving window with cohort-specific coefficients\r\n# based on Sinclair 2001 ICES J Mar Sci 58: 1-10\r\n\r\n# matrix has year in rows and age in columns\r\ncalc_Sinclair_Z <- function(mat){\r\n res <- list()\r\n mat <- as.matrix(mat)\r\n if (all(is.na(mat))){\r\n res$error <- TRUE\r\n return(res)\r\n }\r\n year <- as.numeric(rownames(mat))\r\n age <- as.numeric(colnames(mat))\r\n ny <- length(year)\r\n est.Sinclair.Z <- matrix(NA, nrow=(ny-3), ncol=3)\r\n plot.year <- rep(NA, ny-3)\r\n for (i in 1:(ny-3)){\r\n submat <- mat[year %in% year[i:(i+3)],]\r\n data <- reshape2::melt(submat)\r\n colnames(data) <- c(\"Year\",\"Age\",\"Value\")\r\n data$cohort <- data$Year - data$Age\r\n data$Value[data$Value == 0] <- NA\r\n data <- data[!is.na(data$Value) ,]\r\n data$lnVal <- log(data$Value)\r\n can.calc <- FALSE\r\n if (length(data[,1]) >= 2){\r\n if (max(table(data$cohort)) >= 3){\r\n can.calc <- TRUE\r\n }\r\n }\r\n if (can.calc == TRUE){\r\n my.lm <- lm(data$lnVal ~ as.factor(data$cohort) + data$Age)\r\n data$pred <- predict(my.lm)\r\n data$resid <- residuals(my.lm)\r\n res[[i]] <- data\r\n est.Sinclair.Z[i,1] <- -1 * my.lm$coefficients[names(my.lm$coefficients) == \"data$Age\"]\r\n est.Sinclair.Z[i,2:3] <- -1 * rev(confint(my.lm, \"data$Age\", level=0.90))\r\n }\r\n else{ \r\n res[[i]] <- data\r\n est.Sinclair.Z[i,] <- rep(NA, 3)\r\n }\r\n plot.year[i] <- year[i] + 1.5\r\n }\r\n colnames(est.Sinclair.Z) <- c(\"Sinclair_Z\",\"low90%\",\"high90%\")\r\n res$est.Sinclair.Z <- est.Sinclair.Z\r\n res$plot.year <- plot.year\r\n res$error <- FALSE\r\n return(res)\r\n}\r\n\r\n#-------------------------------------------------------------------------------------\r\n# function to plot the results from calc_Sinclair_Z\r\n# res is a list generated by the function calc_Sinclair_Z\r\nplot_Sinclair_Z <- function(res,est.Z.name,regress.name,resid.name,my.title,save.plots,od,plotf){\r\n # first the plot of estimated Z with CI over time\r\n est.Z <- res$est.Sinclair.Z\r\n if (!all(is.na(est.Z))){\r\n par(mfcol=c(1,1), oma=rep(1,4), mar=rep(4,4))\r\n plot.year <- res$plot.year\r\n Hmisc::errbar(plot.year,est.Z[,1],est.Z[,3],est.Z[,2],ylim=c(0,max(est.Z, na.rm=T)),xlab=\"Year\",ylab=\"Sinclair Z\")\r\n if(!is.na(my.title)) title(main=my.title, outer=F)\r\n if(save.plots) savePlot(paste0(od,est.Z.name,\".\",plotf), type=plotf)\r\n }\r\n \r\n # plot the individual regressions\r\n ny <- length(res$plot.year)\r\n np.row <- 3 # number of plot rows\r\n np.col <- 3 # number of plot columns\r\n np.p <- np.row * np.col # number of plots per page\r\n par(mfcol=c(np.row, np.col))\r\n my.col <- 1:100\r\n my.col[7] <- \"blue\"\r\n icount <- 0\r\n for (i in 1:ny){\r\n data <- res[[i]]\r\n if (!is.na(res$est.Sinclair.Z[i,1])){\r\n icount <- icount + 1\r\n n.coh <- length(unique(data$cohort))\r\n i.coh <- (data$cohort-min(data$cohort, na.rm=T)+1)\r\n plot(data$Age,data$lnVal,pch=i.coh,col=my.col[i.coh],xlab=\"Age\",ylab=\"ln Val\")\r\n title(main=paste0(\"Years \",min(data$Year),\" to \",max(data$Year),\"\\nZ = \",round(res$est.Sinclair.Z[i,1],3)), outer=F)\r\n for (j in 1:n.coh){\r\n subcoh <- data[i.coh == j,]\r\n if (length(subcoh$lnVal) >= 2){\r\n lines(subcoh$Age,subcoh$pred,col=my.col[j],lty=j) \r\n }\r\n }\r\n if(save.plots == T & (icount %% np.p) == 0){\r\n savePlot(paste0(od,regress.name,\"_\",i,\".\",plotf), type=plotf) \r\n }\r\n }\r\n if (save.plots == TRUE & i == ny) savePlot(paste0(od,regress.name,\"_\",i,\".\",plotf), type=plotf)\r\n }\r\n par(mfcol=c(1,1))\r\n \r\n # plot the distribution of residuals by age\r\n if (!all(is.na(est.Z))){\r\n resids <- matrix(NA, nrow=0, ncol=2)\r\n colnames(resids) <- c(\"Age\",\"Resid\")\r\n for (i in 1:ny){\r\n if (!is.na(res$est.Sinclair.Z[i,1])){\r\n data <- res[[i]]\r\n resids <- rbind(resids,cbind(data$Age,data$resid))\r\n } \r\n }\r\n boxplot(resids[,2] ~ resids[,1],xlab=\"Age\",ylab=\"Residual\")\r\n abline(h=0, col=\"red\", lty=2)\r\n if(!is.na(my.title)) title(main=my.title, outer=F)\r\n if(save.plots) savePlot(paste0(od,resid.name,\".\",plotf), type=plotf)\r\n }\r\n else{\r\n resids <- NA\r\n }\r\n \r\n return(resids)\r\n}\r\n#-------------------------------------------------------------------------------------\r\n# function to remove ages from matrix of index catch at age, used by get_Sinclair_Z\r\ndrop_partially_selected_ages <- function(mat,sel,sel.start.age,sel.end.age,sel.cutoff){\r\n sel2 <- sel[sel.start.age:sel.end.age]\r\n age.col <- 1:length(sel2)\r\n drop.col <- age.col[sel2 < sel.cutoff]\r\n if (length(drop.col) > 0) mat[,drop.col] <- NA\r\n return(mat) \r\n}\r\n#-------------------------------------------------------------------------------\r\n#' Get Sinclair Z\r\n#' \r\n#' Set of functions to prepare index matrices and compute and plot Sinclair Z. Estimate Z from catch curves using 4 year moving window with cohort-specific coefficients. Based on Sinclair 2001 ICES J Mar Sci 58: 1-10. Note hard wired to use only ages that are at least 90 percent selected.\r\n#' @param asap name of the variable that read in the asap.rdat file\r\n#' @param a1 list file produced by grab.aux.files function\r\n#' @param index.names names of indices\r\n#' @param save.plots save individual plots\r\n#' @param od output directory for plots and csv files \r\n#' @param plotf type of plot to save\r\n#' @export\r\n\r\nget_Sinclair_Z <- function(asap,a1,index.names,save.plots,od,plotf){\r\n asap.name <- a1$asap.name\r\n index.mats <- ConvertSurveyToAtAge(asap)\r\n nages <- asap$parms$nages\r\n Sinclair.Z <- NA\r\n for (j in 1:length(index.mats$ob)){\r\n if (asap$control.parms$index.age.comp.flag[j] == 1){ # used age composition for the index\r\n mat <- index.mats$ob[[j]]\r\n sel.start.age <- asap$control.parms$index.sel.start.age[j]\r\n sel.end.age <- asap$control.parms$index.sel.end.age[j]\r\n mat <- drop_partially_selected_ages(mat,asap$index.sel[j,],sel.start.age,sel.end.age,0.90)\r\n if (sel.end.age == nages) mat[,length(mat[1,])] <- NA # drop oldest age because plus group in ASAP\r\n Sinclair.Z <- calc_Sinclair_Z(mat)\r\n if (Sinclair.Z$error == FALSE){\r\n est.Z.name <- paste0(\"Sinclair_Z_estimates_index_\",j)\r\n regress.name <- paste0(\"Sinclair_Z_regress_index_\",j)\r\n resid.name <- paste0(\"Sinclair_Z_resids_index_\",j)\r\n resids <- plot_Sinclair_Z(Sinclair.Z,est.Z.name,regress.name,resid.name,index.names[j],\r\n save.plots,od,plotf)\r\n Sinclair.Z.table <- cbind(Sinclair.Z$plot.year,Sinclair.Z$est.Sinclair.Z)\r\n write.csv(Sinclair.Z.table, file=paste0(od,\"Sinclair_Z_index_\",j,\"_\",asap.name,\".csv\"), row.names=F)\r\n }\r\n }\r\n }\r\n return(Sinclair.Z)\r\n}\r\n", "meta": {"hexsha": "823655aecd022c0c7c4bcbca07d72ec2473634e6", "size": 6724, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Sinclair_Z_functions.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/Sinclair_Z_functions.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/Sinclair_Z_functions.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": 40.7515151515, "max_line_length": 290, "alphanum_fraction": 0.5820939917, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5940704545091822}} {"text": "# Example : 1 Chapter : 8.3 Page No: 432\n# Positive Markov matrix Application.\nA<-matrix(c(0.8,0.2,0.05,0.95),ncol=2)\nu0<-c(0.02,0.98)\nu1<-A%*%u0\nprint(u1)\nu2<-A%*%u1\nprint(u2)", "meta": {"hexsha": "08516b628b45f0737b6da19f7d21b80a2f7626dc", "size": 182, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH8/EX8.3.1/Ex8.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/CH8/EX8.3.1/Ex8.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/CH8/EX8.3.1/Ex8.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": 22.75, "max_line_length": 46, "alphanum_fraction": 0.6208791209, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5929245769930336}} {"text": "#######################\r\n## Section 6, Part 1 ##\r\n#######################\r\n\r\n#install.packages(\"pglm\")\r\n#install.packages(\"mlogit\")\r\n#install.packages(\"statmod\")\r\n\r\nlibrary(pglm)\r\nlibrary(mlogit)\r\nlibrary(statmod)\r\nlibrary(MASS)\r\n\r\nsetwd(\"C:\\\\dc_book\\\\Replication_Files_Element\")\r\n\r\nScot.panel <- read.csv(\"Scottish_Ref.csv\")\r\n\r\n# scotReferendumIntention 1 = leave, 0 = stay \r\n# euRefVote 1 = stay, 0 = leave (reverse coded from original survey question) \r\n\r\n###############\r\n## Table 6.1 ##\r\n###############\r\n\r\n\r\n# quadrature\r\nre.logit.quad <- pglm(scotReferendumIntention ~ euRefVote+postEUref+postEUVote+satDemScot+riskUnemployment+Scottish, model=(\"random\"), effect=(\"individual\"), R=64, index=c(\"id\", \"wave\"), family=binomial(link=\"logit\"), data=Scot.panel)\r\nre.logit.quad.results <- cbind(re.logit.quad$estimate, sqrt(diag(vcov(re.logit.quad))), confint.default(re.logit.quad, level=0.95))\r\nN <- length(unique(Scot.panel$id))\r\nO <- nrow(Scot.panel)\r\ncolnames(re.logit.quad.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(re.logit.quad.results, digits=3)))\r\nprint(N)\r\nprint(O)\r\n\r\n# simulation\r\n\r\nScot.panel.long <- mlogit.data(Scot.panel, choice=\"scotReferendumIntention\", shape=\"wide\", id=\"id\")\r\nScot.panel.long$constant <- as.numeric(as.character(Scot.panel.long$alt))\r\nre.logit.sim <- mlogit(scotReferendumIntention ~ constant | 0+euRefVote+postEUref+postEUVote+satDemScot+riskUnemployment+Scottish, rpar=c(constant='n'), panel=TRUE, index=\"id\", R=500, data=Scot.panel.long, reflevel=\"0\")\r\nre.logit.sim.results <- cbind(re.logit.sim$coefficients, sqrt(diag(vcov(re.logit.sim))), confint.default(re.logit.sim, level=0.95))\r\nN <- length(unique(Scot.panel$id))\r\nO <- nrow(Scot.panel)\r\ncolnames(re.logit.sim.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(re.logit.sim.results, digits=3)))\r\nprint(N)\r\nprint(O)\r\n\r\n# logit \r\n\r\npooled.logit <- glm(scotReferendumIntention ~ euRefVote+postEUref+postEUVote+satDemScot+riskUnemployment+Scottish, family=binomial(link=\"logit\"), data=Scot.panel)\r\npooled.logit.results <- cbind(pooled.logit$coefficients, sqrt(diag(vcov(pooled.logit))), confint.default(pooled.logit, level=0.95))\r\nN <- length(unique(Scot.panel$id))\r\nO <- nrow(Scot.panel)\r\ncolnames(pooled.logit.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(pooled.logit.results, digits=3)))\r\nprint(N)\r\nprint(O)\r\n\r\n\r\n################\r\n## Figure 6.1 ##\r\n################\r\n\r\nbeta.re <- re.logit.quad$estimate\r\nbeta.re0 <- re.logit.quad$estimate[-grep(\"sigma\", names(re.logit.quad$estimate))]\r\nbeta.pooled <- pooled.logit$coefficients\r\n\r\nndraws <- 1000\r\nbeta <- re.logit.quad$estimate\r\ncovmat.beta <- vcov(re.logit.quad)\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbetadraw.pooled <- mvrnorm(ndraws, beta.pooled, vcov(pooled.logit))\r\nbetadraw.re0 <- as.matrix(betadraw[,-grep(\"sigma\", names(re.logit.quad$estimate))])\r\n\r\nbaseline.x <- with(Scot.panel, data.frame(\r\nconstant = 1,\r\neuRefVote = median(euRefVote),\r\npostEUref = median(postEUref),\r\npostEUVote = median(postEUVote),\r\nsatDemScot = median(satDemScot),\r\nriskUnemployment = median(riskUnemployment),\r\nScottish = median(Scottish)\r\n))\r\n\r\nsatdemcol <- grep(\"satDemScot\", colnames(baseline.x))\r\nsatdem.range <- seq(0, 5, 0.1)\r\n\r\nprobs.re <- matrix (0, ndraws, length(satdem.range))\r\nprobs.re0 <- matrix (0, ndraws, length(satdem.range))\r\nprobs.pooled <- matrix (0, ndraws, length(satdem.range))\r\n\r\nprobs.mean <- matrix(0, length(satdem.range), 3)\r\n\r\nR <- 64\r\n# the command \"gauss.quad.prob\" gives the \"probabilist\" version of the Hermite polynomial (the command \"gauss.quad\" gives the \"physicist\" version)\r\nquadpoints <- gauss.quad.prob(R, dist=\"normal\")\r\nintpoints <- quadpoints$nodes\r\nintweights <- quadpoints$weights\r\n\r\n\r\n\r\nfor (i in 1:length(satdem.range)) {\r\n\r\n\tbaseline.x[satdemcol] <- satdem.range[i]\r\n\t\r\n\tfor (j in 1:length(intpoints)) {\r\n\t\r\n\t\tx.re <- cbind(baseline.x, intpoints[j])\r\n\t\tp.re <- plogis(beta.re %*% t(x.re)) * intweights[j]\r\n\t\tprobs.mean[i,1] <- probs.mean[i,1] + p.re\r\n\t\t\r\n\t\tp.draw.re <- plogis(betadraw %*% t(x.re)) * intweights[j]\r\n\t\tprobs.re[,i] <- probs.re[,i] + p.draw.re\r\n\t}\r\n\t\r\n\tprobs.mean[i,2] <- plogis(beta.pooled %*% t(baseline.x))\r\n\tprobs.mean[i,3] <- plogis(beta.re0 %*% t(baseline.x))\r\n\t\r\n\tprobs.pooled[,i] <- plogis(betadraw.pooled %*% t(baseline.x))\r\n\tprobs.re0[,i] <- plogis(betadraw.re0 %*% t(baseline.x))\r\n \r\n}\r\n\r\n# random effects, pooled logit, random effect (v=0)\r\ncolors <- c(\"#FC660080\", \"#004D7380\", \"#86AC4180\")\r\n\r\npdf(\"fig61.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 5.5), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(probs.mean[,1] ~ satdem.range, xlim=c(1,4), ylim=c(0, 1), type=\"n\", xaxt=\"n\", xlab=\"Satisfaction with Democracy\", ylab=\"Probability\", xaxt=\"n\", las=1)\r\naxis(1, at=c(1, 2, 3, 4))\r\nfor (i in 1:length(satdem.range)){\r\n\tpoints(probs.re[i,] ~ satdem.range, type=\"l\", col=colors[1], lwd=1)\r\n\tpoints(probs.pooled[i,] ~ satdem.range, type=\"l\", col=colors[2], lwd=1)\r\n\tpoints(probs.re0[i,] ~ satdem.range, type=\"l\", col=colors[3], lwd=1)\r\n}\r\nlines(probs.mean[,1]~satdem.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(probs.mean[,2]~satdem.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(probs.mean[,3]~satdem.range, col=rgb(0,0,0,0.5), lwd=2)\r\nmtext(\"Random\", side=4, at=probs.mean[42,1] + 0.035, cex=1.1, las=1, line=0.5)\r\nmtext(\"Effects\", side=4, at=probs.mean[42,1], cex=1.1, las=1, line=0.5)\r\nmtext(\"Logit\", side=4, at=(probs.mean[42,1] - 0.035), cex=1.1, las=1, line=0.5)\r\nmtext(\"Pooled Logit\", side=4, at=probs.mean[42,2], cex=1.1, las=1, line=0.5)\r\nmtext(\"Random\", side=4, at=probs.mean[42,3]+0.035, cex=1.1, las=1, line=0.5)\r\nmtext(\"Effects\", side=4, at=probs.mean[42,3], cex=1.1, las=1, line=0.5)\r\nmtext(expression(paste(\"Logit (\", alpha,\" = 0)\", sep=\"\")), side=4, at=(probs.mean[42,3] - 0.035), cex=1.1, las=1, line=0.5)\r\ndev.off()\r\n\r\n\r\n\r\n\r\n###############\r\n## Table 6.2 ##\r\n###############\r\n\r\nndraws <- 1000\r\nbeta <- re.logit.quad$estimate\r\ncovmat.beta <- vcov(re.logit.quad)\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- with(Scot.panel, data.frame(\r\nconstant = 1,\r\neuRefVote = median(euRefVote),\r\npostEUref = median(postEUref),\r\npostEUVote = median(postEUVote),\r\nsatDemScot = median(satDemScot),\r\nriskUnemployment = median(riskUnemployment),\r\nScottish = median(Scottish)\r\n))\r\n\r\nx.remain.pre <- baseline.x \r\nx.remain.pre[names(x.remain.pre)==\"euRefVote\"] <- 1\r\nx.remain.pre[names(x.remain.pre)==\"postEUref\"] <- 0\r\nx.remain.pre[names(x.remain.pre)==\"postEUVote\"] <- 0\r\n\r\nx.remain.post <- baseline.x \r\nx.remain.post[names(x.remain.post)==\"euRefVote\"] <- 1\r\nx.remain.post[names(x.remain.post)==\"postEUref\"] <- 1\r\nx.remain.post[names(x.remain.post)==\"postEUVote\"] <- 1\r\n\r\nx.leave.pre <- baseline.x\r\nx.leave.pre[names(x.leave.pre)==\"euRefVote\"] <- 0\r\nx.leave.pre[names(x.leave.pre)==\"postEUref\"] <- 0\r\nx.leave.pre[names(x.leave.pre)==\"postEUVote\"] <- 0\r\n\r\nx.leave.post <- baseline.x\r\nx.leave.post[names(x.leave.post)==\"euRefVote\"] <- 0\r\nx.leave.post[names(x.leave.post)==\"postEUref\"] <- 1\r\nx.leave.post[names(x.leave.post)==\"postEUVote\"] <- 0\r\n\r\nprobs <- matrix(0, ndraws, 7)\r\n\r\n## quadrature\r\nR <- 64\r\n\r\nquadpoints <- gauss.quad.prob(64, dist=\"normal\")\r\nintpoints <- quadpoints$nodes\r\nintweights <- quadpoints$weights\r\n\r\n## could use simulation instead\r\n#install.packages(\"randtoolbox\")\r\n#library(randtoolbox)\r\n#R <- 250\r\n#halton.seq <- halton(R)\r\n#intpoints <- qnorm(halton.seq)\r\n#intweights <- rep(1/R, R)\r\n\r\nfor (i in 1:R) {\r\n\r\n\tx.remain.pre.q <- cbind(x.remain.pre, intpoints[i])\r\n\tx.remain.post.q <- cbind(x.remain.post, intpoints[i])\r\n\tx.leave.pre.q <- cbind(x.leave.pre, intpoints[i])\r\n\tx.leave.post.q <- cbind(x.leave.post, intpoints[i])\r\n\r\n\tp.remain.pre <- plogis(betadraw %*% t(x.remain.pre.q)) * intweights[i]\r\n\tp.remain.post <- plogis(betadraw %*% t(x.remain.post.q)) * intweights[i]\r\n\tp.leave.pre <- plogis(betadraw %*% t(x.leave.pre.q)) * intweights[i]\r\n\tp.leave.post <- plogis(betadraw %*% t(x.leave.post.q)) * intweights[i]\r\n\t\r\n\tprobs[,1] <- probs[,1] + p.remain.pre\r\n\tprobs[,2] <- probs[,2] + p.remain.post\r\n\tprobs[,3] <- probs[,3] + p.leave.pre\r\n\tprobs[,4] <- probs[,4] + p.leave.post\t\r\n \r\n}\r\n\r\nprobs[,5] <- probs[,2] - probs[,1]\r\nprobs[,6] <- probs[,4] - probs[,3]\r\nprobs[,7] <- probs[,5] - probs[,6]\r\n\r\nall.results <- probs\t\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(\"Remain: Pre Brexit\", \"Remain: Post Brexit\", \"Remain: Difference\", \"Leave: Pre Brexit\", \"Leave: Post Brexit\", \"Leave: Difference\", \"Diff in Diff\")\r\nprint(round(first.differences, digits=3))\r\n\r\n\r\n###############\r\n## Table 6.3 ##\r\n###############\r\n\r\nndraws <- 1000\r\nbeta <- re.logit.quad$estimate\r\ncovmat.beta <- vcov(re.logit.quad)\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nR <- 64\r\nquadpoints <- gauss.quad.prob(R, dist=\"normal\")\r\nintpoints <- quadpoints$nodes\r\nintweights <- quadpoints$weights\r\n\r\nobserved.x <- with(Scot.panel, data.frame(\r\nconstant = 1, \r\neuRefVote = euRefVote,\r\npostEUref = postEUref,\r\npostEUVote = postEUVote,\r\nsatDemScot = satDemScot,\r\nriskUnemployment = riskUnemployment,\r\nScottish = Scottish\r\n))\r\n\r\nmean.x <- colMeans(observed.x)\r\n\r\nid.weights <- Scot.panel$sample_weight\r\n\r\nmem <- 0\r\name.all <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\nmem.predprob <- matrix(0, nrow(betadraw), 1)\r\name.predprob <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\nfor (i in 1:R) {\r\n\r\n\t# MEM\r\n\tx.mean.all <- cbind(t(mean.x), intpoints[i])\r\n\tpredprob.mean <- plogis(betadraw %*% t(x.mean.all))\r\n\tpredprob.mean.q <- predprob.mean * intweights[i]\r\n\tmem.predprob <- mem.predprob + (predprob.mean.q)\r\n\tmem.temp <- predprob.mean * (1 - predprob.mean) * betadraw[,\"satDemScot\"] \r\n\tmem <- mem + (mem.temp * intweights[i])\r\n\r\n\t# AME\r\n\tx.vars.all <- cbind(observed.x, intpoints[i])\r\n\tpredprobs <- plogis(betadraw %*% t(x.vars.all)) \r\n\tame.predprob <- ame.predprob + (predprobs * intweights[i])\r\n\tame.temp <- predprobs * (1 - predprobs) * betadraw[,\"satDemScot\"] \r\n\tame.all <- ame.all + (ame.temp * intweights[i])\r\n \r\n}\r\n\r\n\r\name <- colSums(apply(ame.all, 1, function(x){x * id.weights}))/sum(id.weights)\r\nelas <- t(ame.all) * observed.x[,\"satDemScot\"] * t(1/ame.predprob)\r\navg.elas <- colSums(apply(elas, 2, function(x){x * id.weights}))/sum(id.weights)\r\nmem.elas <- mem * (mean.x[\"satDemScot\"]/mem.predprob)\r\n\r\nall.results <- cbind(ame, mem, avg.elas, mem.elas)\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(\"AME\", \"MEM\", \"Average Elasticity\", \"Elasticity at the Mean\")\r\nprint(round(marginal.effects, digits=3))\r\n\r\n\r\n###############\r\n## Table 6.4 ##\r\n###############\r\n\r\n## Population Odds Ratios\r\n\r\nndraws <- 1000\r\nbeta <- re.logit.quad$estimate\r\ncovmat.beta <- vcov(re.logit.quad)\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nR <- 64\r\nquadpoints <- gauss.quad.prob(R, dist=\"normal\")\r\nintpoints <- quadpoints$nodes\r\nintweights <- quadpoints$weights\r\n\r\nobserved.x <- with(Scot.panel, data.frame(\r\nIntercept = 1,\r\neuRefVote = euRefVote,\r\npostEUref = postEUref,\r\npostEUVote = postEUVote,\r\nsatDemScot = satDemScot,\r\nriskUnemployment = riskUnemployment,\r\nScottish = Scottish\r\n))\r\n\r\nid.weights <- Scot.panel$sample_weight \r\n\r\nOR.pop <- matrix(NA, ncol(observed.x), 4)\r\n\r\np.0 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\r\n# calculate baseline\r\nfor (j in 1:R) {\r\n\r\n\tx.vars.all <- cbind(observed.x, intpoints[j])\r\n\tp0 <- plogis(betadraw %*% t(x.vars.all)) \r\n\tp.0 <- p.0 + (p0 * intweights[j])\r\n\t\r\n}\r\n\r\n# increment each variable by 1, calculate odds ratios\r\nfor (i in 1:ncol(observed.x)) {\r\n\r\n\tp.1 <- matrix(0, nrow(betadraw), nrow(observed.x))\r\n\tobserved.x1 <- observed.x\r\n\tobserved.x1[,i] <- observed.x1[,i] + 1\r\n\t\r\n\tif (i==4) { \r\n\tobserved.x1[,2] <- observed.x1[,2] + 1\r\n\tobserved.x1[,3] <- observed.x1[,3] + 1\r\n\t}\r\n\r\n\tfor (j in 1:length(intpoints)) {\r\n\r\n\t\tx1.vars.all <- cbind(observed.x1, intpoints[j])\r\n\t\tp1 <- plogis(betadraw %*% t(x1.vars.all)) \r\n\t\tp.1 <- p.1 + (p1 * intweights[j])\r\n\t\t\r\n\t}\r\n\r\n\t\tOR.temp <- (p.1 / (1 - p.1)) / (p.0 / (1 - p.0))\r\n\t\tOR.temp.w <- colSums(apply(OR.temp, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\t\tOR.pop[i,1:3] <- quantile(OR.temp.w, probs=c(0.5, 0.025, 0.975))\r\n\t\tOR.pop[i,4] <- sd(OR.temp)\r\n\r\n}\r\n\r\nN <- length(unique(Scot.panel$id))\r\nO <- nrow(Scot.panel)\r\ncolnames(OR.pop) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(OR.pop) <- names(observed.x)\r\nprint((round(OR.pop, digits=3)))\r\nprint(N)\r\nprint(O)\r\n\r\n\r\n\r\n## Subject-Specific Odds ratios\r\n\r\nbetadraw.or <- betadraw[,-grep(\"sigma|(Intercept)|postEUVote\", colnames(betadraw))]\r\npostEUVote <- betadraw[,grep(\"euRefVote\", colnames(betadraw))] + betadraw[,grep(\"postEUref\", colnames(betadraw))] + betadraw[,grep(\"postEUVote\", colnames(betadraw))]\r\nbetadraw.or <- cbind(betadraw.or, postEUVote)\r\n\r\nexp.betadraw <- exp(betadraw.or)\r\nN <- length(unique(Scot.panel$id))\r\nO <- nrow(Scot.panel)\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) <- colnames(exp.betadraw) \r\nprint(round(odds.ratios, digits=3))\r\nprint(N)\r\nprint(O)\r\n\r\n\r\n## approximation from Zeger et al. 1988, p. 1054 ##\r\n\r\nc <- ((16*sqrt(3))/(15*pi))\r\nscale.pa <- sqrt(1 + c^2 * re.logit.quad$estimate[grep(\"sigma\", names(re.logit.quad$estimate))]^2)\r\nbeta.Zeger <- apply(betadraw.or, 2, function(x){x/scale.pa})\r\nexp.beta.Zeger <- exp(beta.Zeger)\r\nquantiles.Zeger <- apply(exp.beta.Zeger, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds.Zeger <- apply(exp.beta.Zeger, 2, sd)\r\nZeger.adj <- cbind(t(quantiles.Zeger), sds.Zeger)\r\ncolnames(Zeger.adj) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(Zeger.adj) <- colnames(exp.beta.Zeger) \r\nprint(round(Zeger.adj, digits=3))\r\n\r\n\r\n\r\n## approximation from Hedeker et al. 2018 ## \r\n\r\nbetadraw.H <- betadraw[,-grep(\"sigma|postEUVote\", colnames(betadraw))]\r\npostEUVote <- betadraw[,grep(\"euRefVote\", colnames(betadraw))] + betadraw[,grep(\"postEUref\", colnames(betadraw))] + betadraw[,grep(\"postEUVote\", colnames(betadraw))]\r\nsigma <- betadraw[,grep(\"sigma\", colnames(betadraw))]\r\nbetadraw.H <- cbind(betadraw.H, postEUVote, sigma)\r\n\r\nobserved.H <- with(Scot.panel, data.frame(\r\nIntercept = 1,\r\neuRefVote = euRefVote,\r\npostEUref = postEUref,\r\nsatDemScot = satDemScot,\r\nriskUnemployment = riskUnemployment,\r\nScottish = Scottish,\r\npostEUVote = postEUVote\r\n))\r\n\r\npredprobs <- matrix(0, nrow(betadraw.H), nrow(observed.H))\r\n\r\nfor (i in 1:R) {\r\n\r\n\tx.vars.all <- cbind(observed.H, intpoints[i])\r\n\tpredprobs.temp <- plogis(betadraw.H %*% t(x.vars.all)) \r\n\tpredprobs <- predprobs + (predprobs.temp * intweights[i])\r\n \r\n}\r\n\r\nX <- as.matrix(observed.H)\r\nlambda.matrix <- log(predprobs/(1 - predprobs))\r\nbeta.Hedeker <- apply(lambda.matrix, 1, function(x){solve(t(X) %*% X) %*% (t(X) %*% x)}) \r\nexp.beta.Hedeker <- exp(beta.Hedeker)\r\nquantiles.Hedeker <- apply(exp.beta.Hedeker, 1, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds.Hedeker <- apply(exp.beta.Hedeker, 1, sd)\r\nHedeker.adj <- cbind(t(quantiles.Hedeker), sds.Hedeker)\r\ncolnames(Hedeker.adj) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(Hedeker.adj) <- colnames(observed.H)\r\nHedeker.adj <- Hedeker.adj[-1,] # remove constant term\r\nprint(round(Hedeker.adj, digits=3))\r\n\r\n", "meta": {"hexsha": "8bb92570c562625d9387816cdad58878f7788465", "size": 15568, "ext": "r", "lang": "R", "max_stars_repo_path": "R Code/Section6_Part1.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_Part1.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_Part1.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": 33.8434782609, "max_line_length": 235, "alphanum_fraction": 0.6469681398, "num_tokens": 5379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.592671666945952}} {"text": "# This offline tool is a new method to identify the vent location of tephra fall deposits \n# based on thickness or maximum clast size measurements.\n# It is temporarily named \"svl\", which is short for Source Vent Locator.\n# This file includes the associated R functions and their notations.\n\n###\n# Since the presented method gives estimate on the vent location and prevailing wind \n# direction, it can be used to produce the input for our method to model the thickness\n# or maximum clast size distribution of \n# tephra fall deposits (Yang and Bursik, 2016; https://vhub.org/resources/3957).\n###\n# Author: Qingyuan Yang, Marcus Bursik, and E. Bruce Pitman.\n###\n# License: GPL. Use at your own risk. \n###\n# The work was supported by National Science Foundation Hazard SEES grant number 1521855 to\n# G. Valentine, M. Bursik, E.B. Pitman and A.K. Patra, and National Science Foundation\n# DMS grant number 1621853 to A.K. Patra, M. Bursik, and E.B. Pitman.\n###\n# We appreciate your comments, suggestions, and feedback. \n# Please feel free to contact us through vhub or email: qyang5@buffalo.edu \n# Notes:\n#\tThe functions below are the version of the method that is coupled with the semi-\t\n#\tempirical model proposed by Gonzalez-Mellado and De la Cruz-Reyna (2010).\n###### Functions ######\n#################################Intermediate functions#################################\nsp_par_cal <- function(obs, sv, wind_dir){\t\t\t\n\tsv = as.vector(sv)\n\tzr <- obs[,3]\n\txy <- as.matrix(obs[,c(1,2)])\n\tnr <- nrow(obs)\n\tsv_matrix <- matrix(ncol=2, nrow=nr)\n\tsv_matrix[,1] <- rep(sv[1], nr)\n\tsv_matrix[,2] <- rep(sv[2], nr)\n\tunit_vector <- as.matrix(c(sin(wind_dir*pi/180),cos(wind_dir*pi/180)))\n\trel_xy <- xy - sv_matrix\n\tdist <- (rel_xy[,1]^2 + rel_xy[,2]^2)^0.5\n\tdd <- (rel_xy) %*% (unit_vector)\n\tcd <- (dist^2 - dd^2)^0.5\n\toutput <- matrix(nrow = nr, ncol=7)\n\toutput[,1:2] <- xy\n\toutput[,3:5] <- cbind(dist, dd, cd)\n\toutput[,6] <- dist - dd \n\toutput[,7] <- zr\n\treturn(output)\n}\n\nfi <- function(obs, sv, wind_dir){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\ttd <- as.data.frame(sp_par_cal(obs, sv, wind_dir))\n\tcolnames(td) <- c(\"x\",\"y\",\"dist\",\"dd\",\"cd\", \"dif\",\"zr\")\n\ttd$z = log10(td$zr)\n\n \tfit.res <- lm(z~dif+log(dist),data=td)\t\t# ***case 1: power-law model***\n# \tfit.res <- lm(z~dist+dd,data=td)\t\t# ***case 2: exponential model***\n ssr <- sum(fit.res$residuals^2)\n\treturn(ssr)\n}\n\n\nfi2 <- function(obs, sv, wind_dir){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\ttd <- as.data.frame(sp_par_cal(obs, sv, wind_dir))\n\tcolnames(td) <- c(\"x\",\"y\",\"dist\",\"dd\",\"cd\", \"dif\",\"zr\")\n\ttd$z = log10(td$zr)\n \tfit.res <- lm(z~dif+log(dist),data=td)\t\t# ***case 1: power-law model ***\n# fit.res <- lm(z~dist+dd,data=td)\t\t# ***case 2: exponential model***\n \tssr <- sum(fit.res$residuals^2)\n\treturn(c(ssr, fit.res$coefficients, summary(fit.res)$r.squared))\n}\n\ncg <- function(sv, h){\t\t\t\t\t\n\toutput = cbind(c(rep(sv[,1],4)+sin(0:3*90*pi/180)*h),\n\t\t c(rep(sv[,2],4)+cos(0:3*90*pi/180)*h))\n\treturn(output)\n}\n\nbaf_pre <- function(sv, obs, nlps){\n\tpot_ang <- as.data.frame((1:36)*10)\t\t\t\t\t\t\t\t\t\n\tpot_ssr <- apply(pot_ang, MARGIN = 1, FUN=fi, obs = obs, sv = sv)\n\tlowest_rank = which(rank(pot_ssr)==1)\t\t\t# ***Power-law***\n\tnext_lowest_rank = which(rank(pot_ssr)==2)\t\t# ***Power-law***\n\t#lowest_rank = min(which(rank(pot_ssr)<2))\t\t\t\t# ***exponential***\n\t#next_lowest_rank = min(which(rank(pot_ssr)<4 & rank(pot_ssr)>2))\t# ***exponential***\n\tif(abs(lowest_rank - next_lowest_rank)==1 || abs(lowest_rank - next_lowest_rank)==35){\n\t\treturn(c(1, pot_ang[lowest_rank,1]))\n\t}else{\n\t\treturn(c(2, pot_ang[lowest_rank,1], pot_ang[next_lowest_rank, 1]))\n\t}\n}\n\nbaf_processor <- function(sv, obs, nlps, proposed_winddir){\t\t\t\t\t\t\t\t\t\t\n\tfdm <- matrix(c(-1,0,1,-1,0,1), nrow=2)\t\t\t\t\t\n\th <- 5\n\twarns <- 0\n\tresm <- data.frame(matrix(ncol=2,nrow=2))\n\tgdnt <- c()\t\n\twind_dir = proposed_winddir\n\tres <- fi(obs, sv, wind_dir)\n\tresm[1,1] <- wind_dir\n\tresm[1,2] <- res[1]\n\twind_dir <- wind_dir + h\n\tres <- fi(obs, sv, wind_dir)\n\tresm[2,1] <- wind_dir\n\tresm[2,2] <- res[1]\n\tif(resm[1,2] >= resm[2,2]){\n\t\tlid <- 1\t\n\t}else{\n\t\tlid <- -1\n\t}\n\tr = 1\n\tfor(i in 3:nlps){\n\t\tif(lid == 1){\n\t\t\twind_dir <- resm[order(resm[,2]),][1,1] + h\n\t\t\tlid <- 1\n\t\t}else if(lid == -1){\n\t\t\twind_dir <- resm[order(resm[,2]),][1,1] - 2 * h\n\t\t\tlid <- -1\n\t\t}else if(lid == 0 && r == 1){\n\t\t\th <- h * 0.4\n\t\t\twind_dir <-resm[order(resm[,2]),][1,1] + h\n\t\t\tr = 0\n\t\t}else if(lid == 0 && r == 0){\n\t\t\twind_dir <-resm[order(resm[,2]),][1,1] - h\n\t\t\tr = 1\n\t\t}\n\t\n\t\tres <- fi(obs, sv, wind_dir)\n\t\tresm[i,1] <- wind_dir\n\t\tresm[i,2] <- res[1]\n\t\tresm <- resm[order(resm[,1]),]\n\t\t\tif(lid == 1){\n\t\t\t\tgdnt <- fdm %*% resm[c(i-2,i-1,i),2]\n\t\t\t}\n\t\t\tif(lid == -1){\n\t\t\t\tgdnt <- fdm %*% resm[c(1,2,3),2] \n\t\t\t}\n\t\t\tif(lid == 0 ){\t\n\t\t\t\tn <- which(resm[,2]==min(resm[,2]))\n\t\t\t\tgdnt <- fdm %*% resm[c(n-1,n, n+1) ,2]\n\t\t\t}\n\t\tif(gdnt[1]<0 && gdnt[2]>=0){lid <- 0}\n\t\tif(gdnt[1]>=0 && gdnt[2] >= 0){lid <- -1}\n\t\tif(gdnt[1]<0 && gdnt[2] <0){lid <- 1}\n\t\tif(gdnt[1] > 0 && gdnt[2] < 0){lid <- -1}\n\t\t\n\t\tif(h < 0.01){break}\n\t}\n\ttemp <- resm[which(resm[,2]==min(resm[,2])),]\n\toutput <- as.matrix(cbind(temp[1], temp[2]), nrow = 1)\n\treturn(output)\t\t\n\t\n}\n\t\t\n\t\t\t\t\t\t\t\t\t\t\nbaf <- function(sv, obs, nlps){\n\traw_inference <- baf_pre(sv, obs, nlps)\n\tif(raw_inference[1] == 1){\n\t\toutput = baf_processor(sv, obs, nlps, raw_inference[2])\n\t\treturn(output)\n\t}else{\n\t\toutput_1 = baf_processor(sv, obs, nlps, raw_inference[2])\n\t\toutput_2 = baf_processor(sv, obs, nlps, raw_inference[3])\n\t\tif(output_1[2]0)){\n\t\treturn(1)\n\t}else{\n\t\tfirst_order_grad[first_order_grad > 0] = 0\t\n\t\tdirection = c(1,1,-1,-1)\n\t\tgrad_y = (-1*direction[c(1,3)])%*%first_order_grad[c(1,3)]\n\t\tgrad_x = (-1*direction[c(2,4)])%*%first_order_grad[c(2,4)]\n\t\tgrad_unit = c(grad_x/(grad_x^2+grad_y^2)^0.5, grad_y/(grad_x^2+grad_y^2)^0.5)\n\t\treturn(c(2,grad_unit))\n\t}\n}\n####################End of intermediate functions#################################\n\n#################### Function name: gd_simplified ####################\ngd_simplified <- function(sv, obs, runs, h, r, nlps, h_ratio, numb){\t\t\n obs = obs[numb,] \n\ttcoord <- as.data.frame(matrix(ncol=2))\t\t\t\n\tdec <- c()\n\thl <- c()\n\tihd <- h\n\tir=1\t\t\t\t\t\t\t\n\tjg <- 0\n\twarns <- 0\n\tfor(i in 1:runs){\n\t\t\tdec <- compare(sv, obs, h, nlps, h_ratio)\n\t\t\tif(dec[1]!= 1 && jg ==0){\n\t\t\t\t\tsv <- sv + h*dec[2:3]\n\t\t\t\t\ttcoord[i,] <- sv\n\t\t\t\t\thl[i] <- h\t\t\t\t\t\n\t\t\t\t\tjg <- 0\n\t\t\t}else if(dec[1] != 1 && jg == 1){\n\t\t\t\t\th <- h *(1 - r)\n\t\t\t\t\tsv <- sv + h*dec[2:3]\n\t\t\t\t\ttcoord[i,] <- sv\n\t\t\t\t\thl[i] <- h\t\t\t\t\t\n\t\t\t\t\tjg <- 0\n\t\t\t}else if(dec[1] == 1 && h/ihd >= 0.0001){\t\n\t\t\t\th = h * r\n\t\t\t\thl[i] <- h\t\n\t\t\t\tjg <- 1\n\t\t\t}\t\n\t\tif(h < 0.1){break}\n\t}\n\tbd <- baf(sv, obs, nlps)\n\trownames(tcoord) <- NULL\n\toutput_sv = tcoord[nrow(tcoord),]\n\toutput_ang = bd[1]\n\tfitted_results= fi2(obs, as.matrix(sv), output_ang)\n\treturn(as.matrix(cbind(sv, output_ang, h, coef = t(fitted_results[c(2,3,4)]), ssr = fitted_results[1], rsquare = fitted_results[5])))\n}\n\n########################################## End of functions #####################################################\n\n# Reference:\n#\tGonzalez-Mellado, A. O., and S. De la Cruz-Reyna. \"A simple semi-empirical approach to model thickness of \n# ash-deposits for different #eruption scenarios.\" Natural Hazards and Earth System Sciences 10.11 (2010): 2241.\n# \tYang Q, Bursik M. A new interpolation method to model thickness, isopachs, extent, and volume of tephra fall \n# deposits. Bulletin of Volcanology, 2016, 78(10): 68.\n\n\n\n", "meta": {"hexsha": "4e5164c27986a13602d52a3ea70aae3e21630c7f", "size": 7669, "ext": "r", "lang": "R", "max_stars_repo_path": "pub_svl_2.0_power-law.r", "max_stars_repo_name": "yiqioyang/svl", "max_stars_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pub_svl_2.0_power-law.r", "max_issues_repo_name": "yiqioyang/svl", "max_issues_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pub_svl_2.0_power-law.r", "max_forks_repo_name": "yiqioyang/svl", "max_forks_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_forks_repo_licenses": ["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.9141630901, "max_line_length": 134, "alphanum_fraction": 0.5829964793, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789132480439, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.592507562328706}} {"text": "# Negative log-likelihood component for the tag-recapture data\n# (using Gauss-Hermite quadrature) and assuming a lognormal distn for A.\n\n# Assumes data is in a matrix with columns: l1, l2, t1, t2, measr\n# where l1=release length \n# l2=recapture length \n# t1=release time (in julian time since Jan 1 of reference year) \n# t2=recapture time (in julian time since Jan 1 of reference year)\n# measr=0 if recapture length measured by a scientist\n# =1 if recapture length measured by a fisherman \n\n# Assumes parameters are: mu.L, sig.L, param.f, mu.logA, sig.logA, sig.s, sig.f\n# where param.f is parameters of growth function, mu.logA and sig.logA are\n# parameters of the log normal distribution for A, sig.s is the error variance\n# for scientists, and sig.f is the error variance for fisherman.\n\n# The log density of the age-at-tagging must be specified in a function \n# logdensA.f(a,param.A) \n \n# The errors are specified in the function error.ssnl.f\n\n #------------------------------------------------#\n\n\nlog.lognormA.f<- function(a,param.A)\n{ # the log density of the tagging age A \n # A log-normal \n alpha.A<- param.A[1]\n beta.A<- param.A[2]\n \n # a is nf x n matrix\n lna<- a\n tf<- a>0\n \n lna[tf]<- log(a[tf])\n lna[!tf]<- -300\n\n logpa<- (lna-alpha.A)/beta.A\n logpa<- -0.5*log(2*pi)-log(beta.A)-lna-0.5*logpa^2\n return(logpa)\n}\n\nlognormA.f<- function(a,param.A)\n{# dlnorm only takes vectors for the first argument\n veca<- as.vector(a)\n\n alpha.A<- param.A[1]\n beta.A<- param.A[2]\n \n tf<- a <= 0\n a[tf]<- exp(-30)\n\n pa<- dlnorm(veca,alpha.A,beta.A)\n pa<- matrix(pa,nrow=nrow(a),ncol=ncol(a),byrow=F)\n return(pa)\n}\n\n# The function logdensA.f() is changed if a new distribution for\n# A is tried\nlogdensA.f<- log.lognormA.f\ndensA.f<-lognormA.f\n\nerror.ssnl.f<- function(capstatus,measr,param.sig)\n{ # -this gives the additive error structure of the model\n # -capstatus = \"release\" or \"recapture\"\n # -measr = 0 if a scientist measured the recapture length\n # = 1 if a fisherman measured the recapture length\n \n sig.s<- param.sig[1] # s.d. for a scientiest\n sig.f<- param.sig[2] \t# this is the additional error for fishermen\n if(capstatus==\"release\")\n {sigma<- sig.s} \n if(capstatus==\"recapture\")\n {sigma<- sig.s+sig.f*measr}\n return(sigma)\n}\n\n\nha.ssnl.f<- function(a,tagdat,param.g,param.sig)\n{ # this calculates h(l1,l2|a)\n # it is needed as part of int.f\n \n # a is nf x n matrix\n tf<- a<0\n a[tf]<-0\n\n h<- exp(logha.ssnl.f(a,tagdat,param.g,param.sig))\n return(h)\n}\n\nlogha.ssnl.f<- function(a,tagdat,param.g,param.sig)\n{ # this calculates log h(l1,l2|a)\n # it is needed as part of logint.f\n\n # a is nf x n matrix\n tf<- a<0\n a[tf]<-0\n\n # retrieve the data\n l1<- tagdat[,1]\n l2<- tagdat[,2]\n t1<- tagdat[,3]\n t2<- tagdat[,4]\n measr<- tagdat[,5]\n \n # retrieve the growth curve parameters\n mu.L<- param.g[1]\n sigma.L<- param.g[2]\n param.f<- param.g[3:length(param.g)]\n\n ucol<- matrix(1,nrow=nrow(a),ncol=1)\n urow<- matrix(1,nrow=1,ncol=ncol(a))\n\n a2<- a+(t2-t1)%*%urow\n f1<- growth.ssnl.f(a,param.f,t1-floor(t1))\n f2<- growth.ssnl.f(a2,param.f,t2-floor(t2))\n sigma1<- error.ssnl.f(\"release\",measr,param.sig)\n sigma2<- error.ssnl.f(\"recapture\",measr,param.sig)\n mu1a<- mu.L*f1\n mu2a<- mu.L*f2\n var1a<- (sigma.L*f1)^2 + sigma1^2\n var2a<- (sigma.L*f2)^2 + sigma2^2\n s12<- sqrt(var1a*var2a)\n rhoa<- (sigma.L^2)*f1*f2/s12\n q1<- l1%*%urow-mu1a\n q2<- l2%*%urow-mu2a\n q12<- q1*q2\n q1<- q1^2/var1a\n q2<- q2^2/var2a\n q12<- q12*rhoa/s12\n q<- q1+q2-2*q12\n logh<- -log(2)-log(pi)-0.5*log(var1a)-0.5*log(var2a)-0.5*log(1-rhoa^2)\n rho<- 2*(1-rhoa^2)\n logh<- logh-q/rho\n return(logh)\n}\n\nint.ssnl.f<- function(a,tagdat,param.g,param.A,param.sig)\n{ # this calculates h(l1,l2|a) p(a)\n # so that later it can be integrated\n #\n # a is a nf x n matrix, where nf=nrow(tagdat)\n\n pa<- densA.f(a,param.A)\n integrand<- ha.ssnl.f(a,tagdat,param.g,param.sig)*pa\n return(integrand)\n}\n\nlogint.ssnl.f<- function(a,tagdat,param.g,param.A,param.sig)\n{ # this calculates -log[h(l1,l2|a) p(a)]\n # it is used in the grid search or golden section search\n # for the mode of h(l1,l2|a) p(a)\n # we search on the log scale because the log is more\n # numerically stable\n #\n # a is a nf x n matrix, where nf=nrow(tagdat)\n # tagdat is a nf x 4 matrix of variables l1,l2,t1,t2\n\n logpa<- logdensA.f(a,param.A)\n logha<- logha.ssnl.f(a,tagdat,param.g,param.sig)\n integrand<- logha+logpa\n return(integrand)\n}\n\nh.ssnl.f<- function(tagdat,param.g,param.A,param.sig)\n{\n # This calculates int_-\\infty^\\infty h(l1,l2|a) p(a) da\n # using 20-point Gauss-Hermite integration\n\n gms<- gstats.ssnl.f(tagdat,param.g,param.A,param.sig)\n mng<- gms[,1]\n sdg<- gms[,2]\n pdf.l1.l2<- hermite20.f(int.ssnl.f,tagdat,param.g,param.A,\n param.sig,nrow(tagdat),mng,sdg)\n return(pdf.l1.l2)\n}\n\nlogl.ssnl.f<-function(param,npf,npA,tagdat)\n{ # this calculates the negative log likelihood of the data\n\n npg<- npf+2\n param.g<- param[1:npg]\n param.A<- param[(npg+1):(npg+npA)]\n param.sig<- param[(npg+npA+1):(npg+npA+2)]\n\n # print(c(param.g, param.A, param.sig))\n \n ndata<- nrow(tagdat)\n gms<- gstats.ssnl.f(tagdat,param.g,param.A,param.sig)\n mng<- gms[,1]\n sdg<- gms[,2]\n pdf.l1.l2<- hermite20.f(int.ssnl.f,tagdat,param.g,param.A,\n\t\tparam.sig,ndata,mng,sdg)\n negloglz<- -sum(log(pdf.l1.l2))\n if(is.na(neglogl)){print(\" neglogl NA \")}\n return(neglogl)\n}\n\n\nhermite20.f<- function(f,tagdat,param.g,param.A,param.sig,nf,mu,sigma)\n { # this carries out 20-point Gauss-Hermite integration of f(x)\n # i.e. int_-\\infty^\\infty f(x) dx\n # it assumes that f(x) is roughly Gaussian with mean mu and s.d. sigma\n # here f is a nfx1 vector of functions, and mu, sigma are nfx1 vectors\n #\n # tagdat is a matrix of data which comprise the second argument of f\n # param is a vector of parameters which comprise the third argument of f\n #\n x<- c(-5.3874808900112,-4.6036824495507,-3.9447640401156,-3.3478545673832,\n -2.7888060584281,-2.2549740020893,-1.7385377121166,-1.2340762153953,\n -0.7374737285454,-0.2453407083009, 0.2453407083009, 0.7374737285454,\n 1.2340762153953, 1.7385377121166, 2.2549740020893, 2.7888060584281,\n 3.3478545673832, 3.9447640401156, 4.6036824495507, 5.3874808900112)\n\n wexp<- c(0.8985919614532, 0.7043329611769, 0.6222786961914, 0.5752624428525,\n 0.5448517423644, 0.5240803509486, 0.5096790271175, 0.4999208713363,\n 0.4938433852721, 0.4909215006667, 0.4909215006667, 0.4938433852721,\n 0.4999208713363, 0.5096790271175, 0.5240803509486, 0.5448517423644,\n 0.5752624428525, 0.6222786961914, 0.7043329611769, 0.8985919614532)\n\n rt2<- c(1.414213562373)\n urow<- matrix(1,nrow=1,ncol=20)\n\n xmat<- rt2*(sigma%*%t(x))+mu%*%urow # xmat is a nf x 20 matrix\n fx<- f(xmat,tagdat,param.g,param.A,param.sig)\n \n intf<- fx%*%wexp\n intf<- rt2*sigma*intf\n if(sum(is.na(intf))>0){print(\" hermite20 NA \")}\n return(intf)\n}\n\ngridsch.f<- function(f,l,u,vmat,param.g,param.A,param.sig)\n{ # gridsch.f is a grid search\n #\n # l is vector of true lower bounds\n # u is a vector of true upper bounds\n\n eps1<- 1e-13\n\n n<- 100\n urow<- matrix(1,nrow=1,ncol=(n+1))\n range<- u-l\n ind<- (0:n)\n x<- range%*%t(ind)\n x<- l%*%urow+x/n\n fx<- f(x,vmat,param.g,param.A,param.sig)\n fmax<- apply(fx,1,max)\n xmax<- fmax%*%urow\n tf<- fx >= xmax - eps1\n\n # if there are two minima in a row by some extraordinary chance,\n # xmax found in the following line of code will keep both\n # this is undesirable\n \n # xmax<- as.vector(t(x)[t(tf)])\n\n # the following piece of code avoids that problem\n rmax<- row(x)[tf]\n cmax<- col(x)[tf]\n tf<- (!duplicated(rmax))\n rmax<- rmax[tf]\n cmax<- cmax[tf]\n ord<- order(rmax)\n rmax<- rmax[ord]\n cmax<- cmax[ord]\n rcmax<- cbind(rmax,cmax)\n xmax<- as.vector(x[rcmax])\n if(min(cmax)==1) {print(\"maximum on lower bound\")\n print(\"rows\")\n print(rmax[cmax==1])\n #browser()\n cmax[cmax==1]<-2\n }\n if(max(cmax)==ncol(x)) {print(\"maximum on upper bound\")\n print(\"rows\")\n print(rmax[cmax==ncol(x)])\n #browser()\n cmax[cmax==ncol(x)]<-ncol(x)-1\n }\n rcmax<- cbind(rmax,cmax-1)\n a1<- as.vector(x[rcmax])\n f1<- as.vector(fx[rcmax])\n rcmax<- cbind(rmax,cmax+1)\n a3<- as.vector(x[rcmax])\n f3<- as.vector(fx[rcmax])\n return(cbind(a1,f1,xmax,fmax,a3,f3))\n}\n\nquadmax.f<- function(ahdat)\n{ # we are attempting to improve the estimate of the location \n # of the maximum of a nearly quadratic function h(a)\n # ahdat = cbind(a1,h1,a2,h2,a3,h3)\n # a1 < a2 < a3\n # h2>h1 and h2>h3\n\n a1<- ahdat[,1]\n h1<- ahdat[,2]\n a2<- ahdat[,3]\n h2<- ahdat[,4]\n a3<- ahdat[,5]\n h3<- ahdat[,6]\n\n dett<- (a1-a2)*(a3-a2)*(a3-a1)\n alpha<- ((a3-a2)^2)*(h1-h2)-((a1-a2)^2)*(h3-h2)\n beta<- -(a3-a2)*(h1-h2)+(a1-a2)*(h3-h2)\n alpha<- alpha/dett\n beta<- beta/dett\n mng<- a2-alpha/(2*beta)\n sdg<- sqrt(-1/(2*beta))\n return(cbind(mng,sdg))\n}\n\n\ngstats.ssnl.f<- function(tagdat,param.g,param.A,param.sig)\n{ qt1<- 0.001\n qt2<- 15\n \n l<- matrix(rep(qt1,nrow(tagdat)),ncol=1)\n u<- matrix(rep(qt2,nrow(tagdat)),ncol=1)\n \n aa<- gridsch.f(logint.ssnl.f,l,u,tagdat,param.g,param.A,param.sig)\n brk<-0\n for(i in (1:10))\n {ms<- quadmax.f(aa)\n\n\t# we need to make sure that the mng values have stabilised\n\t# if it has we break out\n\tif(i>3)\n\t {stdiff<- abs((ms[,1]-mngold)/ms[,2])\n\t msd<- max(stdiff)\n\t if(msd<0.2)\n\t { brk<- 1\n\t break\n\t }\n }\n\t\n\t# if not, we refine the estimates\n a2<- pmax(ms[,1],0.9*aa[,1]+0.1*aa[,5])\n a2<- pmin(a2,0.1*aa[,1]+0.9*aa[,5])\n a1<- pmin(a2,aa[,3])\n a2<- a2+aa[,3]-a1\n a1<- pmin(a1,0.1*aa[,1]+0.9*a2)\n f12<- logint.ssnl.f(cbind(a1,a2),tagdat,param.g,param.A,param.sig)\n tf<- f12[,1] 0) \n {\n diccTipos[distXtipo[index,2]] <- diccTipos[distXtipo[index,2]] + 1\n index = index + 1\n k = k - 1 \n #si ya no quedan m�s vecinos por recorrer\n #cuando el dicc esta completo\n if(k == 0)\n {\n for(i in 1:(length(diccTipos) - 1 ))\n {\n value = diccTipos[i]\n if(max < value){\n cadena = names(value)\n max = value\n flag = FALSE\n }\n else if (max == value){\n flag = TRUE\n }\n }\n #Si la moda se repite en 2 tipos de datos entonces \n #aumentamos en 1 el k\n if (flag == TRUE)\n {\n k = k + 1\n }\n }\n }\n return(cadena)\n}\n\ncrear_persona <- function() \n{\n \n \n while (TRUE) \n {\n gender <- as.integer(readline(writeLines(\"Cual es su genero?\\nOPCIONES:\\n(0) Masculino\\n(1) Femenino \")))\n if (gender == 0) {\n gender <- \"Male\"\n break\n }\n else if (gender == 1) {\n gender <- \"Female\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n \n age <- as.integer(readline(\"Cual es su edad?: \\n\"))\n \n height <-as.double(readline(\"Cual es su altura en metros?: \\n\"))\n \n weight <-as.double(readline(\"Cual es su peso en kg?: \\n\"))\n \n \n while (TRUE) \n {\n family_overweight <-as.integer(readline(writeLines(\"En su familia alguien sufre o ha sufrido de sobrepeso?\\nOPCIONES:\\n(0) SI\\n(1) NO \")))\n if (family_overweight == 0) {\n family_overweight <- \"yes\"\n break\n }\n else if (family_overweight == 1) {\n family_overweight <- \"no\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n \n \n while (TRUE) \n {\n favc <- as.integer(readline(writeLines(\"Come comida alta en calorias frecuentemente?\\nOPCIONES:\\n(0) SI\\n(1) NO \")))\n if (favc == 0) {\n favc <- \"yes\"\n break\n }\n else if (favc == 1) {\n favc <- \"no\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n fcvc <-as.integer(readline(writeLines(\"Come vegetales en su comida?\\nOPCIONES:\\n(0) Nunca\\n(1) A veces\\n(2) Siempre? \")))\n if (fcvc == 0) \n {\n fcvc <- 1\n break\n }\n else if (fcvc == 1) {\n fcvc <- 2\n break\n }\n else if (fcvc == 2) {\n fcvc <- 3\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n ncp <-as.integer(readline(writeLines(\"Cuantas comidas principales ingiere en el dia?\\nOPCIONES:\\nINgrese un n�mero entre 1-4\")))\n if (ncp >= 1 | ncp <=4){ \n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n caec <- as.integer(readline(writeLines(\"Come algo durante sus comidas? \\nOPCIONES:\\n(0) Nunca\\n(1) A veces\\n(2) Frecuentemente\\n(3) Siempre \")))\n if (caec == 0) {\n caec <- \"no\"\n break\n }\n else if (caec == 1) {\n caec <- \"Sometimes\"\n break\n }\n else if (caec == 2) {\n caec <- \"Frequently\"\n break\n }\n else if (caec == 3) {\n caec <- \"Always\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n smoke <- as.integer(readline(writeLines(\"Usted fuma?\\n OPCIONES:\\n(0) SI\\n(1) NO \")))\n if (smoke == 0) {\n smoke <- \"yes\"\n break\n }\n else if (smoke == 1) {\n smoke <- \"no\"\n break\n }\n \n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n \n while (TRUE) \n {\n ch20 <-as.integer(readline(writeLines(\"Cuanta agua bebe al dia?\\nOPCIONES:\\n(0) Menos de 1 litro\\n(1) Entre 1 y 2 litros\\n(2) Mas de 2 litros \")))\n \n if (ch20 == 0) \n {\n ch20 <- 1\n break\n }\n else if (ch20 == 1) {\n ch20 <- 2\n break\n }\n else if (ch20 == 2) {\n ch20 <- 3\n break\n }\n \n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n scc <-as.integer(readline(writeLines(\"Monitorea sus calorias diariamente?\\nOPCIONES:\\n(0) SI\\n(1) NO \")))\n if (scc == 0) {\n scc <- \"yes\"\n break\n }\n else if (scc == 1) {\n scc <- \"no\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n faf <-as.integer(readline(writeLines(\"Cuantas veces a la semana hace actividad fisica?\\nOPCIONES:\\n(0) Nunca\\n(1) 1 o 2 dias\\n(2) 2 o 4 dias\\n(3) 4 o 5 dias \")))\n if (faf == 0 | faf == 1 | faf== 2 | faf== 3) {\n break\n }\n \n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n \n while (TRUE) \n {\n tue <-as.integer(readline(writeLines(\"Cuanto tiempo usa aparatos tecnologicos?\\nOPCIONES:\\n(0) 0 a 2 horas\\n(1) 3 a 5 horas\\n(2) Mas de 5 horas \")))\n if (tue == 0 | tue == 1 | tue== 2) {\n break\n }\n \n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n while (TRUE) \n {\n calc <-as.integer(readline(writeLines(\"Que tan amenudo ingiere alcohol?\\nOPCIONES:\\n(0) Nunca\\n(1) A veces\\n(2) Frecuentemente\\n(3) Siempre \")))\n if (calc == 0) {\n calc <- \"no\"\n break\n }\n else if (calc == 1) {\n calc <- \"Sometimes\"\n break\n }\n else if (calc == 2) {\n calc <- \"Frequently\"\n break\n }\n else if (calc == 3) {\n calc <- \"Always\"\n break\n }\n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n \n \n \n while (TRUE) \n {\n mtran <-as.integer(readline(writeLines(\"Que medio de transporte normalmente usa?\\nOPCIONES:\\n(0) Automovil\\n(1) Motocileta\\n(2) Bicicleta\\n(3) Transporte publico\\n(4) Caminando \")))\n if (mtran == 0) {\n mtran <- \"Automobile\"\n break\n }\n else if (mtran == 1) {\n mtran <- \"Motorbike\"\n break\n }\n else if (mtran == 2) {\n mtran <- \"Bike\"\n break\n }\n else if (mtran == 3) {\n mtran <- \"Public_Transportation\"\n break\n }\n else if (mtran == 4) {\n mtran <- \"Walking\"\n break\n }\n \n else\n {\n print(\"Ingresar un valor dentro de las opciones\") \n }\n }\n \n persona = c(gender,age,height,weight,family_overweight,favc,fcvc,ncp,caec,smoke,ch20,scc,faf,tue,calc,mtran)\n \n return(persona)\n \n}\n\n\n\n#leemos el csv\ndata<-read.csv('data.csv')\n\n# persona <- rep(NA, 17) <= para cuando hagamos el input\npersona <- crear_persona()\n#print(persona)\n\n#persona2 <- c('Female', 15, 1.7 , 80, 'yes' , 'yes' , 2 , 2 , 'Always' , 'no' , 3 , 'yes', 0, 0, 'no','Walking')\n\npaste(\"La clasificacion de la persona es:\", knn(30,calcDist(persona, data)), sept= \" \")\n\n", "meta": {"hexsha": "756da1a982f3eccffe42bc2f95ab37754bb0c6c3", "size": 10066, "ext": "r", "lang": "R", "max_stars_repo_path": "knnR/main.r", "max_stars_repo_name": "ItsJavito/knnLP", "max_stars_repo_head_hexsha": "1dbde3434e0326f30798f5c730decd664abb712a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "knnR/main.r", "max_issues_repo_name": "ItsJavito/knnLP", "max_issues_repo_head_hexsha": "1dbde3434e0326f30798f5c730decd664abb712a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "knnR/main.r", "max_forks_repo_name": "ItsJavito/knnLP", "max_forks_repo_head_hexsha": "1dbde3434e0326f30798f5c730decd664abb712a", "max_forks_repo_licenses": ["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.3009259259, "max_line_length": 185, "alphanum_fraction": 0.5507649513, "num_tokens": 3393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5915445103772878}} {"text": "# DLC 2019\n# set of functions allowing to define Var[y]\n# and plot Corr[y] for objects of class\n# lmerModLmerTest or lmerMod\n\n\nOmega.matrix = function(model) {\n if(class(model)[1]==\"lmerModLmerTest\"|class(model)[1]==\"lmerMod\"){\n sigma2.epsilon = sigma(model)^2\n Psi.star = crossprod(getME(model,\"Lambdat\"))*sigma2.epsilon\n Z = getME(model,\"Z\")\n Omega = Z %*% Psi.star %*% t(Z) + sigma2.epsilon* Diagonal(nrow(Z))\n Omega\n }else{\n warning(\"Function only works on outcput of function lmer()\\n\")\n }\n }\n #Corr.fun = function(Sigma){\n # D = sqrt(diag(diag(Sigma)))\n # DInv = solve(D)\n # DInv %*% Sigma %*% DInv\n # }\nOmega.plot = function(Omega,legend=TRUE,axes=TRUE){\n corw = cov2cor(Omega)\n if(any(corw<0)){\n colw=c(gray(1),rainbow(197)[197:100],gray(.9),rainbow(197)[99:1],gray(0))\n zlim=c(-1,1)\n }else{\n colw=c(gray(.9),rainbow(98)[98:1],gray(0))\n zlim=c(0,1)\n }\n image(z=as.matrix(corw[nrow(corw):1,]),zlim=zlim,axes=FALSE,col=colw)\n if(legend){ \n valw = as.numeric(names(table(as.matrix(corw)))) \n posw = round(valw*length(colw))\n posw[posw==0] = 1\n posw[posw>length(colw)] = length(colw) \n legend(\"topright\",ncol=1,legend=format(round(valw,4)),\n col=colw[posw],pch=15,bg=\"light gray\",\n title=\"Values\",box.lwd=NA)\n }\n if(axes){\n axis(3,at=seq(0,1,length=nrow(Omega)),labels=FALSE)\n axis(2,at=seq(0,1,length=nrow(Omega)),labels=FALSE)\n axis(2,at=c(1,0),c(1,nrow(Omega)),las=2)\n axis(3,at=c(0,1),c(1,nrow(Omega)),las=1)\n }\n }\n", "meta": {"hexsha": "e7cd0e33ac42a6bb03934bf9ca93cebad88f1e83", "size": 1696, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/Omega.r", "max_stars_repo_name": "lukaskln/TumorAnalysis", "max_stars_repo_head_hexsha": "62a33f490a9778dcaa08adf2d1d5175b307e0174", "max_stars_repo_licenses": ["MIT"], "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/Omega.r", "max_issues_repo_name": "lukaskln/TumorAnalysis", "max_issues_repo_head_hexsha": "62a33f490a9778dcaa08adf2d1d5175b307e0174", "max_issues_repo_licenses": ["MIT"], "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/Omega.r", "max_forks_repo_name": "lukaskln/TumorAnalysis", "max_forks_repo_head_hexsha": "62a33f490a9778dcaa08adf2d1d5175b307e0174", "max_forks_repo_licenses": ["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.612244898, "max_line_length": 84, "alphanum_fraction": 0.5536556604, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5914078147046508}} {"text": "library(bivpois) # load bivpois library\r\ndata(ex2.sim) # load ex2.sim data from bivpois library\r\nxtemp<-readline(prompt = \"Press Enter to Continue\")\r\n#\r\nex2.m1<-lm.bp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim )\t\t# Model 1: BivPois\r\nex2.m2<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=0)\t# Model 2: Zero Inflated BivPois \r\nex2.m3<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=1)\t# Model 3: Diagonal Inflated BivPois with DISCRETE(1) diagonal inflation distribution\r\nex2.m4<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=2)\t# Model 4: Diagonal Inflated BivPois with DISCRETE(2) diagonal inflation distribution\r\nex2.m5<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=3)\t# Model 5: Diagonal Inflated BivPois with DISCRETE(3) diagonal inflation distribution\r\nex2.m6<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=4)\t# Model 6: Diagonal Inflated BivPois with DISCRETE(4) diagonal inflation distribution\r\nex2.m7<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=5)\t# Model 7: Diagonal Inflated BivPois with DISCRETE(5) diagonal inflation distribution\r\nex2.m8<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , jmax=6)\t# Model 8: Diagonal Inflated BivPois with DISCRETE(6) diagonal inflation distribution\r\nex2.m9<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , distribution='poisson')\t# Model 9: Diagonal Inflated BivPois with POISSON diagonal inflation distribution\r\nex2.m10<-lm.dibp( x~z1 , y~z1+z5, l1l2=~z3, l3=~.-z5, data=ex2.sim , distribution='geometric')\t# Model 10: Diagonal Inflated BivPois with GEOMETRIC diagonal inflation distribution\r\n#\r\n# printing parameters of model 7\r\nex2.m7$beta1\r\nex2.m7$beta2\r\nex2.m7$beta3\r\nex2.m7$p\r\nex2.m7$theta\r\n#\r\n# printing parameters of model 9\r\nex2.m9$beta1\r\nex2.m9$beta2\r\nex2.m9$beta3\r\nex2.m9$p\r\nex2.m9$theta\r\n\r\n\r\n\r\n", "meta": {"hexsha": "9f02ce51a975423702212bdea08fcd5683522c58", "size": 1909, "ext": "r", "lang": "R", "max_stars_repo_path": "bivpois/demo/ex2.r", "max_stars_repo_name": "Louagyd/FootballScorelineForecasting", "max_stars_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bivpois/demo/ex2.r", "max_issues_repo_name": "Louagyd/FootballScorelineForecasting", "max_issues_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bivpois/demo/ex2.r", "max_forks_repo_name": "Louagyd/FootballScorelineForecasting", "max_forks_repo_head_hexsha": "fd58d45304fb735cdc2ea612610fa7439345f72d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.65625, "max_line_length": 180, "alphanum_fraction": 0.694604505, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5912643826941884}} {"text": "\n#------------------------------------------------------------------------------------------------------------------\n#Step PRE: Some functions that is used later on in the mod.jointly.generate.binary.normal function algorithm \n#and so on\n\n# Function1: closest element\n# returns whichever element of candidates vector is closest in abs value to x\n\nclosest = function(x, candidates) {\n return( candidates[ which.min( abs(candidates - x) ) ] )\n}\n\n\n# Function2: binary-normal correlation bound ######\n# given parameters for 1 binary and 1 normal RV, return the maximum correlation\n\nBN.rBound = function(p) {\n q = 1-p\n \n #compute upper bound\n hiBound = dnorm( qnorm(p) ) / sqrt(p*q)\n return( round(hiBound, 2) )\n}\n\n\n# Function3: expand a matrix of slot_0 to the number of specified stages for time_invariant covariate setting\n# repeat each subject's entry in each row for obs number of times\nexpand_matrix = function(.matrix, .n.stage) {\n library(plyr)\n cat(\"Expanding a time invariant covariates to the number of specified stages\\n\")\n \n .n = nrow(.matrix)\n .expanded = matrix(c(NA), nrow = .n*.n.stage, ncol = ncol(.matrix) )\n \n adply(.matrix, 1, function(..subject, ..obs) {\n matrix(rep(..subject, ..obs), nrow = ..obs, byrow = TRUE)\n }, .n.stage)\n \n}\n\n# FUNCTION4: UPPER TRI VEC: \n# turns matrix into vector of upper-triangular elements\n\nupper_tri_vec = function(m) {\n v1 = as.vector( t(m) )\n keepElement = as.vector( t(upper.tri(m) ) ) #use transpose to avoid going by columns\n v2 = as.numeric( v1[keepElement] )\n return(v2)\n}\n#------------------------------------------------------------------------------------------------------------------\n#Step 1: Creating the \"Across\" data\n\nmod.generate.jointly.binary=function(no.rows,no.binary,prop.vec.binary,corr.vec.binary, adjust.corrs = TRUE){\n #Definition of the arguments are as follows:\n #no.rows=Number of subjects\n #no.bin=Number of binary variables (among these )\n #no.nor=Number of normally distributed variables\n #prop.vec.binary=Vector of marginal proportions for binary variables\n #mean.vec.nor=Vector of means for normal variables\n #var.nor=Vector of variances for normal variables\n #corr.vec.binary=Specified correlations among all variables\n #b=2*no.bin #b is double number of the total binary vars\n d=no.binary #d is the total dimension \n #adjust.corrs=T/F. If a correlation is out of bounds, should it\n # be adjusted to the closest feasible values?\n \n ############################################################\n #Important note 1: For convenience, binary variables are assumed\n #to come first, then normal variables follow\n #Important note 2: Correlations are specified in vector form,\n #rather than a matrix form. If the dimension is d, d*(d-1)/2\n #non-redundant correlation terms must be specified. The order\n #in which correlations are specified is based on the upper diagonal\n #elements. For example, if there are four variables (X1,X2,X3,X4),\n #corr.vec.binary is specified in the following form:\n #c(Corr(X1,X2),Corr(X1,X3),Corr(X1,X4),Corr(X2,X3),Corr(X2,X4),\n #Corr(X3,X4))\n #------------------------------------------------------------------------------------------------------------------\n #Step 1-1 Series of control statements to prevent obvious ARGUMENT\n #SPECIFICATION ERRORS:\n \n if ((no.rows<1)|(floor(no.rows)!=no.rows)){stop(\"Number of rows must be\n an integer whose value is at least 1!\\n\")}\n if ((no.binary<1)|(floor(no.binary)!=no.binary)){stop(\"Number of binary variables\n must be an integer whose value is at least 1!\\n\")}\n \n \n if ((min(prop.vec.binary)<=0)|(max(prop.vec.binary)>=1)){\n stop(\"Proportions for binary variables must be between 0 and 1!\\n\")}\n if (length(prop.vec.binary)!=no.binary){stop(\"Proportion vector\n is misspecified, dimension is wrong!\\n\")}\n \n if(length(corr.vec.binary)!=(d*(d-1)/2)){\n stop(\"Vector of correlations is misspecified, dimension is wrong!\\n\")}\n \n #------------------------------------------------------------------------------------------------------------------\n #Step 1-2: Statements to check CORRELATION BOUND VIOLATIONS\n \n #Step 1-2-1: Form a correlation matrix from the specified correlation vector\n # this is equivalent to lower.tri.to.corr.mat function from BinNor package\n # that Converts a lower vector to a full correlation matrix\n sigma=diag(d)\n temp=1\n for(i in 1:(d-1)){\n for(j in (i+1):d){\n sigma[i,j]=sigma[j,i]=corr.vec.binary[temp]\n temp=temp+1\n }\n }\n #------------------------------------------------------------------------------------------------------------------\n \n #Step 1-2-1: Check if the specified correlation matrix is positive definite, if not\n #find the nearest positive definite matrix\n #This is equivalent to the function: compute.sigma.star from BinNor package that\n #Computes intermediate (tetrachoric) correlation matrix\n \n if(is.positive.definite(sigma)==FALSE)\n {sigma=make.positive.definite(sigma)\n print(\"Specified correlation matrix is not positive definite,\")\n print(\"Algorithm will be using the closest positive definite matrix!\")}\n \n diag(sigma)=1\n \n p=prop.vec.binary\n q=1-p\n #------------------------------------------------------------------------------------------------------------------\n \n #Step 1-2-2: Checks if the correlation terms are within the feasible range\n #This is equivalent to the function: validation.range from BinNor package that\n #Checks if the correlation terms among binary-binary, binary-normal\n #and normal-normal combinations.are within the feasible range\n \n #Check if the correlations for binary-binary combinations are\n #in the feasible range\n \n #Boundaries for BB =[max(-sqrt((pi*pj)/(qi*qj)),-sqrt((qi*qj)/(pi*pj))),\n #min(sqrt((pi*qj)/(qi*pj)),sqrt((qi*pj)/(pi*qj)))]\n L_BB=diag(no.binary)\n U_BB=diag(no.binary)\n \n for(i in 1:no.binary){\n for(j in 1:no.binary){\n if (i!=j) L_BB[i,j]=L_BB[j,i]=max(-sqrt((p[i]*p[j])/(q[i]*q[j])),\n -sqrt((q[i]*q[j])/(p[i]*p[j])))\n if (i!=j) U_BB[i,j]=U_BB[j,i]=min(sqrt((p[i]*q[j])/(q[i]*p[j])),\n sqrt((q[i]*p[j])/(p[i]*q[j])))\n }\n }\n \n \n for(i in 1:no.binary){\n for(j in 1:no.binary){\n if(sigma[i,j]U_BB[i,j]) {\n if (!adjust.corrs) {\n # if user does not want to adjust correlations, give error\n stop(\"BB corrrelation [\", i,\",\",j,\"] is out of range! Specify a feasible number!\")\n } else {\n #adjust correlation to the closest feasible value\n cat( c(\"BB corrrelation [\", i,\",\",j,\"],\", sigma[i,j], \", is out of range! Used closest feasible correlation instead\\n\"))\n sigma[i,j] = sigma[j,i] = closest(sigma[i,j], c( L_BB[i,j], U_BB[i,j] ) )\n }\n }\n }\n }\n \n \n #Compute the biserial correlations for binary-normal combinations and\n #check if they are in the feasible range\n \n #temporary matrix\n #BN_temp=sigma\n \n # replace the BN values in BN_temp with the corresponding phi values correlation btw binary and normal\n #for(i in (no.binary+1):d){ \n #for(j in 1:no.binary){\n #BN_temp[i,j]=BN_temp[i,j]/(dnorm(qnorm(p[j]))/sqrt(p[j]*q[j]))\n #}\n #}\n \n #for(i in (no.binary+1):d){\n #for(j in 1:no.binary){\n #if (BN_temp[i,j]< -1 | BN_temp[i,j]> 1) {\n \n #if (!adjust.corrs) {q\n # if user does not want to adjust correlations, give error\n #stop(\"BN correlation [\", i,\",\",j,\"] is out of range! Specify a feasible number!\")\n #} else {\n #adjust correlation to the closest feasible value\n #BN_temp[i,j] = closest(BN_temp[i,j], c(-1, 1))\n \n #}\n # }\n #}\n # }\n \n #keep the BN part of BN_temp matrix\n #BN=BN_temp[(no.binary+1):d,1:no.binary]\n \n #Compute the tetrachoric correlations for binary-binary combinations\n \n \n # create sigmaBB matrix by converting BB part of sigma into polychoric correlations\n sigmaBB=diag(no.binary)\n for(i in 1:no.binary){\n for(j in 1:no.binary){\n if (i > j) {\n sigmaBB[i,j] = sigmaBB[j,i] = phi2poly( sigma[i,j] ,p[i],p[j])\n #force symmetry because phi2poly is an imperfect optimization process with rounding error\n }\n #########################################################################\n ###### NOTE: ABOVE ROUNDING OF SIGMA ENTRY IS A LITTLE SKETCH!!!!! ######\n #########################################################################\n \n }\n }\n \n \n #Biserial correlations for binary-normal combinations\n #sigmaBN=BN\n \n #Combine all three types (binary-binary, binary-normal, normal-normal)\n #of correlations to construct the overall correlation matrix\n #(Step 7 in the algorithm)\n sigma_new=sigma\n sigma_new[1:no.binary,1:no.binary]=sigmaBB\n #sigma_new[(no.binary+1):d,1:no.binary]=sigmaBN\n #sigma_new[1:no.binary,(no.binary+1):d]=t(sigmaBN)\n \n \n #Check if the final correlation matrix is positive definite, if not\n #find the nearest positive definite matrix (Step 8 in the algorithm)\n \n if(is.positive.definite(sigma_new)==FALSE) {\n sigma_new=make.positive.definite(sigma_new)\n print(\"Final correlation matrix is not positive definite,\")\n print(\"Algorithm will be using the closest positive definite matrix!\")\n }\n #------------------------------------------------------------------------------------------------------------------\n \n \n #Step 1-3: Generate multivariate normal data (Step 9 in the algorithm)\n data=rmvnorm(no.rows,mean=rep(0,d), sigma=sigma_new)\n \n #------------------------------------------------------------------------------------------------------------------\n #\n ##\n ###\n ####\n ##### shouldn't be abs(data[i,j])<=qnorm(1-p[j])) ???? check BinNOR \n #Step 1-3-1: Obtain binary variables by the thresholds determined by marginal proportions\n \n for(i in 1:no.rows){\n for(j in 1:no.binary){\n if(data[i,j]<=qnorm(1-p[j])) data[i,j]=0 else data[i,j]=1\n }\n }\n \n #------------------------------------------------------------------------------------------------------------------\n \n #------------------------------------------------------------------------------------------------------------------\n #Step 1-3-3: Go back to the original scale for normal variables by reverse centering and\n \n \n #------------------------------------------------------------------------------------------------------------------\n \n \n #step 1-4: Output is the data matrix!\n diag(sigma_new)=1\n return(list(data,sigma_new))\n #return(data)\n }", "meta": {"hexsha": "f0fa1c051a553793bc10085b290f78d8aa4c1c93", "size": 11456, "ext": "r", "lang": "R", "max_stars_repo_path": "Generate.Correlate.Binary.r", "max_stars_repo_name": "ashkanfa/Generate.Artificial.Data", "max_stars_repo_head_hexsha": "36a27c8cd236d303727dafb368b65f0bed05c3b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-22T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T19:50:36.000Z", "max_issues_repo_path": "Generate.Correlate.Binary.r", "max_issues_repo_name": "ashkanfa/Generate.Artificial.Data", "max_issues_repo_head_hexsha": "36a27c8cd236d303727dafb368b65f0bed05c3b5", "max_issues_repo_licenses": ["MIT"], "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.Correlate.Binary.r", "max_forks_repo_name": "ashkanfa/Generate.Artificial.Data", "max_forks_repo_head_hexsha": "36a27c8cd236d303727dafb368b65f0bed05c3b5", "max_forks_repo_licenses": ["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.2730627306, "max_line_length": 140, "alphanum_fraction": 0.5224336592, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5909377931969053}} {"text": "obrisi = function(podatki, hc = TRUE, od = 2, do = NULL) {\n n = nrow(podatki)\n if (is.null(do)) {\n do = n - 1\n }\n \n razdalje = dist(podatki)\n \n k.obrisi = tibble()\n for (k in od:do) {\n if (hc) {\n o.k = hclust(razdalje) %>%\n cutree(k) %>%\n silhouette(razdalje)\n } else {\n set.seed(42) # zato, da so rezultati ponovljivi\n o.k = kmeans(podatki, k)$cluster %>%\n silhouette(razdalje)\n }\n k.obrisi = k.obrisi %>% bind_rows(\n tibble(\n k = rep(k, n),\n obrisi = o.k[, \"sil_width\"]\n )\n )\n }\n k.obrisi$k = as.ordered(k.obrisi$k)\n \n k.obrisi\n}\n\nobrisi.povprecje = function(k.obrisi) {\n k.obrisi.povprecje = k.obrisi %>%\n group_by(k) %>%\n summarize(obrisi = mean(obrisi))\n}\n\nobrisi.k = function(k.obrisi) {\n obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n summarize(k = min(k)) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\n\ndiagram.obrisi = function(k.obrisi) {\n ggplot() +\n geom_boxplot(\n data = k.obrisi,\n mapping = aes(x = k, y = obrisi)\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = k, y = obrisi),\n color = \"red\"\n ) +\n geom_line(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = as.integer(k), y = obrisi),\n color = \"red\"\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n filter(k == min(k)),\n mapping = aes(x = k, y = obrisi),\n color = \"blue\"\n ) +\n xlab(\"število skupin (k)\") +\n ylab(\"obrisi (povprečje obrisov)\") +\n ggtitle(paste(\"Maksimalno povprečje obrisov pri k =\", obrisi.k(k.obrisi))) +\n theme_classic()\n}\n\n", "meta": {"hexsha": "d0eb84d9ae51e8d7943ed6f8f122960d77f8e053", "size": 1731, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/obrisi.r", "max_stars_repo_name": "justinraisp/APPR-2021-22", "max_stars_repo_head_hexsha": "dd89b278ad15f78d7d733da85b72f41ab2d152c4", "max_stars_repo_licenses": ["MIT"], "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/obrisi.r", "max_issues_repo_name": "justinraisp/APPR-2021-22", "max_issues_repo_head_hexsha": "dd89b278ad15f78d7d733da85b72f41ab2d152c4", "max_issues_repo_licenses": ["MIT"], "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/obrisi.r", "max_forks_repo_name": "justinraisp/APPR-2021-22", "max_forks_repo_head_hexsha": "dd89b278ad15f78d7d733da85b72f41ab2d152c4", "max_forks_repo_licenses": ["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.4805194805, "max_line_length": 80, "alphanum_fraction": 0.5343731947, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5903969081778553}} {"text": "#' Compute payment plan\n#'\n#' @param balance current balance or principal\n#' @param income adjusted gross income\n#' @param rate interest rate on loan\n#' @param years number of years to calculate. Most debt forgiven after 25 years.\n#' @param plan which payment plan to use\n#' @param subsidized whether the government will help subsidze accrued interest\n#' @param income_increase Expected increase in income per year.\n#' @export\ncompute_payments <- function(balance, income, rate, years,\n plan = c(\"repaye\"),\n subsidized = FALSE,\n income_increase = 0.05,\n family_size = 1\n ) {\n # inputs\n plan <- match.arg(plan)\n interest <- 0\n repaye_rate <- 0.1\n\n df <- vector(\"list\", years)\n\n # compute loan payments over time\n for (yr in seq_len(years)) {\n # calculate payment per month\n ppm <- compute_ppm(income, family_size, repaye_rate)\n\n # payment_per_year - interest_accrued\n net_payment <- compute_net_payment(balance, rate, ppm)\n\n # subsidized interest\n if (plan == \"repaye\") {\n govt_help <- ifelse(subsidized*(yr <= 3), 1, 0.5)\n } else {\n govt_help <- 0\n }\n subsidized_interest <- compute_subsidized_interest(net_payment, govt_help)\n\n # new balances. pay off the interest first!\n if (net_payment < 0) {\n # interest more than payment\n payment_to_interest <- -subsidized_interest\n payment_to_balance <- 0\n } else {\n # payment more than interest\n payment_to_interest <- min(interest, net_payment)\n payment_to_balance <- net_payment - payment_to_interest\n }\n\n new_balance <- balance - payment_to_balance\n new_interest <- interest - payment_to_interest\n\n # update list\n df[[yr]] <- tibble::tibble(\n year = yr,\n principal_before = balance,\n interest_per_month = balance*rate/12,\n payment_per_month = ppm,\n govt_help = govt_help,\n principal_after = new_balance,\n interest_accrued = new_interest\n )\n\n # update balance\n balance <- new_balance\n interest <- new_interest\n\n # income increase causes payment increase\n income <- income*(1 + income_increase)\n }\n\n # bind list\n dplyr::bind_rows(df) %>%\n dplyr::filter(!!rlang::sym(\"principal_before\") >= 0) %>%\n dplyr::mutate(principal_after = pmax(0, !!rlang::sym(\"principal_after\")))\n}\n\n#' Compute the net yearly payment\n#'\n#' Subracts student payment from accrued interest\n#' @param balance current balance\n#' @param rate interest rate\n#' @param ppm payment per month\n#'\n#' @keywords internal\ncompute_net_payment <- function(balance, rate, ppm) {\n 12*ppm - balance*rate\n}\n\n#' Compute the subsidized interest\n#'\n#' Interest may be subsidized depending on your repayment plan.\n#'\n#' @param net_payment net payment\n#' @param govt_help percentage of subsidzation the government will provide\ncompute_subsidized_interest <- function(net_payment, govt_help) {\n if (net_payment >= 0) return(0)\n -net_payment*(1 - govt_help)\n}\n\ncompute_poverty_line <- function(family_size) {\n n <- nrow(poverty)\n if (family_size <= n) {\n poverty[[\"poverty_line\"]][family_size]\n } else {\n poverty[[\"poverty_line\"]][n] + 4320*(family_size - n)\n }\n}\n\n#' Payments per month\n#'\n#' @param income adjusted gross income\n#' @param family_size members in family including self, spouse, and dependents\n#' @param repaye_rate REPAYE max payment rate is 10% of adjusted income\ncompute_ppm <- function(income, family_size, repaye_rate = 0.1) {\n poverty_line <- compute_poverty_line(family_size)\n ppm <- (income - 1.5*poverty_line)*repaye_rate/12\n max(ppm, 0)\n}\n\n", "meta": {"hexsha": "11b7a7135fb4c2c91e73531b2dde04d65fbcab78", "size": 3669, "ext": "r", "lang": "R", "max_stars_repo_path": "R/payments.r", "max_stars_repo_name": "zamorarr/loanr", "max_stars_repo_head_hexsha": "b612b447c5444f5f42f1498059822313683fb7b0", "max_stars_repo_licenses": ["MIT"], "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/payments.r", "max_issues_repo_name": "zamorarr/loanr", "max_issues_repo_head_hexsha": "b612b447c5444f5f42f1498059822313683fb7b0", "max_issues_repo_licenses": ["MIT"], "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/payments.r", "max_forks_repo_name": "zamorarr/loanr", "max_forks_repo_head_hexsha": "b612b447c5444f5f42f1498059822313683fb7b0", "max_forks_repo_licenses": ["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.0737704918, "max_line_length": 80, "alphanum_fraction": 0.6683019896, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5901075811417645}} {"text": "\nmetrop.rwalker.proposal.fun <- function(theta){\n # finding the right scaling factor is more of an art than science\n # or try and error to look for the best fit on acceptance %, ideally .234\n # good starting point 2.38/sqrt(N.dimensions)\n # looking to replace rnorm with multivariate version mvrnorm ? \n\n n.theta <- length(theta)\n scale.sd <- round(2.38/sqrt(n.theta), 2)\n return(rnorm(n=n.theta, mean=theta, sd=rep(scale.sd, n.theta)))\n}\n\nhamiltonian.proposal.fun <- function(theta){\n #forget it.. it is a good theory\n # H(q, p) = U(q) + K(p) .. the potential and kinetic energy\n # simulate data by the way of the physical system moves than a random walk\n # faster convergence\n # more parameters to worry: epsilon, M, t, L\n # not to mention the change of proposal..\n # U(q) = -log[pi(q) * L(q|D)]\n # hmc proposal and actual simulation is tight up\n # condition:\n # runif(1) < exp(-U(q*)+U(q)-K(p*)+K(p))\n # no to mention the painful gradient (log likelihood function)\n # there are research work being done on the gradient free hamiltonian\n # don't quote on me, it is still an exciting new area\n #\n # good read, I'll leave the work for others :)\n # indeed, please refer to hmc.r\n #\n # for now, it does exactly the random walk if hmc = TRUE\n\n return(theta+rnorm(length(theta), sd=2.38))\n}\n\n# Metroplis Hasting Monte Carlo Simulation\n# currently not support thinning nor multiple chains\n# fun .......... the logged posterior sampling function\n# theta.init ... initial parameter(s) value\n# nmc .......... number of iterations for the chain\n# nbi .......... number of burn-ins\n# hmc .......... reserved for future Hamiltonian or RWHMC implementation\nmcmc <- function(fun, theta.init, nmc, nbi, hmc = FALSE, ...) {\n\n iterations <- nmc + nbi\n chain <- array(dim = c(iterations, length(theta.init)))\n chain[1, ] <- theta.init\n\n # choose the proposal function\n if(hmc){\n propose <- hamiltonian.proposal.fun #hamiltonian\n }else{\n propose <- metrop.rwalker.proposal.fun #metroplis\n }\n\n for(i in 1:(iterations-1)) {\n proposal <- propose(chain[i, ])\n p <- exp(fun(proposal, ...) - fun(chain[i, ], ...))\n\n if(runif(1) < p) {\n chain[i+1, ] <- proposal #accept\n }else{\n chain[i+1, ] <- chain[i, ] #reject\n }\n }\n\n return(chain[-(1:nbi), ])\n}\n", "meta": {"hexsha": "f7711aa48728ec8b5dfc650fe8f3546136be4d01", "size": 2325, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mcmc.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/mcmc.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/mcmc.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": 33.6956521739, "max_line_length": 76, "alphanum_fraction": 0.6455913978, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.590098267680031}} {"text": "DySyn <- function(ts, measure){\n \n MF <- seq(0.1,0.9,0.2)\n result <- NULL\n rD <- NULL\n \n for(ti in 1:length(MF)){\n scores <- MoSS(1000, 0.5, MF[ti])\n test.p <- scores[scores[,3]==1,1]\n test.n <- scores[scores[,3]==2,1]\n \n ifelse(measure==\"sord\", rQnt <- DySyn_SORD(test.p, test.n, ts), rQnt <- DySyn_DyS(test.p, test.n, ts, measure))\n\n rD <- c(rD, rQnt[[2]])\n result <- c(result, rQnt[[1]][1])\n \n }\n result <- round(result[which.min(rD)],2)\n result <- c(result, 1-result)\n return(list(result, min(rD)))\n}\n\nDySyn_DyS <- function(p.score, n.score, test, measure=\"hellinger\"){\n \n alpha <- seq(0,1,by=0.01)\n \n b_sizes <- c(seq(2,20,2),30)\n \n result <- NULL\n \n for(hi in 1:length(b_sizes)){\n \n Sty_1 <- getHist(p.score, b_sizes[hi])\n Sty_2 <- getHist(n.score, b_sizes[hi])\n Uy <- getHist(test, b_sizes[hi])\n \n vDist <- NULL\n vDistAll <- NULL\n \n f <- function(x){\n return(DySyn_distance(rbind((Sty_1*x)+ (Sty_2*(1-x)), Uy), method = measure))\n }\n \n result <- c(result, TernarySearch(0, 1, f, 1e-2))\n vDistAll <- c(vDistAll, f(result))\n } \n \n result <- median(result)\n result <- c(result, 1 - result)\n names(result) <- c(\"1\", \"2\")\n return(list(round(result,2),vDistAll[order(vDistAll)[1]]))\n \n}\n\nPNTDiff <- function(pos, neg, test, pos_prop){\n p_w <- pos_prop / length(pos)\n n_w <- (1 - pos_prop) / length(neg)\n t_w <- -1 / length(test) # repare no -1 (menos um) !!\n \n \n \n # Cria listas com (valor da observacao), peso [fixo pra cada lista])\n #p <- list(map(lambda x: (x, p_w), pos))\n p <- cbind(pos, rep(p_w, length(pos)))\n #n <- list(map(lambda x: (x, n_w), neg))\n n <- cbind(neg, rep(n_w, length(neg)))\n #t <- list(map(lambda x: (x, t_w), test))\n t <- cbind(test, rep(t_w, length(test)))\n \n \n # Concatena numa lista soh e ordena pelos valores de obervacao\n #v <- sorted(p + n + t, key = lambda x: x[0])\n v <- rbind(p, n, t)\n v <- v[order(v[,1]),]\n \n \n \n #acc <- v[0][1] # inicializa acc com o peso do primeiro elemento\n acc <- v[1,2]\n total_cost <- 0\n \n # comeca a iterar no SEGUNDO elemento (python eh 0-indexado)\n for( i in 2:nrow(v)){\n cost_mul <- v[i,1] - v[i - 1, 1] # custo da movimentacao\n total_cost <- total_cost + abs(cost_mul * acc) #movimenta o que esta acumulado\n acc <- acc + v[i,2]\n }\n \n return(total_cost)\n}\n\n\nDySyn_SORD <- function(p.score, n.score, test){\n \n alpha <- seq(0,1,by=0.01)\n vDist <- NULL\n vDistAll <- NULL\n f <- function(x){\n return(PNTDiff(p.score, n.score, test, x))\n }\n \n result <- TernarySearch(0, 1, f, 1e-5)\n vDist <- f(result)\n \n result <- c(result, 1 - result)\n names(result) <- c(\"1\", \"2\")\n return(list(round(result,2), vDist))\n \n}\n\n\n", "meta": {"hexsha": "fb92e4f77f377b09637a1c644ef3af50b045813f", "size": 2723, "ext": "r", "lang": "R", "max_stars_repo_path": "proposals/DySyn_method.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/DySyn_method.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/DySyn_method.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.3125, "max_line_length": 115, "alphanum_fraction": 0.5714285714, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5900973756788783}} {"text": "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n### fixed seed to allow repeatable results\nset.seed(63)\n\n### Original driver data. This will force our final results to be constrained\n### to a 3-dimensional manifold\ndim = 4\nhidden = 10\nembed = 15\nraw.train = matrix(rnorm(dim*10000), ncol=dim, nrow=10000)\nraw.test = matrix(rnorm(dim*10000), ncol=dim)\n\n### Transformation to final data. This is a simple neural network kind of thing.\nw1 = matrix(rnorm(dim*hidden), nrow=dim)\nw2 = matrix(rnorm(hidden*embed), nrow=hidden)\n\nsig = function(x) {1/(1+exp(-x)) - 0.5}\nxform = function(input, w1, w2) {\n sig(input %*% w1) %*% w2\n}\n\n### The final data is 8 dimensional, but only looks complicated\ntrain.data = xform(raw.train, w1, w2)\ntest.data = xform(raw.test, w1, w2)\n\n### The encoder simply finds the nearest centroids\nclosest = function(v, k) {\n ## This is same as (centers - v)^2 but works with matrix centers and vector v\n ## numerical stability is probably poor\n distances = rowSums(k$centers^2) + sum(v^2) - 2 * k$centers %*% v\n close = min(distances)\n which(distances == close)\n}\n\nencode = function(data, k) {\n apply(data, 1, function(v){closest(v, k)})\n}\n\ndecode = function(kx, k) {\n as.matrix(k$centers[kx,])\n}\n\nreconstruction.error = function(data, k) {\n mean(sqrt(rowSums((data - decode(encode(data, k), k))^2)))\n}\n\nk.10 = kmeans(train.data, centers=10, nstart=10, iter.max=50)\nx.10 = reconstruction.error(train.data, k.10)\ny.10 = reconstruction.error(test.data, k.10)\nprint(10)\n\nk.20 = kmeans(train.data, centers=20, nstart=10, iter.max=50)\nx.20 = reconstruction.error(train.data, k.20)\ny.20 = reconstruction.error(test.data, k.20)\nprint(20)\n\nk.50 = kmeans(train.data, centers=50, nstart=10, iter.max=50)\nx.50 = reconstruction.error(train.data, k.50)\ny.50 = reconstruction.error(test.data, k.50)\nprint(50)\n\nk.100 = kmeans(train.data, centers=100, nstart=10, iter.max=50)\nx.100 = reconstruction.error(train.data, k.100)\ny.100 = reconstruction.error(test.data, k.100)\nprint(100)\n\nk.200 = kmeans(train.data, centers=200, nstart=10, iter.max=50)\nx.200 = reconstruction.error(train.data, k.200)\ny.200 = reconstruction.error(test.data, k.200)\nprint(200)\n\nk.500 = kmeans(train.data, centers=500, nstart=10, iter.max=50)\nx.500 = reconstruction.error(train.data, k.500)\ny.500 = reconstruction.error(test.data, k.500)\nprint(500)\n\nk.1000 = kmeans(train.data, centers=1000, nstart=5, iter.max=50)\nx.1000 = reconstruction.error(train.data, k.1000)\ny.1000 = reconstruction.error(test.data, k.1000)\nprint(1000)\n\nk.2000 = kmeans(train.data, centers=2000, nstart=3, iter.max=50)\nx.2000 = reconstruction.error(train.data, k.2000)\ny.2000 = reconstruction.error(test.data, k.2000)\nprint(2000)\n\n\npoints.fig = function() {\n plot(c(10,20,50,100,200,500,1000, 2000), \n c(x.10, x.20, x.50, x.100, x.200, x.500, x.1000, x.2000),\n ylab=\"Error\", xlab=\"Centroids\", type='b',\n ylim=c(0,2), lwd=2,\n main=\"Reconstruction error for random points\"\n )\n\n lines(c(10,20,50,100,200,500,1000,2000), \n c(y.10, y.20, y.50, y.100, y.200, y.500, y.1000, y.2000),\n col='red', lwd=2, type='b')\n\n legend(1000, 1.9, legend=c(\"Training data\", \"Held-out data\"), col=c(\"black\", \"red\"), pch=21, lwd=2)\n}\n\ncube.root.fig = function() {\n x = data.frame(\n k=c(10, 20, 50, 100, 200, 500, 1000, 2000),\n test=c(y.10, y.20, y.50, y.100, y.200, y.500, y.1000, y.2000),\n train=c(x.10, x.20, x.50, x.100, x.200, x.500, x.1000, x.2000))\n x$rootK = x$k^(1/3)\n x$inv.train = 1/x$train\n x$inv.test = 1/x$test\n m.train = lm(inv.train ~ rootK, x)\n m.test = lm(inv.test ~ rootK, x)\n\n plot(train~k,x,type='b', xlab=\"k\", ylab=\"Error\", main=\"Error is approximately cube root of k\",\n lwd=2, ylim=c(0,2))\n lines(test~k,x,type='b', col='darkgray', lwd=2)\n lines(x$k,1/predict(m.train, newdata=data.frame(rootK=exp(log(x$k)*0.33333))),\n lwd=2, lty=4, col='red')\n lines(x$k,1/predict(m.test, newdata=data.frame(rootK=exp(log(x$k)*0.33333))),\n lwd=2, lty=4, col='red')\n legend(1000, 1.8, legend=c(\"Training data\", \"Test data\", \"Cube root model\"), col=c(\"black\", \"darkgray\", \"red\"), pch=21, lwd=2)\n}\n\npdf(file=\"points.pdf\", width=5, height=5)\npoints.fig()\ndev.off()\n\npng(file=\"images/points.png\", width=400, height=400, pointsize=12)\npoints.fig()\ndev.off()\n\npdf(file=\"cube-root.pdf\", width=5, height=5)\ncube.root.fig()\ndev.off()\n\npng(file=\"images/cube-root.png\", width=400, height=400, pointsize=12)\ncube.root.fig()\ndev.off()\n\n", "meta": {"hexsha": "af25b22aa0eb8f5e09fdd8a5edf77e3e6e91ff6c", "size": 5266, "ext": "r", "lang": "R", "max_stars_repo_path": "clustering.r", "max_stars_repo_name": "tdunning/k-means-auto-encoder", "max_stars_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-06-12T11:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T16:48:03.000Z", "max_issues_repo_path": "clustering.r", "max_issues_repo_name": "tdunning/k-means-auto-encoder", "max_issues_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-10T20:10:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-16T12:13:50.000Z", "max_forks_repo_path": "clustering.r", "max_forks_repo_name": "tdunning/k-means-auto-encoder", "max_forks_repo_head_hexsha": "2359ebf62b0b4153d47aed394cd9496474d9f3f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T14:20:04.000Z", "avg_line_length": 34.1948051948, "max_line_length": 130, "alphanum_fraction": 0.6691986327, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5900886350805724}} {"text": "##Ядерные функции. По умолчанию используется первая.\nnuclearFunction<-function(z, x = 1, r = 2, s = 3) {\n if (x == 1) {\n p<-(1-(z^r))^s\n }\n else if (x == 2) {\n p<-exp(-s*(z^r))\n }\n else if (x == 3) {\n p<-1/(s*(z^r)+1)\n } \n else if (x == 4) {\n p<-1/(z^s)\n }\n else \n p <- 0\n return(p)\n}\n\nf<- function(x, y)\n{\n z<-function(x)\n return(-(1/((x-1)^2 + 0.2))-(1/(2*(x-2)^2 + 0.15)) -(1/(3*(x-3)^2 + 0.3)))\n return(z(x)+z(y))\n}\n\nRuban <- function(x, deltaX, f, lower, upper, n = 500, e = 0.001, M = 1000, y = 1, q = 2, numberOfNuclearFunc = 1, r = 2, s = 100) {\n if (length(x)!= length(deltaX) || length(x)!= length(lower) || length(x)!= length(upper))\n stop(\"Ошибка, не соблюдение размерности у входящих параметров (x, deltaX, upper, lower)!\")\n if (n<0)\n stop(\"Ошибка, количество пробных точек должно быть больше 0!\")\n if (e<0)\n stop(\"Ошибка, константа точности не должна быть меньше 0!\")\n if (M<0)\n stop(\"Ошибка, максимальное количество итераций не должно быть меньше 0!\")\n if (y<0)\n stop(\"Ошибка, (y) не должен быть меньше 0!\")\n k<-1 ##Будем использовать для проверки первого критерия останова - превышения числа итераций\n testX<-matrix(0, n, length(x)) ## В матрицу будут записываться пробные точки. \n ## Где n - количество пробных точек, \n ## length(x) - количество координатых направлений\n functionValues<-rep(0, n) ## А эта матрица содержит значения функции в пробных точках\n uValues<-matrix(0, n, length(x)) ##В этой матрице будут храниться значения u для генерации пробных точек\n p<-rep(0, n) ##Ядра \n pNorm<-rep(0, n) ##нормированные ядра\n allX<-matrix(0, M, length(x)) ##Сюда записываем все X\n allX[1,]<-x\n allResults<-f(x[1],x[2]) ##Сюда записываем все результаты. Если число циклов превысит M, то мы выберем из всех результатов наименьший\n while(kupper[1])\n x[1]<-upper[1]\n if (x[2]>upper[2])\n x[2]<-upper[2]\n for (i in 1:length(x))\n deltaX[i]<-y*deltaX[i] * ((sum(sapply(1:n, function(x){(abs(uValues[x,i])^(q)) * pNorm[x]})))^(1/q))\n cat(\"deltaX=\", deltaX, \"\\n\")\n k<-k+1 ##Увеличиваем счетчик итераций\n allX[k,]<-x\n allResults<-c(allResults,f(x[1],x[2]))\n flag <- (max(deltaX) <= e)\n if (flag == TRUE)\n break\n #if (sqrt(sum(deltaX^2)) < e) \n # break\n }\n cat(\"Сделано шагов: \", k, \"\\n\")\n return(allX[which.min(allResults),]) \n}", "meta": {"hexsha": "316cbf80f9ec143347140dc2d9f6d5cc065525dc", "size": 3758, "ext": "r", "lang": "R", "max_stars_repo_path": "algorithm.r", "max_stars_repo_name": "holycb/ruban-alg", "max_stars_repo_head_hexsha": "cfe35fcf3fd02fe0a1214d3f85a1ee4c403702d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithm.r", "max_issues_repo_name": "holycb/ruban-alg", "max_issues_repo_head_hexsha": "cfe35fcf3fd02fe0a1214d3f85a1ee4c403702d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm.r", "max_forks_repo_name": "holycb/ruban-alg", "max_forks_repo_head_hexsha": "cfe35fcf3fd02fe0a1214d3f85a1ee4c403702d5", "max_forks_repo_licenses": ["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.5578947368, "max_line_length": 135, "alphanum_fraction": 0.5973922299, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.58995547534862}} {"text": "# 4. faza: Analiza podatkov\nsource('lib/libraries.r', encoding = 'UTF-8')\n\n#Napoved prirastka za države z največjim in najnižjim BDP\n\nnajrazvitejse <- neto_tabela %>% filter(Država %in% najvecji.bdp$Država)\nnajmanj_razvite <- neto_tabela %>% filter(Država %in% najnizji.bdp$Država)\nnajmanj_razvite[is.na(najmanj_razvite)] <- 0\n\nnajrazvitejse <- najrazvitejse %>% group_by(Leto) %>% summarise(Neto = sum(Neto))\nnajmanj_razvite <- najmanj_razvite %>% group_by(Leto) %>% summarise(Neto = sum(Neto))\n\n\nfit <- lm(data=najrazvitejse, Neto ~ Leto +I(Leto^2))\nleta <- data.frame(Leto=seq(2011, 2021))\npredict(fit, leta)\nnapoved.prirastka1 <- mutate(leta, Neto=predict(fit, leta))\n\npodatki <- lm(data=najmanj_razvite, Neto ~ Leto)\ncas <- data.frame(Leto=seq(2011, 2021))\npredict(podatki, cas)\nnapoved.prirastka2 <- mutate(cas, Neto=predict(podatki, cas))\n\ngraf.napovedi.prirastka1 <- ggplot(data=najrazvitejse, aes(x=Leto, y=Neto/1000)) + \n geom_smooth(method = \"lm\", formula = y ~ x + I(x^2), fullrange = TRUE) +\n geom_point(data=napoved.prirastka1 %>% filter(Leto>2016)) +\n labs(title = 'Napoved prirastka za države z največjim BDP') +\n geom_point(color = 'red') + \n ylab('Neto prirastek v tisočih')\n\n\ngraf.napovedi.prirastka2 <- ggplot(data=najmanj_razvite, aes(x=Leto, y=Neto/1000)) + \n geom_smooth(method = \"lm\", formula = y ~ x , fullrange = TRUE) +\n geom_point(data=napoved.prirastka2 %>% filter(Leto>2016)) +\n labs(title = 'Napoved prirastka za države z najmanjšim BDP') +\n geom_point(color='red') +\n ylab('Neto prirastek v tisočih')\n \n\n\n", "meta": {"hexsha": "b4c90447071332d7a605e99dbe087423332811af", "size": 1548, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "JernejcicZan/APPR-2018-19", "max_stars_repo_head_hexsha": "685ea89712c9da81893ce16f839250fabb1930db", "max_stars_repo_licenses": ["MIT"], "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": "JernejcicZan/APPR-2018-19", "max_issues_repo_head_hexsha": "685ea89712c9da81893ce16f839250fabb1930db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-08T10:47:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-07T15:01:19.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "JernejcicZan/APPR-2018-19", "max_forks_repo_head_hexsha": "685ea89712c9da81893ce16f839250fabb1930db", "max_forks_repo_licenses": ["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.756097561, "max_line_length": 85, "alphanum_fraction": 0.7080103359, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5899430005961911}} {"text": "#######################################################################################\n# Impact of Gestational Diabetes Mellitus Screening Strategies on Perinatal Outcomes: \n# a Simulation Study\n# Coded by: Isaias Prestes; reviewed by Maicon Falavigna\n# Performed on R version 2.11.1\n# Packages required: hdrcde, boa \n# Date: 01/06/12\n#######################################################################################\n\n# Simulation study for screening for gestational diabetes WHO\n\n# Settings\nn <- 1000000 ;\nalfa <- 0.05\n\n# The Beta distribution with parameters shape1 = a and shape2 = b has density\n#\n# G(a+b)/(G(a)G(b))x^(a-1)(1-x)^(b-1)\n#\n# for a > 0, b > 0 and 0 = x = 1 where the boundary values at x=0 or x=1 are defined as by continuity (as limits). \n# The mean is a/(a+b) and the variance is ab/((a+b)^2 (a+b+1)).\n\n# Given a and b, return a array with mean, variance, deviation, lower endpoint and upper endpoint of the 100(1-alfa)% confidence interval for Beta distribution.\nbeta.parametros <- function(a, b, alfa, digits = 5) {\n\tmedia <- a / (a+b)\n\tvariancia <- (a * b)/ ( (a+b)^2 * (a+b+1) )\n\tliminf <- qbeta(alfa/2, a, b)\n\tlimsup <- qbeta(1 - alfa/2, a, b)\n\treturn( round( c(\"Mean\"=media,\"Var\"=variancia,\"SD\"=variancia^.5, \"LL\"=liminf, \"UL\"=limsup) , digits=5) )\n}\n# Example :\nbeta.parametros(3, 6, alfa)\n\n# Set RNG seed\nset.seed(37589411)\n\n# Values for PWHO\n# PWHO <- seq(0.05,0.15,0.01)\nPWHO <- 0.05\n\n# Simulated parameters values\n\n# LGA Birth (LGA)\nLGA_Iwho_negative <- rbeta(n, 1.5*900, 1.5*9100 ) ; c <- 1.5; beta.parametros(c*900, 9100*c, alfa)\nLGA_logRRwho <- rnorm(n, 0.4256, 0.0494) ;\t\t# Distribution for log(RR)\nLGA_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # approximated solution\nLGA_logRPiadpsg <- rnorm(n, 0.4055, 0.0730) ;\t\t# Distribution for log(RP)\nLGA_logRRtreatment <- rnorm(n, -0.6095, 0.1245) ;\t# Distribution for log(RR)\nLGA_logRRiadpsg <- rnorm(n, 0.5503, 0.1558) ;\t\t# Distribution for log(RR)\n\n# Preeclampsia (PE)\nPE_Iwho_negative <- rbeta(n, 22.5, 477.5 ) ; c <- 0.5; beta.parametros(c*45, c*955, alfa)\nPE_logRRwho <- rnorm(n, 0.5260, 0.1288) ;\t\t# Distribution for log(RR)\nPE_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # approximated solution\nPE_logRPiadpsg <- rnorm(n, 0.4055, 0.0730) ;\t\t# Distribution for log(RP)\nPE_logRRtreatment <- rnorm(n, -0.4903, 0.1413) ;\t# Distribution for log(RR)\nPE_logRRiadpsg <- rnorm(n, 0.5374, 0.1108) ;\t\t# Distribution for log(RR)\n\n# Caesarean section (CS)\nCS_Iwho_negative <- rbeta(n, 11.7475, 51.7525 ) ; beta.parametros(11.7475, 51.7525, alfa) \nCS_logRRwho <- rnorm(n, 0.3144, 0.0508) ;\t\t# Distribution for log(RR)\nCS_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # approximated solution\nCS_logRPiadpsg <- rnorm(n, 0.4055, 0.0730) ;\t\t# Distribution for log(RP)\nCS_logRRtreatment <- rnorm(n, -0.1100, 0.0797) ;\t\t# Distribution for log(RR)\nCS_logRRiadpsg <- rnorm(n, 0.2086, 0.1035) ;\t\t# Distribution for log(RR)\n\n# Set simulated block\nset.idiaf <- function( PWHO, Iwho_negative, logRRwho, Ptreatment, logRRtreatment, logRPiadpsg, logRRiadpsg) {\n\tIDIAF <- ( ( PWHO * Iwho_negative * exp(logRRwho) ) ) + ( ( 1 - PWHO ) * Iwho_negative ) / ( (1 - ( PWHO * exp(logRPiadpsg) ) ) + ( exp(logRRiadpsg) * PWHO * exp(logRPiadpsg) ) )\n\treturn(IDIAF)\n}\n\n# Functions for model simulation\nsimula.nao.rastrear <- function ( n , PWHO, Iwho_negative, logRRwho, Ptreatment, logRRtreatment, logRPiadpsg, logRRiadpsg) {\n\tIwho_positive <- Iwho_negative * exp(logRRwho) # Iwho_positive = Iwho_negative * RRwho\n\t\n\tans <- \t( \n\t\t\t\t( PWHO * Iwho_positive ) + ( ( 1 - PWHO ) * Iwho_negative )\n\t\t\t)\n\n\treturn(ans)\n}\n\nsimula.who <- function ( n , PWHO, Iwho_negative, logRRwho, Ptreatment, logRRtreatment, logRPiadpsg, logRRiadpsg) {\n\tIwho_positive <- Iwho_negative * exp(logRRwho)\n\t\n\tans <- \t( \n\t\t\t\t( ( 1 - PWHO ) * Iwho_negative ) +\n\t\t\t\t( PWHO * ( 1 - Ptreatment ) * Iwho_positive ) + \n\t\t\t\t( PWHO * Ptreatment * exp(logRRtreatment) * Iwho_positive )\n\t\t\t)\n\n\treturn(ans)\n}\n\nsimula.iadpsg <- function ( n , PWHO, Iwho_negative, logRRwho, Ptreatment, logRRtreatment, logRPiadpsg, logRRiadpsg) {\n\n\tPiadpsg <- PWHO * exp(logRPiadpsg)\t# Piadpsg = Pwho * PRiadpsg\n\n\tIiadpsg_negative <- ( ( PWHO * Iwho_negative * exp(logRRwho) ) +\n\t\t\t\t\t\t( ( 1 - PWHO) * Iwho_negative ) ) / ( ( ( 1 - (PWHO * exp(logRPiadpsg) ) ) ) + \n\t\t\t\t\t\t( PWHO * exp(logRPiadpsg) * exp(logRRiadpsg) ) ) \n\t\t\t\t\t\t\n\tIiadpsg_positive <- Iiadpsg_negative * exp(logRRiadpsg)\n\n\tans <- \t( \n\t\t\t\t( ( 1 - Piadpsg ) * Iiadpsg_negative ) +\n\t\t\t\t( Piadpsg * Iiadpsg_positive * Ptreatment * exp(logRRtreatment) ) + \n\t\t\t\t( Piadpsg * Iiadpsg_positive * ( 1 - Ptreatment ) )\n\t\t\t)\n\n\treturn(ans)\n}\n\n# Looping PWHO values\ndatasummary <- array(,10)\ndatasummary.diff <- array(,10)\ndatasummary.table.diff <- array(,3)\n\nnames(datasummary) <- c(\"PWHO\", \"Strategy\", \"Min.\", \"1st Qu.\", \"Median\", \"Mean\", \"3rd Qu.\", \"Max.\")\nnames(datasummary.diff) <- c(\"PWHO\", \"Strategy\", \"Min.\", \"1st Qu.\", \"Median\", \"Mean\", \"3rd Qu.\", \"Max.\")\n\nfor ( i in PWHO ) {\n\tarrayPWHO <- rep(i, n) \n\t# Compute values for each screening strategies\n\tresultados.IADPSG.LGA <- simula.iadpsg( n , arrayPWHO, LGA_Iwho_negative, LGA_logRRwho, LGA_Ptreatment, LGA_logRRtreatment, LGA_logRPiadpsg, LGA_logRRiadpsg)\n\tresultados.IADPSG.PE <- simula.iadpsg( n , arrayPWHO, PE_Iwho_negative, PE_logRRwho, PE_Ptreatment, PE_logRRtreatment, PE_logRPiadpsg, PE_logRRiadpsg)\n\tresultados.IADPSG.CS <- simula.iadpsg( n , arrayPWHO, CS_Iwho_negative, CS_logRRwho, CS_Ptreatment, CS_logRRtreatment, CS_logRPiadpsg, CS_logRRiadpsg)\n\t\n\tresultados.NR.LGA <- simula.nao.rastrear( n , arrayPWHO, LGA_Iwho_negative, LGA_logRRwho, LGA_Ptreatment, LGA_logRRtreatment, LGA_logRPiadpsg, LGA_logRRiadpsg)\n\tresultados.NR.PE <- simula.nao.rastrear( n , arrayPWHO, PE_Iwho_negative, PE_logRRwho, PE_Ptreatment, PE_logRRtreatment, PE_logRPiadpsg, PE_logRRiadpsg)\n\tresultados.NR.CS <- simula.nao.rastrear( n , arrayPWHO, CS_Iwho_negative, CS_logRRwho, CS_Ptreatment, CS_logRRtreatment, CS_logRPiadpsg, CS_logRRiadpsg)\n\t\n\tresultados.WHO.LGA <- simula.who( n , arrayPWHO, LGA_Iwho_negative, LGA_logRRwho, LGA_Ptreatment, LGA_logRRtreatment, LGA_logRPiadpsg, LGA_logRRiadpsg)\n\tresultados.WHO.PE <- simula.who( n , arrayPWHO, PE_Iwho_negative, PE_logRRwho, PE_Ptreatment, PE_logRRtreatment, PE_logRPiadpsg, PE_logRRiadpsg)\n\tresultados.WHO.CS <- simula.who( n , arrayPWHO, CS_Iwho_negative, CS_logRRwho, CS_Ptreatment, CS_logRRtreatment, CS_logRPiadpsg, CS_logRRiadpsg)\n\n\tresultado.final <- data.frame(\n\t\t\"PWHO\" = arrayPWHO,\n\t\t\"NR.LGA\" = resultados.NR.LGA,\n\t\t\"NR.PE\" = resultados.NR.PE,\n\t\t\"NR.CS\" = resultados.NR.CS,\n\t\t\"WHO.LGA\" = resultados.WHO.LGA,\n\t\t\"WHO.PE\" = resultados.WHO.PE,\n\t\t\"WHO.CS\" = resultados.WHO.CS,\n\t\t\"IADPSG.LGA\" = resultados.IADPSG.LGA,\n\t\t\"IADPSG.PE\" = resultados.IADPSG.PE,\n\t\t\"IADPSG.CS\" = resultados.IADPSG.CS\n\t\t)\n\t\n\twrite.csv2( resultado.final , paste(\"table_data_PWHO_\", i,\".csv\", sep=\"\") )\n\n\t# Compute differences\n\tDelta.NR.WHO.LGA <- resultados.NR.LGA - resultados.WHO.LGA\n\tDelta.NR.IADPSG.LGA <- resultados.NR.LGA - resultados.IADPSG.LGA\n\tDelta.WHO.IADPSG.LGA <- resultados.WHO.LGA - resultados.IADPSG.LGA\n\t\n\tDelta.NR.WHO.PE <- resultados.NR.PE - resultados.WHO.PE\n\tDelta.NR.IADPSG.PE <- resultados.NR.PE - resultados.IADPSG.PE\n\tDelta.WHO.IADPSG.PE <- resultados.WHO.PE - resultados.IADPSG.PE\n\t\n\tDelta.NR.WHO.CS <- resultados.NR.CS - resultados.WHO.CS\n\tDelta.NR.IADPSG.CS <- resultados.NR.CS - resultados.IADPSG.CS\n\tDelta.WHO.IADPSG.CS <- resultados.WHO.CS - resultados.IADPSG.CS\n\t\n\t# Compute p-values empirical # Pr { standart strategy > alternative strategy }\n\tcomptype <- c(\"NR.WHO.LGA\",\"NR.IADPSG.LGA\",\"WHO.IADPSG.LGA\",\"NR.WHO.PE\",\"NR.IADPSG.PE\",\"WHO.IADPSG.PE\",\"NR.WHO.CS\",\"NR.IADPSG.CS\",\"WHO.IADPSG.CS\")\n\tresultados.pvalue <- array(,0)\n\t\n\tfor (i in comptype) {\n\t\tans <- c(i, eval(parse(text=paste(\"sum( ifelse(Delta.\",i ,\" < 0 , 1, 0) ) / n\",sep=\"\"))) )\n\t\tresultados.pvalue <- rbind(resultados.pvalue, ans)\n\t\tprint( ans )\n\t}\n\t\n\twrite.csv2( resultados.pvalue , paste(\"Summary_pvalues.csv\", sep=\"\"))\n\t\n\t# NNS for screening strategies\n\tNNS.Delta.NR.WHO.LGA <- 1 / Delta.NR.WHO.LGA\n\tNNS.Delta.NR.IADPSG.LGA <- 1 / Delta.NR.IADPSG.LGA\n\tNNS.Delta.WHO.IADPSG.LGA <- 1 / Delta.WHO.IADPSG.LGA\n\t\n\tNNS.Delta.NR.WHO.PE <- 1 / Delta.NR.WHO.PE\n\tNNS.Delta.NR.IADPSG.PE <- 1 / Delta.NR.IADPSG.PE\n\tNNS.Delta.WHO.IADPSG.PE <- 1 / Delta.WHO.IADPSG.PE\n\t\n\tNNS.Delta.NR.WHO.CS <- 1 / Delta.NR.WHO.CS\n\tNNS.Delta.NR.IADPSG.CS <- 1 / Delta.NR.IADPSG.CS\n\tNNS.Delta.WHO.IADPSG.CS <- 1 / Delta.WHO.IADPSG.CS\n\t\n\t# Compute binary variables for proportions\n\tBin.Delta.NR.WHO.LGA <- ifelse(Delta.NR.WHO.LGA > 0, 1, 0)\n\tBin.Delta.NR.IADPSG.LGA <- ifelse(Delta.NR.IADPSG.LGA > 0, 1, 0)\n\tBin.Delta.WHO.IADPSG.LGA <- ifelse(Delta.WHO.IADPSG.LGA > 0, 1, 0)\n\t\n\tBin.Delta.NR.WHO.PE <- ifelse(Delta.NR.WHO.PE > 0, 1, 0)\n\tBin.Delta.NR.IADPSG.PE <- ifelse(Delta.NR.IADPSG.PE > 0, 1, 0)\n\tBin.Delta.WHO.IADPSG.PE <- ifelse(Delta.WHO.IADPSG.PE > 0, 1, 0)\n\t\n\tBin.Delta.NR.WHO.CS <- ifelse(Delta.NR.WHO.CS > 0, 1, 0)\n\tBin.Delta.NR.IADPSG.CS <- ifelse(Delta.NR.IADPSG.CS > 0, 1, 0)\n\tBin.Delta.WHO.IADPSG.CS <- ifelse(Delta.WHO.IADPSG.CS > 0, 1, 0)\n\t\n\tcomptype <- c(\"NR.WHO.LGA\",\"NR.IADPSG.LGA\",\"WHO.IADPSG.LGA\",\"NR.WHO.PE\",\"NR.IADPSG.PE\",\"WHO.IADPSG.PE\",\"NR.WHO.CS\",\"NR.IADPSG.CS\",\"WHO.IADPSG.CS\")\n\n\tfor (i in comptype) {\n\t\tans <- eval(parse(text=paste(\"table(Bin.Delta.\",i,\")\",sep=\"\")))\n\t\tprint(ans)\n\n\t\tif ( length(ans) < 2 ) ans <- c(\"0\" = 0, ans[1] )\n \t\tdatasummary.table.diff <- rbind( datasummary.table.diff, as.array(c(i,ans)) )\n\t}\n\n\t# Save data \n\tdatasummary.table.diff <- datasummary.table.diff[ !is.na(datasummary.table.diff[,1]) ,]\n\t\n\tdatasummary.table.diff <- data.frame( \n\t\t\"Comparação\" = as.character(datasummary.table.diff[,1]),\n\t\t\"Freq 0\" = as.numeric(as.character(datasummary.table.diff[,2])),\n\t\t\"Freq 1\" = as.numeric(as.character(datasummary.table.diff[,3])),\n\t\t\"Fr 0\" = (100 * (as.numeric(as.character(datasummary.table.diff[,2])) / n )),\n\t\t\"Fr 1\" = (100 * (as.numeric(as.character(datasummary.table.diff[,3])) / n ))\n\t\t)\n\t\n\twrite.csv2( datasummary.table.diff , \"Estatísticas_Binarias_Prop_Comp.csv\", row.names=FALSE )\n\t\t\n\tresultado.final.diff <- data.frame(\n\t\t\"PWHO\" = arrayPWHO,\n\t\t\"NR vs WHO - LGA\" = Delta.NR.WHO.LGA,\n\t\t\"NR vs IADPSG - LGA\" = Delta.NR.IADPSG.LGA,\n\t\t\"WHO vs IADPSG - LGA\" = Delta.WHO.IADPSG.LGA,\n\t\t\n\t\t\"NR vs WHO - PE\" = Delta.NR.WHO.PE,\n\t\t\"NR vs IADPSG - PE\" = Delta.NR.IADPSG.PE,\n\t\t\"WHO vs IADPSG - PE\" = Delta.WHO.IADPSG.PE,\n\t\t\n\t\t\"NR vs WHO - CS\" = Delta.NR.WHO.CS,\n\t\t\"NR vs IADPSG - CS\" = Delta.NR.IADPSG.CS,\n\t\t\"WHO vs IADPSG - CS\" = Delta.WHO.IADPSG.CS\n\t\t\n\t\t)\n\t\n\twrite.csv2( resultado.final.diff , paste(\"table_data_Differences_PWHO_\", i,\".csv\", sep=\"\"), row.names=FALSE )\n\t\n\t# Compute summary tables\n\tdatasummary <- rbind( datasummary, c( i, \"NR.LGA\", c(summary(resultado.final$\"NR.LGA\",)) , \n\t\tquantile(resultado.final$\"NR.LGA\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"NR.PE\", c(summary(resultado.final$\"NR.PE\")) , \n\t\tquantile(resultado.final$\"NR.LGA\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"NR.CS\", c(summary(resultado.final$\"NR.CS\")) , \n\t\tquantile(resultado.final$\"NR.LGA\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\t\n\tdatasummary <- rbind( datasummary, c( i, \"WHO.LGA\", c(summary(resultado.final$\"WHO.LGA\")) , \n\t\tquantile(resultado.final$\"WHO.LGA\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"WHO.PE\", c(summary(resultado.final$\"WHO.PE\")) , \n\t\tquantile(resultado.final$\"WHO.PE\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"WHO.CS\", c(summary(resultado.final$\"WHO.CS\")) , \n\t\tquantile(resultado.final$\"WHO.CS\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\t\n\tdatasummary <- rbind( datasummary, c( i, \"IADPSG.LGA\", c(summary(resultado.final$\"IADPSG.LGA\")) , \n\t\tquantile(resultado.final$\"IADPSG.LGA\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"IADPSG.PE\", c(summary(resultado.final$\"IADPSG.PE\")) , \n\t\tquantile(resultado.final$\"IADPSG.PE\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary <- rbind( datasummary, c( i, \"IADPSG.CS\", c(summary(resultado.final$\"IADPSG.CS\")) , \n\t\tquantile(resultado.final$\"IADPSG.CS\", probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\n\t# Compute summary tables for differences\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs WHO - LGA\", c(summary(Delta.NR.WHO.LGA)) , \n\t\tquantile(Delta.NR.WHO.LGA, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs IADPSG - LGA\", c(summary(Delta.NR.IADPSG.LGA)) , \n\t\tquantile(Delta.NR.IADPSG.LGA, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\n\t# Compute summary : screening strategies WHO vs IADPSG for LGA\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"WHO vs IADPSG - LGA\", c(summary(Delta.WHO.IADPSG.LGA)) , \n\t\tquantile(Delta.WHO.IADPSG.LGA, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs WHO - PE\", c(summary(Delta.NR.WHO.PE)) , \n\t\tquantile(Delta.NR.WHO.PE, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs IADPSG - PE\", c(summary(Delta.NR.IADPSG.PE)) , \n\t\tquantile(Delta.NR.IADPSG.PE, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\t\t\n\t# Compute summary : screening strategies WHO vs IADPSG for PE\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"WHO vs IADPSG - PE\", c(summary(Delta.WHO.IADPSG.PE)) , \n\t\tquantile(Delta.WHO.IADPSG.PE, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs WHO - CS\", c(summary(Delta.NR.WHO.CS)) , \n\t\tquantile(Delta.NR.WHO.CS, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"NR vs IADPSG - CS\", c(summary(Delta.NR.IADPSG.CS)) , \n\t\tquantile(Delta.NR.IADPSG.CS, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n\n\t# Compute summary : screening strategies WHO vs IADPSG for CS\n\tdatasummary.diff <- rbind( datasummary.diff, c( i, \"WHO vs IADPSG - CS\", c(summary(Delta.WHO.IADPSG.CS)) , \n\t\tquantile(Delta.WHO.IADPSG.CS, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n}\n\n# Save summary data\ndatasummary <- datasummary[ !is.na(datasummary[,1]) ,]\ndatasummary.diff <- datasummary.diff[ !is.na(datasummary.diff[,1]) ,]\n\ndatasummary <- data.frame(datasummary)\nnames(datasummary) <- c(names(datasummary)[1:(length(names(datasummary))-2)], \npaste(\"Percentil \",round((alfa/2)*100, digits=1),sep=\"\"), paste(\"Percentil \",round((1-alfa/2)*100, digits=1),sep=\"\"))\n\ndatasummary.diff <- data.frame(datasummary.diff)\nnames(datasummary.diff) <- c(names(datasummary.diff)[1:(length(names(datasummary))-2)], \npaste(\"Percentil \",round((alfa/2)*100, digits=1),sep=\"\"), paste(\"Percentil \",round((1-alfa/2)*100, digits=1),sep=\"\"))\n\nwrite.csv2( datasummary , paste(\"Summary_statistics.csv\", sep=\"\"), row.names=FALSE )\nwrite.csv2( datasummary.diff , paste(\"Summary_statistics_for_differences.csv\", sep=\"\"), row.names=FALSE )\n\n# Summary - distribution - Compute the Highest Posterior Density Interval (HPD)\nrequire(hdrcde) \nrequire(boa)\n\ncomptype <- c(\"NR.LGA\",\"NR.PE\",\"NR.CS\",\"WHO.LGA\",\"WHO.PE\",\"WHO.CS\",\"IADPSG.LGA\",\"IADPSG.PE\",\"IADPSG.CS\")\n\nfor (i in comptype) {\n\tprint(paste(\"Computing HPD Interval for \",i,sep=\"\"))\n\t\n\tgraphname <- paste(\"grafico_\",i,\".png\", sep=\"\")\n\tpng(file.path(paste(getwd(),\"//saida\", sep=\"\"),graphname))\n\t\tans <- hdr.den(resultado.final[,i])\n\tdev.off()\n\n\t# Using boa package\n\tans <- boa.hpd(resultado.final[,i], alpha = 0.05)\n\twrite.csv2( ans , paste(\"HPD \",i,\".csv\", sep=\"\"))\n\tprint( ans )\n\t\n}\n\ncomptype <- c(\"NR.WHO.LGA\",\"NR.IADPSG.LGA\",\"WHO.IADPSG.LGA\",\"NR.WHO.PE\",\"NR.IADPSG.PE\",\"WHO.IADPSG.PE\",\"NR.WHO.CS\",\"NR.IADPSG.CS\",\"WHO.IADPSG.CS\")\n\nfor (i in comptype) {\n\tprint(paste(\"Computing HPD Interval for Difference \",i,sep=\"\"))\n\t\n\tgraphname <- paste(\"grafico_IDiff_\",i,\".png\", sep=\"\")\n\tpng(file.path(paste(getwd(),\"//saida\", sep=\"\"),graphname))\n\t\tans <- eval(parse(text=paste(\"hdr.den(Delta.\",i,\")\",sep=\"\")))\n\tdev.off()\n\t\n\t# Using boa package\n\tans <- eval(parse(text=paste(\"boa.hpd(Delta.\",i,\", alpha = 0.05)\",sep=\"\")))\t\n\twrite.csv2( ans , paste(\"HPD Diff \",i,\".csv\", sep=\"\"))\n\tprint( ans )\n\t\n}\n\ncomptype <- c(\"NR.WHO.LGA\",\"NR.IADPSG.LGA\",\"WHO.IADPSG.LGA\",\"NR.WHO.PE\",\"NR.IADPSG.PE\",\"WHO.IADPSG.PE\",\"NR.WHO.CS\",\"NR.IADPSG.CS\",\"WHO.IADPSG.CS\")\n\nfor (i in comptype) {\n\tprint(paste(\"Computing HPD Interval for NNS\",i,sep=\"\"))\n\t\n\tgraphname <- paste(\"grafico_NNS_Diff_\",i,\".png\", sep=\"\")\n\tpng(file.path(paste(getwd(),\"//saida\", sep=\"\"),graphname))\n\t\tans <- eval(parse(text=paste(\"plot(density(NNS.Delta.\",i,\"))\",sep=\"\")))\n\tdev.off()\n\t\n\t# Using boa package\n\tans <- eval(parse(text=paste(\"boa.hpd(NNS.Delta.\",i,\", alpha = 0.05)\",sep=\"\")))\t\n\twrite.csv2( ans , paste(\"HPD Diff \",i,\".csv\", sep=\"\"))\n\tprint( ans )\n\t\n}\n\n###############################\n# Sensitivity analysis - HAPO #\n###############################\n\n# Screening strategies settings\nLGA_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # melhor solução encontrada\nLGA_logRRtreatment <- rnorm(n, -0.6095, 0.1245) ;\t# A distribuição de log(RR)\n\nPE_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # melhor solução encontrada\nPE_logRRtreatment <- rnorm(n, -0.4903, 0.1413) ;\t# A distribuição de log(RR)\n\nCS_Ptreatment <- rbeta(n, 40.5, 4.5 ) ; c <- 4.5; beta.parametros(9*c, 1*c, alfa) # melhor solução encontrada\nCS_logRRtreatment <- rnorm(n, -0.1100, 0.0797) ;\t\t# A distribuição de log(RR)\n\n# Common parameters settings\nPwho_HAPO <- 0.114\nPiadpsg_HAPO <- 0.161\nLGA_Iwhopos_HAPO <- 0.137\nPE_Iwhopos_HAPO <- 0.076\nCS_Iwhopos_HAPO <- 0.244\nLGA_Iiadpsgpos_HAPO <- 0.162\nPE_Iiadpsgpos_HAPO <- 0.091\nCS_Iiadpsgpos_HAPO <- 0.244\n\n# Compute incidence reduction - WHO\nRI_LGA_WHO <- Pwho_HAPO * LGA_Iwhopos_HAPO * LGA_Ptreatment * (1-exp(LGA_logRRtreatment))\nNNS_LGA_WHO <- 1 / RI_LGA_WHO\n\nRI_PE_WHO <- Pwho_HAPO * PE_Iwhopos_HAPO * PE_Ptreatment * (1-exp(PE_logRRtreatment))\nNNS_PE_WHO <- 1 / RI_PE_WHO\n\nRI_CS_WHO <- Pwho_HAPO * CS_Iwhopos_HAPO * CS_Ptreatment * (1-exp(CS_logRRtreatment))\nNNS_CS_WHO <- 1 / RI_CS_WHO\n\n# Compute incidence reduction - IADPSG\nRI_LGA_IADPSG <- Piadpsg_HAPO * LGA_Iiadpsgpos_HAPO * LGA_Ptreatment * (1-exp(LGA_logRRtreatment))\nNNS_LGA_IADPSG <- 1 / RI_LGA_IADPSG \n\nRI_PE_IADPSG <- Piadpsg_HAPO * PE_Iiadpsgpos_HAPO * PE_Ptreatment * (1-exp(PE_logRRtreatment))\nNNS_PE_IADPSG <- 1 / RI_PE_IADPSG \n\nRI_CS_IADPSG <- Piadpsg_HAPO * CS_Iiadpsgpos_HAPO * CS_Ptreatment * (1-exp(CS_logRRtreatment))\nNNS_CS_IADPSG <- 1 / RI_CS_IADPSG \n\n# Save data\nresultado.final.sa <- data.frame(\n\t\"RI_LGA_WHO\" = RI_LGA_WHO,\n\t\"NNS_LGA_WHO\" = NNS_LGA_WHO,\n\t\"RI_PE_WHO\" = RI_PE_WHO,\n\t\"NNS_PE_WHO\" = NNS_PE_WHO,\n\t\"RI_CS_WHO\" = RI_CS_WHO,\n\t\"NNS_CS_WHO\" = NNS_CS_WHO,\n\t\n\t\"RI_LGA_IADPSG\" = RI_LGA_IADPSG,\n\t\"NNS_LGA_IADPSG\" = NNS_LGA_IADPSG,\n\t\"RI_PE_IADPSG\" = RI_PE_IADPSG,\n\t\"NNS_PE_IADPSG\" = NNS_PE_IADPSG,\n\t\"RI_CS_IADPSG\" = RI_CS_IADPSG,\n\t\"NNS_CS_IADPSG\" = NNS_CS_IADPSG\n\t)\n\t\nwrite.csv2( resultado.final.sa , \"table_data_sensitivity analysis.csv\" )\n\n# Compute summary tables\ntabela.resumo.sa <- array(,9)\n\nvet.nomeselementos <- c(\"RI_LGA_WHO\",\"NNS_LGA_WHO\",\"RI_PE_WHO\",\"NNS_PE_WHO\",\"RI_CS_WHO\",\"NNS_CS_WHO\",\n \"RI_LGA_IADPSG\", \"NNS_LGA_IADPSG\", \"RI_PE_IADPSG\", \"NNS_PE_IADPSG\", \"RI_CS_IADPSG\", \"NNS_CS_IADPSG\")\n \nfor (i in vet.nomeselementos) {\n\tans <- eval(parse(text=i))\n\ttabela.resumo.sa <- rbind( tabela.resumo.sa, c( i, summary(ans), quantile(ans, probs = c(alfa/2, 1 - alfa/2), names = FALSE ) ) )\n}\n\t\ntabela.resumo.sa <- tabela.resumo.sa[ !is.na(tabela.resumo.sa[,1]) ,]\n\ntabela.resumo.sa <- data.frame(tabela.resumo.sa)\nnames(tabela.resumo.sa) <- c(\"Estatística/Estratégia\", names(tabela.resumo.sa)[2:(length(names(tabela.resumo.sa))-2)], \npaste(\"Percentil \",round((alfa/2)*100, digits=1),sep=\"\"), paste(\"Percentil \",round((1-alfa/2)*100, digits=1),sep=\"\"))\n\nwrite.csv2( tabela.resumo.sa , paste(\"Summary_AS_HAPO.csv\", sep=\"\"), row.names=FALSE )\n\n# Summary - Highest Posterior Density Interval (HPD)\nvet.nomeselementos1 <- c(\"RI_LGA_WHO\",\"RI_PE_WHO\",\"RI_CS_WHO\",\"RI_LGA_IADPSG\", \"RI_PE_IADPSG\", \"RI_CS_IADPSG\")\nvet.nomeselementos2 <- c(\"NNS_LGA_WHO\", \"NNS_LGA_IADPSG\",\"NNS_PE_WHO\", \"NNS_PE_IADPSG\", \"NNS_CS_WHO\", \"NNS_CS_IADPSG\")\nvet.nomeselementos <- c(vet.nomeselementos1, vet.nomeselementos2)\n\nfor (i in vet.nomeselementos) {\n\tprint(paste(\"HPD Interval for \",i,\" | Sensitivity analysis HAPO\",sep=\"\"))\n\n\tgraphname <- paste(\"grafico_AS_HAPO_\",i,\".png\", sep=\"\")\n\tpng(file.path(paste(getwd(),\"//saida\", sep=\"\"),graphname))\n\t\tans <- eval(parse(text=paste(\"plot(density(\",i,\"))\",sep=\"\")))\n\tdev.off()\n\t\n\tans <- eval(parse(text=paste(\"boa.hpd(\",i,\", alpha = 0.05)\",sep=\"\")))\t\n\twrite.csv2( ans , paste(\"HPD Sensitivity analysis HAPO \",i,\".csv\", sep=\"\"))\n\tprint( ans )\n\t\n}\n\ndev.off()\n\n\n####################\n# End of the syntaxe\n####################\n", "meta": {"hexsha": "7bdcbe5dcce74be797540ee34880aeda9ad4edc7", "size": 21115, "ext": "r", "lang": "R", "max_stars_repo_path": "Simulation Gestational Diabetes WHO/Simulation main.r", "max_stars_repo_name": "isix/Othprojects", "max_stars_repo_head_hexsha": "f53c443e3314a0097f2abd9b872dd45d55e8e275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simulation Gestational Diabetes WHO/Simulation main.r", "max_issues_repo_name": "isix/Othprojects", "max_issues_repo_head_hexsha": "f53c443e3314a0097f2abd9b872dd45d55e8e275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simulation Gestational Diabetes WHO/Simulation main.r", "max_forks_repo_name": "isix/Othprojects", "max_forks_repo_head_hexsha": "f53c443e3314a0097f2abd9b872dd45d55e8e275", "max_forks_repo_licenses": ["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.83014862, "max_line_length": 179, "alphanum_fraction": 0.6657352593, "num_tokens": 8006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5896717818327392}} {"text": "bootstrap_samples = function( expected_I, observed_I, number_samples, window_size=3 , use_wa = FALSE, beta = 0.9){\n \"\n Once the expected_I vector is computed is posible to generate the bootsrapped\n samples for a confidence interval cosntruction.\n \n Parameters\n ----------\n Expected_I : numeric vector\n Number of sintomatic people on a given day (estimated).\n Observed_I : numeric vector\n Number of sintomatic people on a given day.\n number_samples : numeric\n number of samples.\n window_size : numeric\n smoothing factor.\n \n Returns\n -------\n standarized_residual : data_frame\n bootstrapped sample\n \"\n standarized_residual <- standarized_residuals(expected_I, observed_I, window_size)\n samples = list()\n for( i in 1:number_samples)\n {\n sample <- sample(standarized_residual$SR, length(expected_I), replace = TRUE)\n\n if(use_wa){\n DES = 1:length(expected_I)\n temp_de = standarized_residual$DE\n for(j in 2:length(observed_I))\n { \n temp_de[j] = beta*temp_de[j - 1] + (1-beta)*temp_de[j]\n }\n sample = sample*temp_de\n }else{\n sample = sample*standarized_residual$DE\n }\n sample_I = expected_I + sample\n samples <- list.append(samples, i=sample_I)\n }\n df <- data.frame(matrix(unlist(samples), nrow=length(samples), byrow=T))\n return(df)\n}\n\nstandarized_residuals = function(expected_I, observed_I, window_size=3){\n\"\n Residuals normalization for an umbaised bootstrap.\n \n Parameters\n ----------\n Expected_I : numeric vector\n Number of sintomatic people on a given day (estimated).\n Observed_I : numeric vector\n Number of sintomatic people on a given day.\n window_size : numeric\n smoothing factor.\n \n Returns\n -------\n standarized_residual : list\n SR : residuals\n DE : standard deviation\n \"\n half_window_size = floor(window_size / 2)\n standarized_residual <- observed_I - expected_I\n DES = 1:length(expected_I)\n for( i in seq(half_window_size + 1, length(expected_I) - half_window_size + 1))\n {\n indices = (i-half_window_size):(i + half_window_size-1)\n DE = sd(observed_I[indices] - expected_I[indices])\n standarized_residual[i] = standarized_residual[i]/DE \n DES[i] = DE\n }\n\n first_window_idexes = 1:half_window_size\n last_window_indexes = (length(expected_I) - half_window_size + 1):length(expected_I)\n DE_in = sd(observed_I[first_window_idexes] - expected_I[first_window_idexes])\n DE_out = sd(observed_I[last_window_indexes] - expected_I[last_window_indexes])\n DES[first_window_idexes] = DE_in\n DES[last_window_indexes] = DE_out\n standarized_residual[first_window_idexes] = standarized_residual[first_window_idexes]/DE_in\n standarized_residual[last_window_indexes] = standarized_residual[last_window_indexes]/DE_out \n return(list(\"SR\"=standarized_residual, \"DE\"=DES))\n}\n\n\ncompute_variances = function(observed_I, window_size=3){\n \"\n Residuals normalization for an umbaised bootstrap.\n \n Parameters\n ----------\n Expected_I : numeric vector\n Number of sintomatic people on a given day (estimated).\n Observed_I : numeric vector\n Number of sintomatic people on a given day.\n window_size : numeric\n smoothing factor.\n \n Returns\n -------\n standarized_residual : list\n SR : residuals\n DE : standard deviation\n \"\n variance_observed = 1:length(observed_I)\n half_window_size = floor(window_size / 2)\n for( i in seq(half_window_size + 1, length(observed_I) - half_window_size + 1))\n {\n indices = (i-half_window_size):(i + half_window_size-1)\n variance = var(observed_I[indices])\n variance_observed[i] = variance\n }\n\n first_window_idexes = 1:half_window_size\n last_window_indexes = (length(observed_I) - half_window_size + 1):length(observed_I)\n DE_in = var(observed_I[first_window_idexes])\n DE_out = var(observed_I[last_window_indexes])\n variance_observed[first_window_idexes] = DE_in\n variance_observed[last_window_indexes] = DE_out\n return(variance_observed)\n}", "meta": {"hexsha": "c2b7c161f5b879834784a83c741b4253715b2071", "size": 3970, "ext": "r", "lang": "R", "max_stars_repo_path": "bootstrapping.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": "bootstrapping.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": "bootstrapping.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.2764227642, "max_line_length": 114, "alphanum_fraction": 0.7166246851, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5896255696453878}} {"text": "\n#' f_qscop\n#'\n#' Estimate the quantile given specific $(\\tau, x)$\n#'\n#' @param tau conditional probability\n#' @param n1 the first covariates\n#' @param til_beta the current estimation fro $\\tilde{\\beta}$\n#' @param m_sigma $K_\\tau K_1 \\times K_\\tau K_1 \\Sigma$ diagonal block matix.\n#' @param ktau internal knots of tau\n#' @param mtau order for tau spline\n#'\n#'\n#' @return An estimated the quantile given specific $(\\tau, x)$\n#'\n#' @examples\n#' \\dontrun{\n#' k1 <- 4; ktau <- 4; m1 <- 4; mtau <- 4; y <- rnorm(200)\n#' n1 <- f_n1(1:200, k1, m1); beta <- rnorm(prod(ktau + mtau, k1 + m1))\n#' til_beta <- tilde_beta(beta, k1 + m1)\n#' m_sigma <- f_sigma(ktau + mtau, k1 + m1)\n#' f_qscop(seq(0, 1, 0.1), n1, til_beta, m_sigma, ktau, mtau)\n#' f_qscop(0, n1, til_beta, m_sigma, ktau, mtau) < f_qscop(1, n1, til_beta, m_sigma, ktau, mtau)\n\n#' }\n\nf_qscop <- function(tau, n1, til_beta, m_sigma, ktau, mtau) {\n m_n <- kronecker(spline_basis(tau, ktau, mtau, c(1, 0)), n1)\n out <- m_n %*% m_sigma %*% til_beta\n return(c(out))\n}\n\n\n\n#' f_qzeros\n#'\n#' zeros function to find the root $\\tau_i$ for each observs\n#'\n#' @param tau conditional probability\n#' @param idx index of the observations\n#' @param v_y vector of y\n#' @param n1 spline basis for the first covariates\n#' @param ... other 4 args for f_qscop in order (til_beta, m_sigma, ktau, mtau)\n#'\n#'\n#' @return Difference bw response and estimation $Q(\\tau, x_i) - y_i$\n#'\n#' @examples\n#' \\dontrun{\n#' k1 <- 4; ktau <- 4; m1 <- 4; mtau <- 4; y <- rnorm(200)\n#' n1 <- f_n1(1:200, k1, m1); beta <- rnorm(prod(ktau + mtau, k1 + m1))\n#' til_beta <- tilde_beta(beta, k1 + m1)\n#' m_sigma <- f_sigma(ktau + mtau, k1 + m1)\n#' f_qzeros(0.5, 2:3, y, n1, til_beta, m_sigma, ktau, mtau)\n#' }\nf_qzeros <- function(tau, idx, v_y, n1, ...) {\n n1 <- n1[idx, ]\n if (length(idx) == 1) {\n n1 <- t(n1)\n }\n s_dif <- f_qscop(tau, n1, ...) - v_y[idx]\n if ((tau == 0 && s_dif > 0) || (tau == 1 && s_dif < 0)) {\n return(0)\n }\n\n return(s_dif)\n}\n\n\n#' f_tausearch\n#'\n#' search the $\\tau^*$ using the unitroot function\n#'\n#' @param v_y vector of y\n#' @param n1 spline basis for the first covariates\n#' @param ... other 4 args for f_qscop in order (til_beta, m_sigma, k2, m2)\n#'\n#'\n#' @return $\\tau^*$\n#'\n#' \\dontrun{\n#' k1 <- 4; ktau <- 4; m1 <- 4; mtau <- 4; y <- rnorm(200)\n#' n1 <- f_n1(1:200, k1, m1); beta <- rnorm(prod(ktau + mtau, k1 + m1))\n#' til_beta <- tilde_beta(beta, k1 + m1)\n#' m_sigma <- f_sigma(ktau + mtau, k1 + m1)\n#' f_qzeros(0.5, 2:3, y, n1, til_beta, m_sigma, ktau, mtau)\n#' v_taus <- f_tausearch(y, n1, til_beta, m_sigma, ktau, mtau)\n#' sapply(1:200, function(x) {\n#' f_qscop(v_taus[x], t(n1[x, ]), til_beta, m_sigma, ktau, mtau)\n#' }) - y\n#' }\nf_tausearch <- function(v_y, n1, ...) {\n taustar <- sapply(seq_along(v_y), function(x) {\n uniroot(f_qzeros,\n idx = x,\n v_y = v_y,\n n1 = n1,\n ...,\n interval = c(0, 1))$root})\n return(taustar)\n}", "meta": {"hexsha": "2549ed67aa066077fc29632b9babaf4dbdff9c35", "size": 3077, "ext": "r", "lang": "R", "max_stars_repo_path": "R/tau_star.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/tau_star.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/tau_star.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.4653465347, "max_line_length": 96, "alphanum_fraction": 0.5674358141, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5892963340646501}} {"text": " E04NFJ Example Program Results\n \n *** e04nf \n \n Parameters \n ---------- \n \n Problem type........... QP2 \n \n Linear constraints..... 7 Feasibility tolerance.. 1.05E-08 \n Variables.............. 7 Optimality tolerance... 1.05E-08 \n Hessian rows........... 7 Rank tolerance......... 1.11E-14 \n \n Infinite bound size.... 1.00E+20 COLD start............. \n Infinite step size..... 1.00E+20 EPS (machine precision) 1.11E-16 \n \n Check frequency........ 50 Expand frequency....... 5 \n Minimum sum of infeas.. NO Crash tolerance........ 1.00E-02 \n \n Max degrees of freedom. 7 Print level............ 10 \n Feasibility phase itns. 70 Monitoring file........ -1 \n Optimality phase itns. 70 \n \n Workspace provided is IWORK( 17), WORK( 189). \n To solve problem we need IWORK( 17), WORK( 189). \n \n \n Itn Step Ninf Sinf/Objective Norm Gz \n 0 0.0E+00 3 1.038000E-01 0.0E+00 \n 1 4.1E-02 1 3.000000E-02 0.0E+00 \n 2 4.2E-02 0 0.000000E+00 0.0E+00 \n Itn 2 -- Feasible point found. \n 2 0.0E+00 0 4.580000E-02 0.0E+00 \n 3 1.3E-01 0 4.161596E-02 0.0E+00 \n 4 1.0E+00 0 3.936227E-02 4.2E-17 \n 5 4.1E-01 0 3.758935E-02 1.2E-02 \n 6 1.0E+00 0 3.755377E-02 1.0E-17 \n 7 1.0E+00 0 3.703165E-02 3.8E-17 \n \n \n Varbl State Value Lower Bound Upper Bound Lagr Mult Slack \n \n V 1 LL -1.000000E-02 -1.000000E-02 1.000000E-02 0.4700 . \n V 2 FR -6.986465E-02 -0.100000 0.150000 . 3.0135E-02 \n V 3 FR 1.825915E-02 -1.000000E-02 3.000000E-02 . 1.1741E-02 \n V 4 FR -2.426081E-02 -4.000000E-02 2.000000E-02 . 1.5739E-02 \n V 5 FR -6.200564E-02 -0.100000 5.000000E-02 . 3.7994E-02 \n V 6 FR 1.380544E-02 -1.000000E-02 None . 2.3805E-02 \n V 7 FR 4.066496E-03 -1.000000E-02 None . 1.4066E-02 \n \n \n L Con State Value Lower Bound Upper Bound Lagr Mult Slack \n \n L 1 EQ -0.130000 -0.130000 -0.130000 -1.908 -5.5511E-17 \n L 2 FR -5.879898E-03 None -4.900000E-03 . 9.7990E-04 \n L 3 UL -6.400000E-03 None -6.400000E-03 -0.3144 8.6736E-19 \n L 4 FR -4.537323E-03 None -3.700000E-03 . 8.3732E-04 \n L 5 FR -2.915996E-03 None -1.200000E-03 . 1.7160E-03 \n L 6 LL -9.920000E-02 -9.920000E-02 None 1.955 . \n L 7 LL -3.000000E-03 -3.000000E-03 2.000000E-03 1.972 4.3368E-18 \n \n Exit e04nf - Optimal QP solution. \n \n Final QP objective value = 0.3703165E-01 \n \n Exit from QP problem after 7 iterations. \n", "meta": {"hexsha": "13101d20c2ba320b55a373bf17b3b285be5a8010", "size": 5777, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/e04nfje.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/e04nfje.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/e04nfje.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": 86.223880597, "max_line_length": 120, "alphanum_fraction": 0.2499567249, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5891707536936803}} {"text": "hist_nwj <- function(x, type='nwj', alpha=0.01, P=0.99, breaks=NULL, jfit='all',\n upperbound=TRUE, main=NULL, subtitle='yes', suppress='no') {\n ## plot histogram and normal, Weibull, and Johnson distributions\n ## adds lines for upper tolerance limits for given alpha and proportion\n ## alpha = 1 - confidence\n ## P = coverage proportion (tolerance interval only)\n proportion = P\n ## breaks = number of bins used in the histogram (default auto determines number)\n ## jfit = 'all' = uses SuppDists::JohnsonFit to determine parameters\n ## = 'SU' = uses ExtDist::eJohnsonSU to determine parameters\n ## = list of user specified parameters\n ## e.g., jparms <- list(gamma = -1.039,\n ## delta = 1.66,\n ## xi = 14.46,\n ## lambda = 6.95,\n ## type = 'SU')\n ## johnson_tol(mtcars$mpg, jfit=jparms)\n ## main = title for histogram (default is \"Histogram of ...\")\n ## subtitle = 'yes' = puts description of lines in subtitle\n ## = 'no' = subtitle is blank\n ## = user specified, single line subtitle\n ## suppress = 'yes' creates plot but does not return calculated values to the screen\n ## (e.g., fit parameters and tolerance limits)\n \n ## name of variable passed in\n xname <- deparse(substitute(x))\n\n ## initialize parameters\n xmean <- NA\n xsd <- NA\n shape <- NA\n scale <- NA\n jparms <- NA\n tol_out_norm <- NA\n tol_out_weib <- NA\n tol_out_john <- NA\n upper_tolerance_limit_norm <- NA\n upper_tolerance_limit_weib <- NA\n upper_tolerance_limit_john <- NA\n xdensity_norm <- NA\n xdensity_weib <- NA\n xdensity_john <- NA\n \n if (grepl('n', type)) {\n ## normal distribution calculations\n tol_out_norm <- tolerance::normtol.int(x, alpha = alpha, P=proportion, side=1)\n upper_tolerance_limit_norm <- tol_out_norm$'1-sided.upper'\n }\n \n if (grepl('w', type)) {\n ## Weibull distribution calculations\n if (min(x) < 0) {\n cat('\\n')\n cat('#####################################################################\\n')\n cat('Skip Weibull: Negative values cannot be fit with Weibull distribution\\n')\n cat('#####################################################################\\n\\n')\n tol_out_weib <- NA\n shape <- NA\n scale <- NA\n upper_tolerance_limit_weib <- NA\n } else {\n tol_out_weib <- tolerance::exttol.int(x, alpha=alpha, P=proportion, side=1, dist=\"Weibull\")\n shape <- tol_out_weib$'shape.1'\n scale <- tol_out_weib$'shape.2'\n upper_tolerance_limit_weib <- tol_out_weib$'1-sided.upper'\n }\n }\n \n if (grepl('j', type)) {\n ## Johnson distribution calculations\n tol_out_john <- johnson_tol(x, alpha=alpha, P=proportion, side=1, jfit=jfit)\n jparms <- tol_out_john$jparms\n upper_tolerance_limit_john <- tol_out_john$xtol_upper\n }\n \n ## create vectors with density distributions\n xmin <- min(x)\n if (isTRUE(upperbound)) {\n xmax <- max(x,\n upper_tolerance_limit_norm,\n upper_tolerance_limit_weib,\n upper_tolerance_limit_john,\n na.rm = TRUE)\n } else {\n xmax <- max(x, na.rm = TRUE)\n }\n chuncks <- (xmax-xmin)/1000\n xrange <- seq(xmin,xmax,by=chuncks)\n xmean <- mean(x)\n xsd <- sd(x)\n if (grepl('n', type)) xdensity_norm <- stats::dnorm(xrange,xmean,xsd) \n if (grepl('w', type)) xdensity_weib <- stats::dweibull(xrange,shape=shape,scale=scale)\n if (grepl('j', type)) xdensity_john <- SuppDists::dJohnson(xrange, jparms)\n\n ## make histogram\n ## warning: xlim range can mess up x-axis\n ## obtain histogram parameters but suppress plot\n if (is.null(breaks)) {\n ## breaks not specified so figure out what to use\n out <- hist(x, plot=FALSE)\n breaks <- length(out$breaks)\n }\n ## hist needed with number of breaks to be used to get density for max height of histogram\n out <- hist(x, breaks=breaks, plot=FALSE)\n maxdensity <- max(xdensity_norm, xdensity_weib, xdensity_john, out$density, na.rm=TRUE)\n ymax <- max(out$density, maxdensity)\n ## create plot\n if (is.null(main)) main <- paste('Histogram of', xname, sep=\" \")\n hist(x, breaks=breaks,\n xlab = xname,\n xlim=c(xmin,xmax+(xmax-xmin)/breaks), \n ylim=c(0,maxdensity),\n freq=FALSE,\n main=main)\n if (subtitle == 'yes') {\n n <- w <- j <- NULL\n if (grepl('n', type)) n <- 'red = normal,'\n if (grepl('w', type)) w <- 'blue = Weibull,'\n if (grepl('j', type)) j <- 'black = Johnson'\n ## subtitle <- list('line color: red = normal, blue = Weibull, black = Johnson',\n ## 'line type: solid = distribution or mean, dashed = 1-sided upper bound')\n subtitle <- list(paste('line color:', n, w, j, sep=' '),\n 'line type: solid = distribution or mean, dashed = 1-sided upper bound')\n mtext(subtitle, side=3, line=c(0.75, 0), cex=.75, col='black')\n } else if (subtitle == 'no') {\n ## skip subitile\n } else {\n ## use user specified subitile\n mtext(subtitle)\n }\n \n ## add distributions\n if (grepl('n', type)) lines(x=xrange, y=xdensity_norm, col='red', lty=1)\n if (grepl('w', type)) lines(x=xrange, y=xdensity_weib, col='blue', lty=1)\n if (grepl('j', type)) lines(x=xrange, y=xdensity_john, col='black', lty=1)\n\n ## add lines for mean and upper 1-sided 99/99 tolerance limits\n abline(v=xmean,col=\"red\")\n if (isTRUE(upperbound)) {\n if (grepl('n', type)) abline(v=upper_tolerance_limit_norm,col=\"red\", lty=2)\n if (grepl('w', type)) abline(v=upper_tolerance_limit_weib,col=\"blue\", lty=2)\n if (grepl('j', type)) abline(v=upper_tolerance_limit_john,col=\"black\",lty=2)\n }\n\n ## print to screen\n if (suppress == 'no') {\n cat(\"Upper, 1-Sided Tolerance Limits\\n\")\n cat(\"confidence =\", 1-alpha, \", coverage proportion\", proportion, '\\n')\n cat(\"-------------------------------\")\n cat(\"\\n\")\n if (grepl('n', type)) {\n cat(\"Normal distribution (red):\\n\")\n cat(\" mean =\",xmean,\"\\n\")\n cat(\" standard deviation =\",xsd,\"\\n\")\n cat(\" tolerance limit =\",upper_tolerance_limit_norm,\"\\n\")\n cat(\"\\n\")\n }\n if (grepl('w', type)) {\n cat(\"Weibull distribution (blue):\\n\")\n cat(\" shape =\",shape,\"\\n\")\n cat(\" scale =\",scale,\"\\n\")\n cat(\" tolerance limit =\",upper_tolerance_limit_weib,\"\\n\")\n cat(\"\\n\")\n }\n if (grepl('j', type)) {\n cat(\"Johnson distribution (black):\\n\")\n cat(\" gamma =\",jparms$gamma ,\"\\n\")\n cat(\" delta =\",jparms$delta ,\"\\n\")\n cat(\" xi =\",jparms$xi ,\"\\n\")\n cat(\" lambda =\",jparms$lambda,\"\\n\")\n cat(\" type =\",jparms$type ,\"\\n\")\n cat(\" tolerance limit =\",upper_tolerance_limit_john,\"\\n\")\n cat(\" (tolerance limit is the distribution bound if type SB or SL)\\n\")\n }\n } \n\n return(list(sided = '1-sided, upper limits',\n proportion = proportion,\n alpha = alpha,\n nparms = list(mean = xmean, sd=xsd),\n wparms = list(shape = shape, scale = scale),\n jparms = jparms,\n tol_out_norm=tol_out_norm,\n tol_out_weib=tol_out_weib,\n tol_out_john=tol_out_john))\n\n}\n\n## set.seed(1)\n## jparms <- list(gamma = -1.039, delta = 1.66, xi = 14.46, lambda = 6.95, type = 'SU')\n## xjohn <- SuppDists::rJohnson(999, parms=jparms) + 2\n## out <- hist_nwj(xjohn, jfit=jparms)\n\n## out <- hist_nwj(mtcars$mpg)\n## out <- hist_nwj(mtcars$mpg, type='n')\n## out <- hist_nwj(mtcars$mpg, type='w')\n## out <- hist_nwj(mtcars$mpg, type='j')\n## out <- hist_nwj(mtcars$mpg, type='nw')\n", "meta": {"hexsha": "a9ed6bf8a5424f0674ecd61601488da71677e7fa", "size": 8380, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/hist_nwj.r", "max_stars_repo_name": "dhjelmar/R-setup", "max_stars_repo_head_hexsha": "42436ac2389512261da87dfb0257d34b7ad33b14", "max_stars_repo_licenses": ["MIT"], "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": "dhjelmar/R-setup", "max_issues_repo_head_hexsha": "42436ac2389512261da87dfb0257d34b7ad33b14", "max_issues_repo_licenses": ["MIT"], "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": "dhjelmar/R-setup", "max_forks_repo_head_hexsha": "42436ac2389512261da87dfb0257d34b7ad33b14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-16T12:06:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T12:06:21.000Z", "avg_line_length": 42.1105527638, "max_line_length": 104, "alphanum_fraction": 0.5304295943, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5891707361028511}} {"text": "correlations <- function(x, y, block=5, nboot=1000) {\r\n\r\n\torig <- cor(x,y)\r\n\tdistr <- array(0, nboot)\r\n\r\n\tfor(boot in 1:nboot) {\r\n\r\n\t\tnblock <- length(x)/block\r\n\r\n\t\ttmpx <- sample(seq(1:(length(x)-block)), size=nblock, replace=TRUE)\r\n\t\ttmpy <- sample(seq(1:(length(y)-block)), size=nblock, replace=TRUE)\r\n\r\n\t\tx.b <- 0\r\n\t\ty.b <- 0\r\n\r\n\t\tfor(i in 1:nblock) {\r\n\t\t\tx.b <- c(x.b, x[tmpx[i]:(tmpx[i]+block-1)])\r\n\t\t\ty.b <- c(y.b, y[tmpy[i]:(tmpy[i]+block-1)])\r\n\t\t}\r\n\t\tdistr[boot] <- cor(x.b, y.b)\r\n\t}\r\n\r\n\tp <- length(which(abs(distr) >= abs(orig)))/nboot\r\n\r\n my_return <- list('p' = p, 'distr' = distr)\r\n\r\n\treturn (my_return)\r\n}\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/1.csv\")\r\n\r\nrr1 <- correlations(data$RR_A,data$RR_B)\r\npos1 <- correlations(data$Pos_A,data$Pos_B)\r\ndel1 <- correlations(data$Delta_PosA, data$Delta_PosB)\r\n\r\nrp1 <-correlations(data$RR_A,data$Pos_A)\r\nrd1 <-correlations(data$RR_A,data$Delta_PosA)\r\nrp1_ <-correlations(data$RR_B,data$Pos_B)\r\nrd1_ <-correlations(data$RR_B,data$Delta_PosB)\r\ncrp1 <-correlations(data$RR_A,data$Pos_B)\r\ncrd1 <-correlations(data$RR_A,data$Delta_PosB)\r\ncrp1_ <-correlations(data$RR_B,data$Pos_A)\r\ncrd1_ <-correlations(data$RR_B,data$Delta_PosA)\r\n\r\ncrd1$p\r\ncrd2$p\r\ncrd3$p\r\ncrd4$p\r\ncrd5$p\r\ncrd6$p\r\n\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/2.csv\")\r\n\r\nrr2 <- correlations(data$RR_A,data$RR_B)\r\npos2 <- correlations(data$Pos_A,data$Pos_B)\r\ndel2 <- correlations(data$Delta_PosA, data$Delta_PosB)\r\n\r\nrp2 <-correlations(data$RR_A,data$Pos_A)\r\nrd2 <-correlations(data$RR_A,data$Delta_PosA)\r\nrp2_ <-correlations(data$RR_B,data$Pos_B)\r\nrd2_ <-correlations(data$RR_B,data$Delta_PosB)\r\n\r\ncrp2 <-correlations(data$RR_A,data$Pos_B)\r\ncrd2 <-correlations(data$RR_A,data$Delta_PosB)\r\ncrp2_ <-correlations(data$RR_B,data$Pos_A)\r\ncrd2_ <-correlations(data$RR_B,data$Delta_PosA)\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/3.csv\")\r\n\r\nrr3 <- correlations(data$RR_C,data$RR_D)\r\npos3 <- correlations(data$Pos_C,data$Pos_D)\r\ndel3 <- correlations(data$Delta_PosC, data$Delta_PosD)\r\n\r\nrp3 <-correlations(data$RR_C,data$Pos_C)\r\nrd3 <-correlations(data$RR_C,data$Delta_PosC)\r\nrp3_ <-correlations(data$RR_D,data$Pos_D)\r\nrd3_ <-correlations(data$RR_D,data$Delta_PosD)\r\ncrp3 <-correlations(data$RR_C,data$Pos_D)\r\ncrd3 <-correlations(data$RR_C,data$Delta_PosD)\r\ncrp3_ <-correlations(data$RR_D,data$Pos_C)\r\ncrd3_ <-correlations(data$RR_D,data$Delta_PosC)\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/4.csv\")\r\n\r\nrr4 <- correlations(data$RR_C,data$RR_D)\r\npos4 <- correlations(data$Pos_C,data$Pos_D)\r\ndel4 <- correlations(data$Delta_PosC, data$Delta_PosD)\r\n\r\nrp4 <-correlations(data$RR_C,data$Pos_C)\r\nrd4 <-correlations(data$RR_C,data$Delta_PosC)\r\nrp4_ <-correlations(data$RR_D,data$Pos_D)\r\nrd4_ <-correlations(data$RR_D,data$Delta_PosD)\r\n\r\ncrp4 <-correlations(data$RR_C,data$Pos_D)\r\ncrd4 <-correlations(data$RR_C,data$Delta_PosD)\r\ncrp4_ <-correlations(data$RR_D,data$Pos_C)\r\ncrd4_ <-correlations(data$RR_D,data$Delta_PosC)\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/5.csv\")\r\n\r\nrr5 <- correlations(data$RR_E,data$RR_F)\r\npos5 <- correlations(data$Pos_E,data$Pos_F)\r\ndel5 <- correlations(data$Delta_PosE, data$Delta_PosF)\r\n\r\nrp5 <-correlations(data$RR_E,data$Pos_E)\r\nrd5 <-correlations(data$RR_E,data$Delta_PosE)\r\nrp5_ <-correlations(data$RR_F,data$Pos_F)\r\nrd5_ <-correlations(data$RR_F,data$Delta_PosF)\r\n\r\ncrp5 <-correlations(data$RR_E,data$Pos_F)\r\ncrd5 <-correlations(data$RR_E,data$Delta_PosF)\r\ncrp5_ <-correlations(data$RR_F,data$Pos_E)\r\ncrd5_ <-correlations(data$RR_F,data$Delta_PosE)\r\n\r\ndata <- read.csv(\"C:/Users/LucasMarquesGasparin/Desktop/Learning/TCC/Data/Processed/6.csv\")\r\n\r\nrr6 <- correlations(data$RR_E,data$RR_F)\r\npos6 <- correlations(data$Pos_E,data$Pos_F)\r\ndel6 <- correlations(data$Delta_PosE, data$Delta_PosF)\r\n\r\nrp6 <-correlations(data$RR_E,data$Pos_E)\r\nrd6 <-correlations(data$RR_E,data$Delta_PosE)\r\nrp6_ <-correlations(data$RR_F,data$Pos_F)\r\nrd6_ <-correlations(data$RR_F,data$Delta_PosF)\r\n\r\ncrp6 <-correlations(data$RR_E,data$Pos_F)\r\ncrd6 <-correlations(data$RR_E,data$Delta_PosF)\r\ncrp6_ <-correlations(data$RR_F,data$Pos_E)\r\ncrd6_ <-correlations(data$RR_F,data$Delta_PosE)\r\n\r\n\r\nrr1$p\r\nhist(rr1$distr)\r\n\r\npos1$p\r\nhist(pos1$distr)\r\n\r\ndel1$p\r\nhist(del1$distr)\r\n\r\n\r\n# Simulação\r\n\r\nX <- vector(length = T)\r\nY <- vector(length = T)\r\nT = 1000\r\nnboot = 1000\r\np_valores = array(0, nboot)\r\nfor(boot in 1:nboot) {\r\n\tt = 1\r\n\tX[0] <- rnorm(0)\r\n\tY[0] <- rnorm(0)\r\n\twhile (t < T) {\r\n\t\tt = t + 1\r\n\t\tY[t] <- 0.5*Y[t-1] + rnorm(1)\r\n\t\tX[t] <- 0.5*X[t-1] + rnorm(1) \r\n\t}\r\n\trr <- correlations(X, Y)\r\n\tp_valores[boot] <- rr$p\r\n}\r\n\r\nhist(p_valores)", "meta": {"hexsha": "4a80b91f033c13603da557d7a6f02553309b9ea8", "size": 4779, "ext": "r", "lang": "R", "max_stars_repo_path": "code/R/Bootstrap RR.r", "max_stars_repo_name": "LucGaspar/GrangerHRV", "max_stars_repo_head_hexsha": "09b01257ed59ba9190a2aeaa4f0b2a7c85cb8e4e", "max_stars_repo_licenses": ["MIT"], "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/Bootstrap RR.r", "max_issues_repo_name": "LucGaspar/GrangerHRV", "max_issues_repo_head_hexsha": "09b01257ed59ba9190a2aeaa4f0b2a7c85cb8e4e", "max_issues_repo_licenses": ["MIT"], "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/Bootstrap RR.r", "max_forks_repo_name": "LucGaspar/GrangerHRV", "max_forks_repo_head_hexsha": "09b01257ed59ba9190a2aeaa4f0b2a7c85cb8e4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-06T13:56:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T13:56:54.000Z", "avg_line_length": 29.3190184049, "max_line_length": 92, "alphanum_fraction": 0.7108181628, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5891477904794518}} {"text": "# Various useful functions\n\ngetPmat <- function(tmu,tv_ti_ratio,acgt) {\n # Returns the evolutionary substitution matrix\n if (any(acgt >= 1) || any(acgt <= 0)) {\n abort(\"The ACGT frequencies must be in the range 0 to 1\")\n } else if (sum(acgt) != 1) {\n abort(\"The ACGT frequencies do not sum to 1\")\n } else if (tv_ti_ratio <= 0) {\n abort(\"The transversion and transtition ratio cannot go under 0\")\n }\n\n # Returns the substitution probability matrix.\n if (tv_ti_ratio == 1 && identical(acgt, c(0.25, 0.25, 0.25, 0.25))) {\n return(jukesCantorPmat(tmu))\n } else {\n Q <- qmatHKY85(tmu, tv_ti_ratio, acgt)\n r <- eigen(Q)\n B <- r$vectors\n E <- diag(exp(r$values))\n\n # Q The eigen vector change of basis\n # M -> M\n #\n # ^ ^\n # |B^-1 |B\n # Eig\n # N -> N\n\n # Little trick to avoid numerical difficulties\n out <- solve(a=t(B), b=E %*% t(B))\n\n rownames(out) <- c(\"A\",\"C\",\"G\",\"T\")\n colnames(out) <- c(\"A\",\"C\",\"G\",\"T\")\n return(out)\n }\n}\n\njukesCantorPmat2 <- function(tmu){\n # Using the Juke-Cantor model\n names <- c(\"A\", \"C\", \"G\", \"T\")\n return(matrix(1 / 4 - exp(-tmu) / 4, nrow=4, ncol=4, dimnames=list(names, names)) + diag(exp(-tmu), 4, 4))\n}\n\nqmatHKY85 <- function(tmu, tv_ti, acgt) {\n # HKY85 model\n # | sum_1 pi_c * tv_ti pi_g pi_t * tv_ti |\n # | pi_a * tv_ti sum_2 pi_g * tv_ti pi_t |\n # Q = tmu * | pi_a pi_c * tv_ti sum_3 pi_t * tv_ti |\n # | pi_a * tv_ti pi_c pi_g * tv_ti sum_4 |\n #\n Qmat <- rbind(\n c(0, tv_ti, 1, tv_ti) * acgt,\n c(tv_ti, 0, tv_ti, 1) * acgt,\n c(1, tv_ti, 0, tv_ti) * acgt,\n c(tv_ti, 1, tv_ti, 0) * acgt)\n\n return(tmu * (Qmat - diag(rowSums(Qmat))))\n}\n\nmetroDesc <- function(lpr, lol){\n # the logic in the Metropolis-Hastings step\n stopifnot(!is.na(lpr))\n stopifnot(!is.na(lol))\n\n return(log(runif(1)) < lpr - lol)\n}\n\nseqProbVecLambda <- function(lambda, lambda_disp, m, termini=\"both\") {\n # Returns the position specific probability of being in an overhang\n pvals <- dnbinom(1:m - 1, prob=lambda, size=lambda_disp)\n psum <- (1 - cumsum(pvals)) / 2\n\n if (termini == \"both\") {\n return(c(psum[1:(m / 2)], rev(psum[1:(m / 2)])))\n } else if (termini == \"5p\") {\n return(psum)\n } else if (termini == \"3p\") {\n return(rev(psum))\n } else {\n abort(\"Invalid value for termini: '%s'\", termini)\n }\n}\n\n\ncat(\"Compiling C++ extension. This may take a moment ..\\n\")\nsourceCpp(code='\n// [[Rcpp::depends(RcppGSL)]]\n#include \n\n#include \n\n// [[Rcpp::export]]\ndouble logLikFunOneBaseFast(\n const Rcpp::NumericVector Gen,\n const Rcpp::NumericVector S,\n const Rcpp::NumericVector theta,\n const double deltad,\n const double deltas,\n const Rcpp::NumericVector laVec,\n const Rcpp::NumericVector nuVec,\n const int m,\n const int lin\n) {\n Rcpp::NumericVector pDam(4);\n double result = 0;\n\n for (int i = 0; i < laVec.size(); i++) {\n double la = laVec[i];\n double nu = nuVec[i];\n double pct = nu * (la * deltas + deltad * (1 - la));\n double pga = (1 - nu) * (la * deltas + deltad * (1 - la));\n\n pDam[0] = theta(lin - 1, 0) * 1 + theta(lin - 1, 2) * pga;\n pDam[1] = theta(lin - 1, 1) * (1 - pct);\n pDam[2] = theta(lin - 1, 2) * (1 - pga);\n pDam[3] = theta(lin - 1, 1) * pct + theta(lin - 1, 3) * 1;\n\n double p1 = gsl_sf_lnfact(Gen(i)) -\n gsl_sf_lnfact(S(i, 0)) -\n gsl_sf_lnfact(S(i, 1)) -\n gsl_sf_lnfact(S(i, 2)) -\n gsl_sf_lnfact(S(i, 3));\n\n double p2 = S(i, 0) * log(pDam[0]) +\n S(i, 1) * log(pDam[1]) +\n S(i, 2) * log(pDam[2]) +\n S(i, 3) * log(pDam[3]);\n\n result += p1 + p2;\n }\n return result;\n}')\ncat(\"Compilation of C++ extension completed\\n\")\n\n\nlogLikAll <- function(dat, Theta, deltad, deltas, laVec, nuVec, m) {\n # Calculates the logLikelihood for all the bases\n if (deltad < 0 || deltad > 1 || deltas < 0 || deltas > 1) {\n return(-Inf)\n }\n\n Asub <- dat[, \"A.C\"] + dat[, \"A.G\"] + dat[, \"A.T\"]\n ALL <- logLikFunOneBaseFast(dat[,\"A\"], cbind(dat[,\"A\"]-Asub,dat[,\"A.C\"],dat[,\"A.G\"],dat[,\"A.T\"]),Theta,deltad,deltas,laVec,nuVec,m,1)\n\n Csub <- dat[, \"C.A\"] + dat[, \"C.G\"] + dat[, \"C.T\"]\n CLL <- logLikFunOneBaseFast(dat[,\"C\"], cbind(dat[,\"C.A\"],dat[,\"C\"]-Csub,dat[,\"C.G\"],dat[,\"C.T\"]),Theta,deltad,deltas,laVec,nuVec,m,2)\n\n Gsub <- dat[, \"G.A\"] + dat[, \"G.C\"] + dat[, \"G.T\"]\n GLL <- logLikFunOneBaseFast(dat[,\"G\"], cbind(dat[,\"G.A\"],dat[,\"G.C\"],dat[,\"G\"]-Gsub,dat[,\"G.T\"]),Theta,deltad,deltas,laVec,nuVec,m,3)\n\n Tsub <- dat[, \"T.A\"] + dat[, \"T.C\"] + dat[, \"T.G\"]\n TLL <- logLikFunOneBaseFast(dat[,\"T\"], cbind(dat[,\"T.A\"],dat[,\"T.C\"],dat[,\"T.G\"],dat[,\"T\"]-Tsub),Theta,deltad,deltas,laVec,nuVec,m,4)\n\n return(ALL + CLL + GLL + TLL)\n}\n\n\ngetParams <- function(cp){\n #Utility function nice to update the MCMC iterations matrix\n return(c(cp$Theta,cp$Rho,cp$DeltaD,cp$DeltaS,cp$Lambda,cp$LambdaRight,cp$LambdaDisp))\n}\n\nplotTrace<- function(dat,main,k=111){\n #Running median of the MCMC iterations\n plot(1:length(dat),dat,xlab=\"Iteration\",ylab=\"\",main=main,type=\"l\")\n}\n\nplotEverything <- function(mcmcOut,hi=0,pl,thin=100){\n #Plots the MCMC traceplot in the form of a running median and\n #histogram of the MCMC iterations\n if (sum(c(cu_pa$same_overhangs==FALSE,\n cu_pa$fix_disp==FALSE,\n cu_pa$fix_ti_tv==FALSE))>1){\n #Check if I need to add a extra row\n a_extra_row <- 1\n }else {\n a_extra_row <- 0\n }\n par(mfrow=c(3,2+a_extra_row))\n if(hi){\n hist(mcmcOut$out[,\"Theta\"],main=expression(theta),xlab=\"\",freq=FALSE)\n if (!mcmcOut$cu_pa$fix_ti_tv){\n hist(mcmcOut$out[,\"Rho\"],main=expression(rho),xlab=\"\",freq=FALSE)\n }\n hist(mcmcOut$out[,\"DeltaD\"],main=expression(delta[d]),xlab=\"\",freq=FALSE)\n hist(mcmcOut$out[,\"DeltaS\"],main=expression(delta[s]),xlab=\"\",freq=FALSE)\n hist(mcmcOut$out[,\"Lambda\"],main=expression(lambda),xlab=\"\",freq=FALSE)\n if (!mcmcOut$cu_pa$same_overhangs){\n hist(mcmcOut$out[,\"LambdaRight\"],main=expression(lambda[r]),xlab=\"\",freq=FALSE)\n }\n if (!mcmcOut$cu_pa$fix_disp){\n hist(mcmcOut$out[,\"LambdaDisp\"],main=expression(sigma[lambda]),xlab=\"\",freq=FALSE)\n }\n hist(mcmcOut$out[,\"LogLik\"],main=\"LogLik\",xlab=\"\",freq=FALSE)\n }else {\n plotTrace(mcmcOut$out[,\"Theta\"],main=expression(theta))\n if (!mcmcOut$cu_pa$fix_ti_tv){\n plotTrace(mcmcOut$out[,\"Rho\"],main=expression(theta))\n }\n plotTrace(mcmcOut$out[,\"DeltaD\"],main=expression(delta[d]))\n plotTrace(mcmcOut$out[,\"DeltaS\"],main=expression(delta[s]))\n plotTrace(mcmcOut$out[,\"Lambda\"],main=expression(lambda))\n if (!mcmcOut$cu_pa$same_overhangs){\n plotTrace(mcmcOut$out[,\"LambdaRight\"],main=expression(lambda[r]))\n }\n if (!mcmcOut$cu_pa$fix_disp){\n plotTrace(mcmcOut$out[,\"LambdaDisp\"],main=expression(sigma[lambda]))\n }\n plotTrace(mcmcOut$out[,\"LogLik\"],main=\"LogLik\")\n }\n par(mfrow=c(1,1))\n}\n\naccRat <- function(da){\n #A rough measure of the acceptance ratio\n return(length(unique(da))/length(da))\n}\n\nadjustPropVar <- function(mcmc,propVar){\n #Adjust the proposal variance to get something near .22\n for (i in colnames(mcmc$out)){\n if (i==\"LogLik\"){\n next\n } else if (i==\"LambdaRight\" & mcmc$cu_pa$same_overhangs){\n next\n } else if (i==\"LambdaDisp\" & mcmc$cu_pa$fix_disp){\n next\n } else if (i==\"Rho\" & mcmc$cu_pa$fix_ti_tv){\n next\n }\n rat <- accRat(mcmc$out[,i])\n if (rat<0.1){\n propVar[[i]] <- propVar[[i]]/2\n } else if (rat>0.3) {\n propVar[[i]] <- propVar[[i]]*2\n }\n }\n return(propVar)\n}\n\nrunGibbs <- function(cu_pa,iter){\n #Sampling over the conditional posterior distribution\n #for the parameters.\n esti <- matrix(nrow=iter,ncol=8)\n colnames(esti) <- c(\"Theta\",\"Rho\",\"DeltaD\",\"DeltaS\",\"Lambda\",\"LambdaRight\",\"LambdaDisp\",\"LogLik\")\n for (i in 1:iter){\n cu_pa<-updateTheta(cu_pa)\n if (!cu_pa$fix_ti_tv){\n #Fix the transition and transversion ratio\n cu_pa<-updateRho(cu_pa)\n }\n cu_pa<-updateDeltaD(cu_pa)\n cu_pa<-updateDeltaS(cu_pa)\n cu_pa<-updateLambda(cu_pa)\n if (!cu_pa$same_overhangs){\n #Not the same overhangs update lambda right\n cu_pa <- updateLambdaRight(cu_pa)\n }\n if (!cu_pa$fix_disp){\n #Allowing dispersion in the overhangs\n cu_pa<-updateLambdaDisp(cu_pa)\n }\n esti[i,c(1:7)] <- getParams(cu_pa)\n esti[i,\"LogLik\"] <- logLikAll(cu_pa$dat,cu_pa$ThetaMat,cu_pa$DeltaD,cu_pa$DeltaS,cu_pa$laVec,cu_pa$nuVec,cu_pa$m)\n if (! (i %% 1000) && cu_pa$verbose){\n cat(\"MCMC-Iter\\t\",i,\"\\t\",esti[i,\"LogLik\"],\"\\n\")\n }\n }\n return(list(out=esti,cu_pa=cu_pa))\n}\n\n\nsimPredCheck <- function(da,output){\n #Simulates one draw from the posterior predictive distribution\n #and the probability of a C>T substitution because of a cytosine\n #demnation.\n bases <- da[,c(\"A\",\"C\",\"G\",\"T\")]\n #Constructing the lambda vector\n if (output$cu_pa$same_overhangs){\n laVec <- seqProbVecLambda(sample(output$out[,\"Lambda\"],1),\n sample(output$out[,\"LambdaDisp\"],1),\n output$cu_pa$m,\n output$cu_pa$termini)\n }else {\n laVecLeft <- seqProbVecLambda(sample(output$out[,\"Lambda\"],1),\n sample(output$out[,\"LambdaDisp\"],1),\n output$cu_pa$m)\n laVecRight <- seqProbVecLambda(sample(output$out[,\"LambdaRight\"],1),\n sample(output$out[,\"LambdaDisp\"],1),\n output$cu_pa$m)\n laVec <- c(laVecLeft[1:(output$cu_pa$m/2)],laVecRight[(output$cu_pa$m/2+1):output$cu_pa$m])\n }\n #Constructing the nu vector\n nuVec <- output$cu_pa$nuVec\n\n #Sample the other parameters\n des <- sample(output$out[,\"DeltaS\"],1)\n ded <- sample(output$out[,\"DeltaD\"],1)\n the <- sample(output$out[,\"Theta\"],1)\n rho <- sample(output$out[,\"Rho\"],1)\n pmat <- getPmat(the,rho,output$cu_pa$acgt)\n ptransCT <- pmat[\"C\",\"T\"]\n ptransCC <- pmat[\"C\",\"C\"]\n ptransGA <- pmat[\"G\",\"A\"]\n ptransGG <- pmat[\"G\",\"G\"]\n #\n coln <- c(\"A.C\",\"A.G\",\"A.T\",\"C.A\",\"C.G\",\"C.T\",\"G.A\",\"G.C\",\"G.T\",\"T.A\",\"T.C\",\"T.G\")\n subs <- matrix(NA,nrow=nrow(output$cu_pa$dat),ncol=4+length(coln))\n colnames(subs) <- c(\"A\",\"C\",\"G\",\"T\",coln)\n #\n damProb <- rep(NA,nrow(output$cu_pa$dat))\n damProbGA <- damProb\n for (i in 1:nrow(output$cu_pa$dat)){\n #Construct the site specific probabilities\n pct <- nuVec[i]*(laVec[i]*des+ded*(1-laVec[i]))\n pga <- (1-nuVec[i])*(laVec[i]*des+ded*(1-laVec[i]))\n pDamMat <- matrix(c(\n 1,0,0,0,\n 0,1-pct,0,pct,\n pga,0,1-pga,0,\n 0,0,0,1\n ),nrow=4,byrow=TRUE)\n ThetapDam <- pDamMat %*% pmat\n #Calculate the probability C.T due to cytosine demanation\n damProb[i] <- ptransCC*pct/(ptransCC*pct+ptransCT)\n #Do not forget the reverse complement\n damProbGA[i] <- ptransGG*pga/(ptransGG*pga+ptransGA)\n #Then draw from a multinomial distribution\n subs[i,c(\"A.C\",\"A.G\",\"A.T\")] <- t(rmultinom(1,output$cu_pa$dat[i,\"A\"],ThetapDam[1,]))[-1]/output$cu_pa$dat[i,\"A\"]\n subs[i,c(\"C.A\",\"C.G\",\"C.T\")] <- t(rmultinom(1,output$cu_pa$dat[i,\"C\"],ThetapDam[2,]))[-2]/output$cu_pa$dat[i,\"C\"]\n subs[i,c(\"G.A\",\"G.C\",\"G.T\")] <- t(rmultinom(1,output$cu_pa$dat[i,\"G\"],ThetapDam[3,]))[-3]/output$cu_pa$dat[i,\"G\"]\n subs[i,c(\"T.A\",\"T.C\",\"T.G\")] <- t(rmultinom(1,output$cu_pa$dat[i,\"T\"],ThetapDam[4,]))[-4]/output$cu_pa$dat[i,\"T\"]\n }\n return(list(subs=subs,damProb=damProb,damProbGA=damProbGA))\n}\n\ncalcSampleStats <- function(da,X){\n #Summary statistics of the posterior distributions\n return(data.frame(\n x=1:nrow(da),\n pos=da[,\"Pos\"],\n mea=apply(X,1,mean),\n med=apply(X,1,median),\n loCI=apply(X,1,quantile,c(0.025), na.rm = TRUE),\n hiCI=apply(X,1,quantile,c(0.975), na.rm = TRUE)\n ))\n}\n\npostPredCheck <- function(da,output,samples=10000){\n #Plots the 95% posterior predictive intervals with the data as lines.\n #Returns the site specific probability of a C>T or G>A substitution\n #because of a cytosine demnation.\n CTs <- matrix(NA,nrow=nrow(da),ncol=samples)\n GAs <- matrix(NA,nrow=nrow(da),ncol=samples)\n REs <- matrix(NA,nrow=nrow(da),ncol=samples)\n C2TProbs <- matrix(NA,nrow=nrow(da),ncol=samples)\n G2AProbs <- matrix(NA,nrow=nrow(da),ncol=samples)\n #Two indices here, 1-based and the relative one\n da <- cbind(1:(nrow(da)),da)\n colnames(da)[1] <- \"oneBased\"\n #Get the breaks depending on parameters for pretty plots\n if (output$cu_pa$termini == \"both\") {\n bres <- c(seq(from=1,to=floor(nrow(da)/2),by=2),rev(seq(from=nrow(dat),to=floor(nrow(da)/2)+1,by=-2)))\n } else if (output$cu_pa$termini == \"5p\") {\n bres <- seq(from=1,to=nrow(da),by=2)\n } else if (output$cu_pa$termini == \"3p\") {\n bres <- seq(from=nrow(dat),to=1,by=-2)\n }else {\n abort(\"There is something fishy with the options\")\n }\n labs <- dat[bres,\"Pos\"]\n #Sample from the posterior predicitive distibution\n for (i in 1:samples){\n sam <- simPredCheck(da,output)\n C2TProbs[,i] <- sam$damProb\n G2AProbs[,i] <- sam$damProbGA\n CTs[,i] <- sam$subs[,\"C.T\"]\n GAs[,i] <- sam$subs[,\"G.A\"]\n REs[,i] <- apply(sam$subs[,c(\"A.C\",\"A.G\",\"A.T\",\"C.A\",\"C.G\",\"G.C\",\"G.T\",\"T.A\",\"T.C\",\"T.G\")],1,mean)\n }\n CTsStats <- calcSampleStats(da,CTs)\n GAsStats <- calcSampleStats(da,GAs)\n REsStats <- calcSampleStats(da,REs)\n #Plotting the posterior predictive intervals\n p <- ggplot()+\n geom_point(aes(x,mea,colour=\"C->T\"),data=CTsStats)+\n geom_point(aes(x,mea,colour=\"G->A\"),data=GAsStats)+\n geom_point(aes(x,mea,colour=\"Others\"),data=REsStats)+\n geom_errorbar(aes(x=x,ymin=loCI,ymax=hiCI,color=\"C->T\"),data=CTsStats)+\n geom_errorbar(aes(x=x,ymin=loCI,ymax=hiCI,color=\"G->A\"),data=GAsStats)+\n geom_errorbar(aes(x=x,ymin=loCI,ymax=hiCI,color=\"Others\"),data=REsStats)+\n geom_line(aes(oneBased,C.T/C),color=\"red\",data=data.frame(da))+\n geom_line(aes(oneBased,G.A/G),color=\"green\",data=data.frame(da))+\n geom_line(aes(oneBased,((A.C+A.G+A.T)/A+(C.A+C.G)/C+(G.C+G.T)/G+(T.A+T.C+T.G)/T)/10),color=\"blue\",data=data.frame(da))+\n labs(y = \"Substitution rate\",\n x = \"Relative position\",\n colour = \"Subs. type\",\n title = \"Posterior prediction intervals\")+\n scale_x_continuous(breaks=bres,labels=labs)\n if (output$cu_pa$use_bw_theme){\n p <- p+theme_bw()\n }\n plot(p)\n #The correcting probabilities\n coProbs <- cbind(da[,\"Pos\"],apply(C2TProbs,1,mean),apply(G2AProbs,1,mean))\n colnames(coProbs) <- c(\"Position\",\"C.T\",\"G.A\")\n return(coProbs)\n}\n\n\nwriteMCMC <- function(out,filename){\n #Writes the posterior samples to a file\n parameters <- c(\"Theta\",\"DeltaD\",\"DeltaS\",\"Lambda\")\n if (!out$cu_pa$fix_ti_tv){\n parameters <- c(parameters,\"Rho\")\n }\n if (!out$cu_pa$same_overhangs){\n parameters <- c(parameters,\"LambdaRight\")\n }\n if (!out$cu_pa$fix_disp){\n parameters <- c(parameters,\"LambdaDisp\")\n }\n parameters <- c(parameters,\"LogLik\")\n write.csv(out$out[,parameters],paste(filename,\".csv\",sep=\"\"))\n #Now calculate summary statistic of the posterior distributions\n mea <- apply(out$out[,parameters],2,mean)\n std <- apply(out$out[,parameters],2,sd)\n qua <- apply(out$out[,parameters],2,quantile,seq(from=0,to=1,by=.025))\n acc <- apply(out$out[,parameters],2,accRat)\n summStat <- rbind(mea,std,acc,qua)\n rownames(summStat)[1] <- \"Mean\"\n rownames(summStat)[2] <- \"Std.\"\n rownames(summStat)[3] <- \"Acceptance ratio\"\n write.csv(summStat,paste(filename,\"_summ_stat.csv\",sep=\"\"))\n}\n", "meta": {"hexsha": "237c3226adf037002da773bce67964ce42ef06a8", "size": 16830, "ext": "r", "lang": "R", "max_stars_repo_path": "mapdamage/r/stats/function.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/function.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/function.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": 38.5125858124, "max_line_length": 137, "alphanum_fraction": 0.5615567439, "num_tokens": 5354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5888193663231883}} {"text": "#' V-structure bias, binary exposure and binary outcome.\n#'\n#' Explore bias due to sample ascertainment when the exposure and outcome are binary variables. This class explores the range or OR generated by parameters in the following model:\n#' \\eqn{P(S = 1 | A,Y) = \\beta_0 + \\beta_a A + \\beta_y Y + \\beta_{ay}AY}\n#' Where A is a binary exposure, Y is a binary outcome and S indicates whether an individual is present in the dataset\n#' \\eqn{P(S = 1)} is the proportion of the population that is present in the data.\n#'\n#' @importFrom R6 R6Class\n#' @export\nVBB <- R6Class(\"VBB\", list(\n\n\t#' @field param Dataframe of parameter range list\n\tparam = NULL,\n\tdetails = list(),\n\n\t#' @description\n\t#' Calculate the expected OR under collider bias when null hypothoses of OR = 1 is true:\n\t#' @param b0 Baseline probability of being selected\n\t#' @param ba Effect of A on being selected\n\t#' @param by Effect of Y on being selected\n\t#' @param bay Effect of joint AY interaction on being selected\n\t#'\n\t#' @return Odds ratio\n\tor_calc = function(b0, ba, by, bay)\n\t{\n\t\tb0 * (b0 + ba + by + bay) / ((b0 + ba) * (b0 + by))\n\t},\n\t\n\t#' @description\n\t#' Calculate the proportion of samples included in the model for a given set of parameters\n\t#' @param b0 Baseline probability of being selected\n\t#' @param ba Effect of A on being selected\n\t#' @param by Effect of Y on being selected\n\t#' @param bay Effect of joint AY interaction on being selected\n\t#' @param pA \\eqn{P(A = 1)} in the general population\n\t#' @param pY \\eqn{P(Y = 1)} in the general population\n\t#' @param pAY \\eqn{P(A = 1, Y = 1)} in the general population\n\t#'\n\t#' @return P(S = 1)\n\tps_calc = function(b0, ba, by, bay, pA, pY, pAY)\n\t{\n\t\tb0 + ba * pA + by * pY + bay * pAY\n\t},\n\n\t#' @description\n\t#' Specify a set of parameters for the structural equation, and calculate the set of odds ratios that would be obtained, assuming the odds ratio of A on Y in the total population is 1.\n\t#' @param target_or Target odds ratio. e.g. in an observational study this OR is observed, and the researcher seeks to find parameter ranges that could explain it\n\t#' @param pS Proportion of the population present in the sample\n\t#' @param pA \\eqn{P(A = 1)} in the general population\n\t#' @param pY \\eqn{P(Y = 1)} in the general population\n\t#' @param pAY \\eqn{P(A = 1, Y = 1)} in the general population\n\t#' @param b0_range Baseline probability of being selected. Provide a range of values to explore e.g. `c(0,1)`\n\t#' @param ba_range Effect of A on being selected into the sample. Provide a range of values to explore e.g. `c(-0.2, 0.2)`\n\t#' @param by_range Effect of Y on being selected into the sample. Provide a range of values to explore e.g. `c(-0.2, 0.2)`\n\t#' @param bay_range Effect of AY interaction on being selected into the sample. Provide a range of values to explore e.g. `c(-0.2, 0.2)`\n\t#' @param granularity Granularity of the search space. Default=`100`, going much higher can be computationally difficult\n\t#' @param pS_tol Tolerance of pS value Default=`0.0025`\n\t#' @return Data frame of parameters that satisfy the `target_or` and target `pS` values\n\tparameter_space = function(target_or, pS, pA, pY, pAY, b0_range, ba_range, by_range, bay_range, granularity=100, pS_tol=0.0025)\n\t{\n\t\ts <- sign(log(target_or))\n\t\tparam <- expand.grid(\n\t\t\tpA = pA,\n\t\t\tpY = pY,\n\t\t\tpAY = pAY,\n\t\t\tb0 = seq(b0_range[1], b0_range[2], length.out=granularity) %>% unique(),\n\t\t\tba = seq(ba_range[1], ba_range[2], length.out=granularity) %>% unique(),\n\t\t\tby = seq(by_range[1], by_range[2], length.out=granularity) %>% unique(),\n\t\t\tbay = seq(bay_range[1], bay_range[2], length.out=granularity) %>% unique()\n\t\t)\n\t\tmessage(nrow(param), \" parameter combinations\")\n\t\tself$details$parameter_combinations <- nrow(param)\n\t\tparam <- param %>%\n\t\tdplyr::mutate(ps1 = self$ps_calc(b0=b0, ba=ba, pA=pA, by=by, pY=pY, bay=bay, pAY=pAY)) %>%\n\t\tdplyr::filter(ps1 >= pS - pS_tol & ps1 <= pS + pS_tol & b0 + by + ba + bay > 0) %>%\n\t\tdplyr::mutate(or = self$or_calc(b0=b0, ba=ba, by=by, bay=bay))\n\t\tmessage(nrow(param), \" within pS_tol\")\n\t\tself$details$within_ps_told <- nrow(param)\n\t\tif(target_or >= 1)\n\t\t{\n\t\t\tparam <- subset(param, or >= target_or & or < 50)\n\t\t} else {\n\t\t\tparam <- subset(param, or <= target_or & or > 0)\n\t\t}\n\t\tmessage(nrow(param), \" beyond OR threshold\")\n\t\tself$details$beyond_or <- nrow(param)\n\t\tself$param <- dplyr::as_tibble(param)\n\t},\n\n\t#' @description\n\t#' 3D scatterplot of output from `parameter_space` function. See [`plot3D::scatter3D`] for info on parameters\n\t#' @param ticktype Default=`\"detailed\"`\n\t#' @param theta Default=`130`\n\t#' @param phi Default=`0`\n\t#' @param bty Default=`\"g\"`\n\t#' @param xlab Default=`\"ba\"`\n\t#' @param ylab Default=`\"by\"`\n\t#' @param zlab Default=`\"b0\"`\n\t#' @param clab Default=`\"OR\"`\n\t#' @param ... Further parameters to be passed to [`plot3D::scatter3D`]\n\t#' @return Scatterplot\n\tscatter3d = function(ticktype=\"detailed\", theta=130, phi=0, bty=\"g\", xlab=expression(beta[A]), ylab=expression(beta[Y]), zlab=expression(beta[AY]), clab=expression(beta[0]), ...)\n\t{\n\t\tplot3D::scatter3D(x=self$param$ba, y=self$param$by, z=self$param$bay, colvar=self$param$b0, ticktype = ticktype, theta=theta, phi=phi, bty=bty, xlab=xlab, ylab=ylab, zlab=zlab, clab=clab, ...)\n\t},\n\n\t#' @description\n\t#' Simple scatterplot of output from parameter_space function. Plotted are the parameter values of `b0`, `ba` and `by` that can give rise to an OR \\eqn{\\ge} `target_or`\n\tscatter = function()\n\t{\n\t\tggplot2::ggplot(self$param, ggplot2::aes(x=ba, y=by)) +\n\t\tggplot2::geom_point(ggplot2::aes(colour=b0)) + \n\t ggplot2::xlab(expression(beta[A])) + \n \tggplot2::ylab(expression(beta[Y])) + \n \tggplot2::labs(colour = expression(beta[0]))\n\t},\n\n\t#' @description\n\t#' Histogram of odds ratios across the range of parameter values\n\t#' @param bins How many bins to split histogram. Default=`30`\n\t#'\n\t#' @return ggplot object\n\thistogram = function(bins=30)\n\t{\n\t\tggplot2::ggplot(self$param, ggplot2::aes(x=or)) +\n\t\tggplot2::geom_histogram(bins=bins) +\n\t\tggplot2::scale_x_log10() + \n\t\tggplot2::xlab(\"OR\")\n\t}\n\n))\n", "meta": {"hexsha": "cc72189331c899318cfcce68465e70ec95b2e2f5", "size": 6028, "ext": "r", "lang": "R", "max_stars_repo_path": "R/binary.r", "max_stars_repo_name": "explodecomputer/collidR", "max_stars_repo_head_hexsha": "d7f7a6dbd2f72e51d17fbed7dceb148b809acf93", "max_stars_repo_licenses": ["MIT"], "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/binary.r", "max_issues_repo_name": "explodecomputer/collidR", "max_issues_repo_head_hexsha": "d7f7a6dbd2f72e51d17fbed7dceb148b809acf93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T06:40:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T06:40:54.000Z", "max_forks_repo_path": "R/binary.r", "max_forks_repo_name": "explodecomputer/collidR", "max_forks_repo_head_hexsha": "d7f7a6dbd2f72e51d17fbed7dceb148b809acf93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-15T13:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T20:10:23.000Z", "avg_line_length": 45.6666666667, "max_line_length": 194, "alphanum_fraction": 0.6819840743, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5884532123067164}} {"text": "#-------------------------------------------------------------------\n# vtfn -- Generate spectrum of vocal tract response given formant\n# frequency, amplitude, and bandwidth.\n#\n# Args:\n# pars -- A vector of named parameters. The first parameter is the\n# number of poles and zeros described in subsequent triplets\n# (frequency, bandwidth, amplitude) of parameters. Poles are\n# distinguished from zeros by having positive instead of \n# negative frequency values.\n#\n# np -- The number of points of spectrum values to cover the\n# Nyquist range from 0 - fs/2. This is deceptive because,\n# to be consistent with FFT concentions, there will really\n# be an np+1 point spectrum returned with the first value\n# corresponding to DC and the last to the Nyquist frequency.\n#\n# fs -- Sampling frequency in Hz.\n#\n# Notes: This is the \"parallel formant\" version with each formant\n# curve calculated independently and added to the others.\n# Each formant is also multiplied by an amplitude factor\n# that is passed as a quantity in dB via the pars vector.\n# Additionally, this function called the underlying formant\n# function with scaled=TRUE so that every formant response\n# curve is generated with a theoretical peak amplitude of 1.0.\n#\n# 1/10/20 -- htb\n#-------------------------------------------------------------------\n\nvtfn2 <- function(pars, np=512, fs=16000) {\n maxf <- fs/2\n nres <- pars[1]\n s <- rep(0,np+1)\n z <- rep(1,np+1)\n for (j in seq(2,nres*3,3)) {\n af <- 10^(pars[j+2]/20)\n if (pars[j] > 0) {\n s <- s + af * formant(pars[j],pars[j+1],np,maxf)\n #cat(paste0('pole: af=',af,'; f=',pars[j],'; b=',pars[j+1],'\\n'))\n } else {\n z <- z * af / formant(pars[j],pars[j+1],np,maxf)\n #cat(paste0('zero: af=',af,'; f=',pars[j],'; b=',pars[j+1],'\\n'))\n }\n }\n s*z\n}", "meta": {"hexsha": "fc3d64125f3507384a6377c5fe5e64f90a9e4e5c", "size": 1917, "ext": "r", "lang": "R", "max_stars_repo_path": "R/vtfn2.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/vtfn2.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/vtfn2.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": 40.7872340426, "max_line_length": 71, "alphanum_fraction": 0.5821596244, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5876417772391564}} {"text": "Bio1<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-2.235282155+(2.3733*(log(DAP)))) # bs-T de alvarez et al. (en preparacion)\nBio2<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-1.544182155+(2.3733*(log(DAP)))) # bh-T de alvarez et al. (en preparacion)\nBio3<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-1.908382155+(2.3733*(log(DAP)))) # bp-T de alvarez et al. (en preparacion)\nBio4<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-1.865582155+(2.3733*(log(DAP)))) # bh-PM de alvarez et al. (en preparacion)\nBio5<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-1.662982155+(2.3733*(log(DAP)))) # bh-MB de alvarez et al. (en preparacion)\nBio6<-function(Dens=NULL,DAP,Alt=NULL,AB=NULL) exp(-2.616382155+(2.3733*(log(DAP)))) # bh-M de alvarez et al. (en preparacion)\n\nCargarIndividuos<-function(y){\ntryCatch({\nIndividuos<-read.csv(y,enc=\"latin1\")\nreturn (list(FALSE,Individuos))\n}, error = function(ex) {\nprint(\"No se pudo cargar el archivo de individuos\")\nreturn (TRUE)\n})\n}\n\nCargarParcelas<-function(x){\ntryCatch({\nParcela<-read.csv(x,enc=\"latin1\")\nreturn (list(FALSE,Parcela))\n}, error = function(ex) {\nprint(\"No se pudo cargar el archivo de parcelas\")\nreturn (TRUE)\n})\n}\n\n\norganizarInfo<-function(i,p){\ntryCatch({\nbase1<-merge(i,p)\nbase1a<-subset(base1,DAP>=10) \nbase2<-subset(base1a,Familia!=\"Arecaceae\") \nstr(base2)\nsummary(base2)\nreturn (list(FALSE,base2,base1))\n}, error = function(ex) {\nprint(\"Error en el analisis de la informacion de los archivos\")\nreturn(TRUE)\n})\n}\n\nCalculaBiomasa<-function(x){\n tryCatch({\n EcuacionesAlometricas<-c('Bio1','Bio2','Bio3','Bio4','Bio5','Bio6')\n Biomasa<-get(EcuacionesAlometricas[as.integer(x[[\"Ecuacion\"]])])(as.numeric(x[[\"Dens\"]]),\n as.numeric(x[[\"DAP\"]]),\n as.numeric(x[[\"Alt\"]]),\n as.numeric(x[[\"AB\"]]))\n return(Biomasa)\n }, error = function(ex) {\nprint(\"No se pudo realizar el calculo de la Biomasa\")\n})\n}\n\ncalcularBiomasaCarbono<-function(base2){\ntryCatch({\nbase2$BiomasaKg<-apply(base2,1,CalculaBiomasa) \nParcelasBiomasa<-aggregate(base2$BiomasaKg/((base2$Area*10000)/10),list(Plot=base2[,\"Plot\"]),sum,na.rm=TRUE)\n#base3<-merge(Parcela,ParcelasBiomasa)\nbase3<-merge(base1,ParcelasBiomasa)\nbase3$Biomasa<-base3$x\nbase3$Carbono<-base3$Biomasa*0.5\nbase4<-subset(base3,select=c(Plot,FID,DAP,Familia,Area,Bosque,Ecuacion,Biomasa,Carbono))\nreturn(list(FALSE,base4,ParcelasBiomasa))\n}, error = function(ex) {\nprint(\"Error al realizar el calculo de la biomasa y el carbono\")\nreturn (TRUE)\n})\n}\n\ncargarExtremeValues<-function(){\ntryCatch({\n library(extremevalues)\n return(FALSE)\n}, error = function(ex) {\n return(TRUE)\n})\n}\n\nAtipicos<-function(p,x,y)\n{\ntryCatch({\nbase3<-merge(p,x)\nParcelaBiomasa<-subset(y,select=c(Plot,Area,Bosque,Biomasa))\nlognormal<-getOutliersII(ParcelaBiomasa$Biomasa,distribution=\"lognormal\")\nParcelaSinOuts<-ParcelaBiomasa[-c(lognormal$iRight,lognormal$iLeft),]\nreturn(list(FALSE,ParcelaBiomasa,ParcelaSinOuts))\n\t}, error = function(ex) {\nprint(\"Error realizando el calculo de los datos Atipicos\");\nreturn (TRUE)\n})\n}\n\nvar.wtd.mean.cochran <- function(x,w,na.rm=TRUE)\n{\n if (na.rm){\n x<-x[!is.na(w)]\n w<-w[!is.na(w)]\n }\n\tn = length(w)\n\txWbar = weighted.mean(x,w)\n\twbar = mean(w)\n\tout = n/((n-1)*sum(w)^2)*(sum((w*x-wbar*xWbar)^2)-2*xWbar*sum((w- wbar)*(w*x-wbar*xWbar))+xWbar^2*sum((w-wbar)^2))\n\treturn (out)\n}\n\nAtipicosTodos<-function(ParcelaBiomasa){\ntryCatch({\nvarzas<-with(ParcelaBiomasa,tapply(Biomasa,list(Bosque,Area),var))\ndesv.estand<-with(ParcelaBiomasa,tapply(Biomasa,list(Bosque),sd))\nns1<-with(ParcelaBiomasa,tapply(Biomasa,list(Bosque),length))\nponderaciones<-(1/varzas)/apply((1/varzas),1,sum,na.rm=TRUE)\napply(ponderaciones,1,sum,na.rm=TRUE)\nmedias1<-with(ParcelaBiomasa,tapply(Biomasa,list(Bosque,Area),mean))\nmedias2<-apply(medias1*ponderaciones,1,sum,na.rm=TRUE)\nmedias3<-with(ParcelaBiomasa,tapply(Biomasa,Bosque,mean))\nsec1<-1:nrow(medias1)\nvar.wtd.media<-function(i,medias,varianzas,na.rm=TRUE){\n var.wtd.mean.cochran(medias1[i,],1/varianzas[i,],na.rm=TRUE)\n }\nr1<-sapply(sec1,var.wtd.media,medias1,varzas)\n\nSalidaTodos<-data.frame(ns=ns1,\n media_w=medias2,desv.estand_w=sqrt(r1),\n CV_w=sqrt(r1)/medias2*100,\n IC_w=1.96*sqrt(r1))\nreturn (list(FALSE,SalidaTodos))\n}, error = function(ex) {\nprint(\"No se pudo realizar el analisis de los Valores Atipicos\")\nreturn (TRUE)\n})\t\t\t\t \n}\n\nAtipicosSin<-function(ParcelaSinOuts){\ntryCatch({\nvarzas<-with(ParcelaSinOuts,tapply(Biomasa,list(Bosque,Area),var))\ndesv.estand<-with(ParcelaSinOuts,tapply(Biomasa,list(Bosque),sd))\nns1<-with(ParcelaSinOuts,tapply(Biomasa,list(Bosque),length))\nponderaciones<-(1/varzas)/apply((1/varzas),1,sum,na.rm=TRUE)\napply(ponderaciones,1,sum,na.rm=TRUE)\nmedias1<-with(ParcelaSinOuts,tapply(Biomasa,list(Bosque,Area),mean))\nmedias2<-apply(medias1*ponderaciones,1,sum,na.rm=TRUE)\nmedias3<-with(ParcelaSinOuts,tapply(Biomasa,Bosque,mean))\nsec1<-1:nrow(medias1)\nvar.wtd.media<-function(i,medias,varianzas,na.rm=TRUE){\n var.wtd.mean.cochran(medias1[i,],1/varianzas[i,],na.rm=TRUE)\n }\nr1<-sapply(sec1,var.wtd.media,medias1,varzas)\n\nSalidaSinOuts<-data.frame(ns=ns1,\n media_w=medias2,desv.estand_w=sqrt(r1),\n CV_w=sqrt(r1)/medias2*100,\n IC_w=1.96*sqrt(r1))\nreturn (list(FALSE,SalidaSinOuts))\n}, error = function(ex) {\nprint(\"No se pudo realizar el analisis de los Valores Atipicos\")\nreturn (TRUE)\n})\n}", "meta": {"hexsha": "87d331f02f05b6cf5ba947a489f444df22712a39", "size": 5376, "ext": "r", "lang": "R", "max_stars_repo_path": "MonitoreoBC-EJB/ejbModule/co/gov/ideamredd/reportes/biomasa/EcuacionesBiomasa.r", "max_stars_repo_name": "danielrcardenas/mapas_ideam", "max_stars_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-03T09:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T09:29:34.000Z", "max_issues_repo_path": "ReportesMonitoreo-EJB/ejbModule/co/gov/ideamredd/biomasa/EcuacionesBiomasa.r", "max_issues_repo_name": "danielrcardenas/mapas_ideam", "max_issues_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ReportesMonitoreo-EJB/ejbModule/co/gov/ideamredd/biomasa/EcuacionesBiomasa.r", "max_forks_repo_name": "danielrcardenas/mapas_ideam", "max_forks_repo_head_hexsha": "e2bb4235621aa789d8af9758a91e0ac05c622607", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6, "max_line_length": 127, "alphanum_fraction": 0.712983631, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5874704358429028}} {"text": "2 + 2\n10/3\n\nv = c(1, 4, 5, 3, 7)\nv <- c(1, 4, 5, 3, 7)\nclass(v)\nsum(v)\nmean(v)\nlength(v)\nmax(v)\nv[1]\nv[3:5]\nv[-(2:3)]\nv^2\nexp(v)\nv[v >= 3]\nsum(v >= 3)\nsum(v >= 3)/2\n\n\n\n\nn = 10\nk = 5 \nsqrt(n)\nlog(n)\nexp(-k)\nfactorial(n)\nchoose(n,k)\nsample(n)\nsample(n,replace=TRUE)\nsample(4, 3, replace=TRUE, prob=c(0.1,0.2,0.3,0.4)) #samples three numbers between 1 and 4, with replacement, and with probabilities given by (0.1,0.2,0.3,0.4)\nreplicate(5,c(1:3))\nprod(c(2, 4, 5))\n\n\nx = c(1:10)\ny = x*x\nplot(x, y, type=\"l\")", "meta": {"hexsha": "c8a900121d5f77ea637537a14f65e005e22db15b", "size": 503, "ext": "r", "lang": "R", "max_stars_repo_path": "files/stat345/basic_R.r", "max_stars_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_stars_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T03:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T14:15:29.000Z", "max_issues_repo_path": "files/stat345/basic_R.r", "max_issues_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_issues_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/stat345/basic_R.r", "max_forks_repo_name": "anastasiiakim/anastasiiakim.github.io", "max_forks_repo_head_hexsha": "83aad58339ba629dd4e63ffb833d1ec5a172ad12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T06:27:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T06:27:06.000Z", "avg_line_length": 12.8974358974, "max_line_length": 159, "alphanum_fraction": 0.5705765408, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5871223854726066}} {"text": "#' Multivariate normal mixture conditional likelihood model\n#'\n#' Gibbs sampling from the multivariate normal mixture conditional likelihood \n#' model.\n#' \n#' @param y_train factor. Categorical response in the train data.\n#' @param s_train matrix. Probabilistic predictions of candidate models for \n#' train data, binded by columns.\n#' @param s_test matrix. Probabilistic predictions of candidate models for test \n#' data, binded by columns.\n#' @param n_c numeric. Number of classes of the response.\n#' @param n_s numeric. Number of candidate models.\n#' @param iter numeric. Number of iterations for Gibbs sampling.\n#' @param n_g numeric. Number of mixtures at the beginning of Gibbs sampling. \n#' Redundant mixtures will collapse during sampling.\n#' @param invalog logical. If TRUE, transform s_train and s_test with the \n#' inverse logistic transformation. Defaults to TRUE.\n#' @param prior_s2 numeric. Prior on the diagonal of the inverse-Wishart scale \n#' matrix for covariance matrices.\n#' @param prior_mu numeric. Prior on the means of latent multivariate normal \n#' distributions.\n#' @param prior_nu numeric. Prior on the inverse-Wishart degrees of freedom for \n#' covariance matrices.\n#'\n#' @return Matrix with posterior means of probabilistic predictions for each \n#' test observation. The number of columns is n_c and the number of rows is the \n#' same as nrow(s_test).\n#'\n#' @examples\n#' set.seed(1)\n#' n <- 1000\n#' t <- sample(1:2, n, replace = T)\n#' M1 <- vector(mode = \"numeric\", length = n)\n#' M2 <- vector(mode = \"numeric\", length = n)\n#' \n#' nt1 <- sum(t == 1)\n#' nt2 <- n - nt1\n#' \n#' # Candidate model predictions\n#' # M1: systematic error\n#' # M2: random\n#' M1[t == 1] <- rbeta(nt1, 1, 2)\n#' M2[t == 1] <- rbeta(nt1, 2, 2)\n#' M1[t == 2] <- rbeta(nt2, 2, 1)\n#' M2[t == 2] <- rbeta(nt2, 1, 1)\n#' \n#' p <- matrix(c(M1, 1-M1, M2, 1-M2), ncol = 4)\n#' train_ind <- 1:500\n#' test_ind <- 501:1000\n#' \n#' t_train <- t[train_ind]\n#' t_test <- t[test_ind]\n#' p_train <- p[train_ind, ]\n#' p_test <- p[test_ind, ]\n#' \n#' MM_fit <- model_MM(t_train, p_train, p_test, n_c = 2, n_s = 2)\n#' \n#' \n#' @references Pirs, G. and Strumbelj, E. (2019). Bayesian Combination of \n#' Probabilistic Classifiers using Multivariate Normal Mixtures. Journal of \n#' Machine Learning Research, 20, 51-1.\n#'\n#' @export\nmodel_MM <- function (y_train, s_train, s_test, n_c, n_s,\n iter = 100, \n n_g = 15,\n invalog = T,\n regularize = F,\n # priors\n prior_s2 = 100,\n prior_mu = 0,\n prior_nu = 2 + (n_c - 1) * n_s\n) {\n library(mvtnorm)\n library(MASS)\n \n invalog_transform <- function (x, n_s, n_c) {\n for (i in 1:n_s) {\n lo <- (i-1)*n_c + 1\n hi <- (i-1)*n_c + n_c\n x[,lo:hi] <- x[,lo:hi] + runif(nrow(x[,lo:hi]) * ncol(x[,lo:hi]), 0.00,0.001)\n x[,lo:hi] <- x[,lo:hi] / rowSums(x[,lo:hi])\n \n for (j in 1:n_c) {\n x[ ,(i-1)*n_c + j] <- log(x[ ,(i-1)*n_c + j] / x[ ,(i-1)*n_c+n_c])\n }\n }\n x[,(1:ncol(x) %% n_c) != 0]\n }\n \n vec_prod <- function(vec) {return(vec %*% t(vec))}\n \n to_matrix <- function(vec) {return(matrix(vec, \n ncol = sqrt(length(vec)), \n byrow = TRUE))}\n \n sum_na <- function (my_vec) {return (sum(is.na(my_vec)))}\n if (invalog) {\n t_train <- invalog_transform(s_train, n_s, n_c)\n t_test <- invalog_transform(s_test, n_s, n_c)\n } else {\n x <- seq(1, ncol(s_train), n_c)\n t_train <- s_train[,-x]\n t_test <- s_test[,-x]\n }\n t_all <- rbind(t_train, t_test)\n \n collapsed <- array(F, dim = c(n_c, n_g)) \n \n # priors ----\n nu_0 <- prior_nu\n Sigma_0 <- diag(prior_s2, ncol(t_train))\n S_0 <- diag(prior_s2, ncol(t_train))\n mu_0 <- rep(prior_mu, ncol(t_train))\n invSigma_0 <- solve(Sigma_0) # Prepare the inverse of the prior.\n \n # parameters ----\n par_y_test <- array(NA, dim = c(iter+1, nrow(t_test)))\n par_p_test <- array(NA, dim = c(iter+1, nrow(t_test), n_c))\n par_predict<- array(NA, dim = c(iter+1, nrow(t_test), n_c))\n par_group <- array(NA, dim = c(iter+1, nrow(t_test) + nrow(t_train)))\n par_mu <- array(NA, dim = c(iter+1, n_c, n_g, ncol(t_train)))\n par_invSigma <- array(NA, dim = c(iter+1, n_c, n_g, ncol(t_train), ncol(t_train)))\n \n \n # assignment of starting values ----\n par_y_test[1,] <- sample(1:n_c, nrow(t_test), rep = T)\n par_group[1,] <- sample(1:n_g, nrow(t_test) + nrow(t_train), rep = T)\n \n par_mu[1,,,] <- 0\n for (j in 1:n_c) {\n for (k in 1:n_g) {\n par_invSigma[1,j,k,,] <- diag(ncol(t_train))\n }\n }\n \n COMPLETE_DATA <- F\n \n # main loop ----\n for (i in 2:(iter + 1)) { \n cat(i, \" \")\n\n y_all <- c(y_train, par_y_test[i-1,])\n # mu and Sigma ----\n for (j in 1:n_c) {\n # collapse groups\n for (k in n_g:1) {\n \n if (COMPLETE_DATA) {\n if (sum(par_group[i-1,] == k & y_all == j) <= 1) {\n collapsed[j,k] <- T\n }\n } else {\n if (sum(par_group[i-1,1:length(y_train)][y_train == j] == k) <= 1) {\n collapsed[j,k] <- T\n } \n }\n }\n\n \n # sample new params\n for (k in 1:n_g) if (!collapsed[j,k]) {\n\n # get data for this class and this group\n if (COMPLETE_DATA) {\n tmp_t_all <- t_all[y_all == j & par_group[i - 1, ] == k,]\n } else {\n tmp_t_all <- t_train[y_train == j & par_group[i-1,1:length(y_train)] == k,]\n }\n \n n_j <- nrow(tmp_t_all)\n \n # Get values from the previous iteration.\n invSigma_j <- par_invSigma[i-1,j,k,,]\n mu_j <- par_mu[i-1,j,k,] \n Sigma_n <- solve(invSigma_0 + n_j*invSigma_j)\n umean <- colMeans(tmp_t_all)\n \n \n mu_n <- Sigma_n %*% (invSigma_0 %*% mu_0 + \n n_j * invSigma_j %*% umean)\n mu_j <- mvrnorm(1, mu_n, Sigma_n)\n nu_n <- nu_0 + n_j\n mu_mat <- matrix(rep(mu_j, n_j), ncol = length(mu_j), byrow=TRUE)\n ecm <- t(as.matrix(tmp_t_all - mu_mat))\n ecm <- apply(ecm, 2, vec_prod)\n ecm <- rowSums(ecm)\n ecm <- matrix(ecm, ncol = length(mu_j), byrow = TRUE)\n S_n <- S_0 + ecm\n invSigma_j <- rWishart(1, nu_n, solve(S_n))[,,1]\n \n # Insert new values into the current iteration.\n \n par_mu[i,j,k,] <- mu_j\n par_invSigma[i,j,k,,] <- invSigma_j\n }\n }\n \n # groups ----\n par_group[i,] <- par_group[i-1,]\n group_all <- par_group[i,1:length(y_train)]\n g_probs <- array(0, dim = c(nrow(t_train), n_g))\n for (j in 1:n_c) {\n idxs <- y_train == j\n tmp_t_all <- t_train[idxs,]\n for (k in 1:n_g) if (!collapsed[j,k]) {\n mu <- par_mu[i,j,k,]\n Sigma <- solve(par_invSigma[i,j,k,,])\n g_probs[idxs,k] <- dmvnorm(tmp_t_all, mean = mu, sigma = Sigma) \n }\n }\n\n g_probs <- g_probs / rowSums(g_probs)\n par_group[i,1:length(y_train)] <- apply(g_probs, 1, function(x){sample(1:n_g, 1, prob = x)})\n\n get_pred <- function(t_test, y_all, n_c, n_g, collapsed, par_mu, par_invSigma, group_all, lambda = rep(0, ncol(t_test))) {\n pred <- array(0, dim = c(nrow(t_test), n_c, n_g))\n for (j in 1:n_c) {\n for (k in 1:n_g) if (!collapsed[j,k]) {\n mu <- par_mu[i,j,k,]\n Sigma <- solve(par_invSigma[i,j,k,,]) + diag(lambda)\n \n pred[,j,k] <- dmvnorm(t_test, mean = mu, sigma = Sigma) * sum(group_all == k & y_all == j)\n }\n }\n\n pred <- sweep(pred, 1, apply(pred, 1, sum), FUN=\"/\")\n }\n pred <- get_pred(t_test, y_train, n_c, n_g, collapsed, par_mu, par_invSigma, par_group[i,1:length(y_train)])\n tmp <- apply(pred, 1, function(x){sample(1:(n_c * n_g), 1, prob = c(x))})\n par_y_test[i,] <- (tmp - 1) %% n_c + 1\n par_group[i,(length(y_train) + 1):length(par_group[i,])] <- floor((tmp - 1) / n_c) + 1\n\n # regularize\n fn_optim <- function(x, t_train, y_train, n_c, n_g, collapsed, par_mu, par_invSigma, par_group) {\n pred <- get_pred(t_train, y_train, n_c, n_g, collapsed, par_mu, par_invSigma, par_group, lambda = x)\n pred <- apply(pred, c(1,2), sum)\n p_star <- pred[cbind(1:nrow(pred), y_train)]\n -mean(log(p_star))\n }\n \n if (regularize) {\n lambda <- rep(0, ncol(t_train))\n idx <- sample(1:length(y_train), 100, rep = T)\n lambda_max <- 100000\n res <- optim(lambda, fn = fn_optim, \n lower = rep(0, length(lambda)),\n upper = rep(lambda_max, length(lambda)),\n method = \"L-BFGS-B\", #control = list(trace = 1),\n t_train = t_train[idx,], y_train = y_train[idx], n_c = n_c,\n n_g = n_g, collapsed = collapsed, par_mu = par_mu, par_invSigma = par_invSigma, par_group = par_group[i,1:length(y_train)][idx])\n \n pred <- get_pred(t_test, y_train, n_c, n_g, collapsed, par_mu, par_invSigma, par_group[i,1:length(y_train)], lambda = res$par)\n par_predict[i,,] <- apply(pred, c(1,2), sum)\n \n } else {\n par_predict[i,,] <- apply(pred, c(1,2), sum)\n }\n }\n cat(\"\\n\")\n \n return(pred = apply(par_predict[-1,,], c(2,3), mean))\n}", "meta": {"hexsha": "3da53c3d3118ec0dd220b3e4f0b8e1990deee7b6", "size": 9470, "ext": "r", "lang": "R", "max_stars_repo_path": "R/model_MM.r", "max_stars_repo_name": "gregorp90/MM", "max_stars_repo_head_hexsha": "97d9367aa5def64bf83df942430cf1479355b07b", "max_stars_repo_licenses": ["MIT"], "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/model_MM.r", "max_issues_repo_name": "gregorp90/MM", "max_issues_repo_head_hexsha": "97d9367aa5def64bf83df942430cf1479355b07b", "max_issues_repo_licenses": ["MIT"], "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/model_MM.r", "max_forks_repo_name": "gregorp90/MM", "max_forks_repo_head_hexsha": "97d9367aa5def64bf83df942430cf1479355b07b", "max_forks_repo_licenses": ["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.0076045627, "max_line_length": 147, "alphanum_fraction": 0.5468848997, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5871223843896979}} {"text": "#\tfunctions to calculate paleoflow depth from preserved cross-sets.\n#\tEric Barefoot\n#\tNov 2017\n#\n#\tlargely taken from work by Suzanne Leclair, Chris Paola and methods in a review paper by Bradley and Venditti\n\n#\tfirst step is to relate the cross-set (xset) thickness to dune height (H)\n\n#\trequire packages\n\n# require(stats4)\n\n#' Dune height calculation from cross-set thicknesses\n#'\n#' \\code{xset2H} takes measured cross-set thicknesses (\\code{y}) and converts it to dune heights (H).\n#'\n#' @param y \tA vector of measured cross-set thicknesses in meters.\n#' @param mode\tTakes two values: \\code{simple} and \\code{pdfFit}. \\code{simple} uses a simple approximation to determine the beta value in Leclair's equation relating x-sets to dune heights. \\code{pdfFit} uses a more complicated procedure, fitting a PDF from Paola + Borgman to get the beta value. \\code{pdfFit} is better suited when there are adequate data to estimate the distribution.\n#' @param output \tTakes two values: \\code{vanilla} and \\code{rich}. \\code{vanilla} only returns the estimated value of \\code{H}, or dune height. \\code{rich} returns \\code{H}, as well as \\code{beta} and either \\code{startVal} which is the inital guess of a for the MLE algorithm in \\code{pdfFit}, or a span of \\code{H} values giving a reasonable range of one particular assumption.\n#' @return Either a single numeric if \\code{output = vanilla}, or a list if \\code{output = rich}.\n#' @export\n\nxset2H = function(y, mode = 'simple', output = 'vanilla') {\n\n\t#\tfunction takes two modes: 'simple' and 'pdfFit'\n\t#\ty is a vector of cross-set thicknesses -- MUST BE IN METERS\n\n\ty = y * 1000 # \tconvert to millimeters\n\n\t#\tgives output in meters\n\n\tn = length(y)\n\n\t#\tfirst a function to estimate the average dune height via fitting a PDF of x-set thicknesses to find the right parameters\n\tpdfFit = function(y) {\n\n\t\t#\tdefine the probability density function from Paola and Borgman\n\t\tpfun = function(a,s) {\n\t\t\tp = a * exp(-a*s) * (exp(-a*s) + a * s - 1) / (1 - exp(-a*s))^2\n\t\t\treturn(p)\n\t\t}\n\n\t\t#\tconstruct a likelihood function which takes data as an external argument and the parameter as the internal argument.\n\t\tloglikely = function(data) {\n\t\t\tfunction(a) {\n\t\t\t\tR = R = pfun(a, data)\n\t\t\t\t-sum(log(R))\n\t\t\t}\n\t\t}\n\n\t\t#\tconstruct likelihood function for these data.\n\t\tLL = loglikely(y)\n\n\t\t#\tdefault starting a value for fitting\n\t\t#\tand error handling sequence for finding an inital guess value for that works and doesnt crash the MLE.\n\t\tworked = FALSE\n\t\tstartVal = 1\n\t\ttry(stop(''), silent = T)\n\t\tj = 1\n\t\twhile (!worked) {\n\n\t\t\ttry_MLE = try(coef(mle(minuslogl = LL, start = list(a = startVal))), silent = T)\n\n\t\t\tif (class(try_MLE) == 'try-error' & j < 1000) {\n\n\t\t\t\toptions(warn = -1)\n\t\t\t\tmsg = as.character(try_MLE)\n\n\t\t\t\tif (grepl('initial value', msg)) {\n\t\t\t\t\tstartVal = startVal / 2\n\t\t\t\t\tj = j + 1\n#\t\t\t\t\tmessage(paste(startVal))\n\t\t\t\t} else {\n\t\t\t\t\tstop('Something else happened, its real bad')\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tworked = TRUE\n\n\t\t\t}\n\t\t}\n\n\t\t#\testimate parameter using MLE function\n\t\ta = coef(mle(minuslogl = LL, start = list(a = startVal)))\n\n\t\t#\tget beta a la Leclair et al. 0.9 is for dune height/scour correction\n\t\tbeta = 0.9/a\n\n\t\t#\tget dune height from beta from Leclair et al. two ways.\n#\t\tH = 2.22 * beta ^ 1.32\n\t\tH = 5.3 * beta + 0.001 * beta ^ 2\n\n\t\tlist(H = as.numeric(H) / 1000, beta = as.numeric(beta), startVal = startVal)\n\t}\n\n\t#\tHere, a simpler function using only the empirical estimations made by Leclair et al.\n\tsimple = function(y) {\n\t\tsm = mean(y, na.rm = T) #\tfind average set thickness\n\t\thsd_tssd = seq(from = 0.7, to = 1.1, by = 0.1) #\tfind ratio of scour deviation to height deviation. supposedly an average of 0.9, but ranges randomly from 0.7 to 1.1 this function spits out a range.\n\t\tbeta = sm / (1.64493 / hsd_tssd) #\tuse that to calculate beta\n#\t\tbeta = sm / 1.8\n\n#\t\tH = 2.22 * beta ^ 1.32\n\t\tH = 5.3 * beta + 0.001 * beta ^ 2 #\tuse same equation as in pdfFit to get the average height\n\n\t\tlist(H = mean(H) / 1000, beta = as.numeric(beta), vecH = H / 1000)\n\t}\n\n\t#\toffer some recommendations to the user.\n\tif(n >= 25 & mode == 'simple') {\n\n\t\tmessage('this dataset may benefit from running a more complicated PDF based function.')\n\n\t\tH = simple(y)\n\n\t} else if (n < 25 & mode == 'simple' ) {\n\n\t\tH = simple(y)\n\n\t} else if (n < 25 & mode == 'pdfFit') {\n\n\t\tmessage('this dataset is small, and may benefit from running a less complicated empirical.')\n\n\t\tH = pdfFit(y)\n\n\t} else if (n >= 25 & mode == 'pdfFit') {\n\n\t\tH = pdfFit(y)\n\n\t}\n\n\tswitch(output ,\n\t\t vanilla = return(H$H),\n\t\t rich = return(H)\n\t\t )\n}\n\n#' Paleo-depth calculation from dune height\n#'\n#' \\code{H2h} takes estimated dune heights (H) and calculates a flow depth.\n#'\n#' @param H \tA vector of measured cross-set thicknesses in meters.\n#' @param CL\tA pre-specified confidence level. If you pick a low confidence (50\\%), the range in estimated flow depth will be smaller.\n#' @param output \tTakes two values: \\code{vanilla} and \\code{rich}. \\code{vanilla} only returns the estimated value of \\code{h}. \\code{rich} returns \\code{h}, as well as \\code{CI}, the confidence interval around the \\code{h} estimate.\n#' @return Either a single numeric if \\code{output = vanilla}, or a list if \\code{output = rich}.\n#' @export\n\n#\tsecond step is to relate the dune height to the flow depth, following Bradley and Venditti\n\nH2h = function(H, CL = 50, output = 'vanilla') {\n\n\t#\tH is the height of a dune in meters.\n\t#\tor if H is a vector, it is a set of dune heights\n\t#\tCL is the confidence level in percent\n\n\t#\tconfidence ranges\n\n\tCR = data.frame(CL = c(50, 80, 90, 95), upper = c(10.1, 14.6, 23.9, 29.5), lower = c(4.4, 3.1, 2.8, 2.7))\n\n\tCind = which.min(abs(CR$CL - CL)) # match closest one from the table\n\n\th = 6.7 * H\t#\tusing the median parameter from Bradley and Venditti\n\n\tCI = list(upper = H * CR$upper[Cind], lower = H * CR$lower[Cind]) # and based on Confidence Level, assign bounds of confidence\n\n\treturnval = switch(output ,\n\t\t\t\t\t vanilla = return(h),\n\t\t\t\t\t rich = return(list(h = h, CI = CI))\n\t\t\t\t\t )\n}\n\n#\tand now a function that combines both into one function, so you can go straight from xsets to flow depth with no extra frills, or depth\n\n#' Paleo-depth calculation from cross-set thicknesses\n#'\n#' \\code{xset2depthSimple} uses the simplest implementation of both \\code{xset2H} and \\code{H2h}. It uses the vanilla options of each one and spits out an estimate of paleo-depth based on the defaults. Look in the code for the other functions to see what those defaults are.\n#' @param y \tA vector of measured cross-set thicknesses in meters.\n#' @return The paleo-depth estimate in meters.\n#' @export\n\nxset2depthSimple = function(y) {\n\n\t#\ty is a vector of thicknesses of xsets in meters\n\n\tH = xset2H(y)\n\n\th = H2h(H)\n\n\treturn(h)\n\n}\n", "meta": {"hexsha": "89395a2023e157d757f0ffc26a89637f57587df7", "size": 6747, "ext": "r", "lang": "R", "max_stars_repo_path": "R/paleo_depth.r", "max_stars_repo_name": "ericbarefoot/barefootr", "max_stars_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_stars_repo_licenses": ["MIT"], "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/paleo_depth.r", "max_issues_repo_name": "ericbarefoot/barefootr", "max_issues_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_issues_repo_licenses": ["MIT"], "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/paleo_depth.r", "max_forks_repo_name": "ericbarefoot/barefootr", "max_forks_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_forks_repo_licenses": ["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.9585492228, "max_line_length": 388, "alphanum_fraction": 0.6786720024, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5869523191922813}} {"text": "#' @title Calculate probability based on zero inflated generalized Dirichlet-multinomial distribution\n#'\n#' @description\n#' This function estimates parameters from zero inflated generalized Dirichlet-multinomial distribution, and test the pro.\n#' @param Y Count table of microbiome\n#' @param Xc design matrices for probability of absence model. The first column should contain \"1\" for the intercept. For intercept only model, the three matrices are simply contain vectors of 1.\n#' @param Xa design matrices for mean model. The first column should contain \"1\" for the intercept. For intercept only model, the three matrices are simply contain vectors of 1.\n#' @param Xb design matrices for dispersion model. The first column should contain \"1\" for the intercept. For intercept only model, the three matrices are simply contain vectors of 1.\n#' @param c0 c0: initial values for regression coefficients \"c\" organized in a matrix (dim: K x d, K+1 is the #taxa (i.e. K+1 = ncol(Y)), d is the number of columns in the corresponding design matrix)\n#' @param alpha0: initial values for regression coefficients \"alpha\" organized in a matrix (dim: K x d)\n#' @param beta0: initial values for regression coefficients \"beta\" organized in a matrix (dim: K x d)\n#' @param tol: convergence tolerance\n#' @param max.iter: maximum number of iterations\n\n#' @return A vector containning the probablity of multinomial distribution\n#' @export\n#' @examples\n####estimate probability of of absent matrix, mean and dispersion matrix from Y based on ZIGDM model\n###Test_result <- ZIGDM.EM.PAR2(Y=Y, Xc=Xc, Xa=Xa, Xb=Xb, c0=c0, alpha0=alpha0, beta0=beta0, tol=tol, max.iter=max.iter)\n#### using probability of of absent matrix to random generate present and absent value\n\n\nZIGDM_prob <- function(Test_result, row) {\n ####row is Xc[1,]\n Delta <- Bernoulli(c.est = Test_result$c.est, row = row)\n #### based on Delta, generate Z, row2 is Xa[1,], row3 is Xb[1,]. since Xc[1,]=Xa[1,]=Xb[1,],row is used for all\n Z_value <- Zvalue_Generator(Delta = Delta, Test_result = Test_result, row2 = row, row3 = row)\n #### based on Z, generate p vector for multinomial\n\n MultinomialP <- multinormial_P(Z=Z_value)\n MultinomialP[length(MultinomialP)+1] <- 1- sum(MultinomialP) #### add the K+1 taxa back\n\n return (MultinomialP)\n\n #probability = apply(Y,1,dmultinom, prob = MultinomialP)\n\n #return (probability)\n}\n\n", "meta": {"hexsha": "72e2a2b5f630d204a4b57fcecae05599101e8bbd", "size": 2378, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ZIGDM_prob.r", "max_stars_repo_name": "qunfengdong/BioMarkerClassifier", "max_stars_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_stars_repo_licenses": ["MIT"], "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/ZIGDM_prob.r", "max_issues_repo_name": "qunfengdong/BioMarkerClassifier", "max_issues_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_issues_repo_licenses": ["MIT"], "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/ZIGDM_prob.r", "max_forks_repo_name": "qunfengdong/BioMarkerClassifier", "max_forks_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.45, "max_line_length": 200, "alphanum_fraction": 0.7422203532, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5869503122354726}} {"text": "# ----------------------------------------\n# App Title: Chaos Game -- 2 Dimensions\n# Author: Jimmy Doi\n# ----------------------------------------\n\nlibrary(shiny)\nlibrary(shinyBS)\nlibrary(shape)\n\n###################################################################\n# Triangle\n###################################################################\n\ntri.gen <- function(wt){\n \tweight <- wt\n\t\t\n\t\tlen <- 50000\n\t\t\n # loci matrix to contain all endpoints\n\t\tloci <- matrix(NA,ncol=3,nrow=3)\n\t\t\n\t\tloci[1,] <- c(1,0,0)\n\t\tloci[2,] <- c(2,0.5,sqrt(3)/2)\n\t\tloci[3,] <- c(3,1,0)\n\n # vertices contains all random vertex points\n vertices <- runif(len)\n\t\tvertices[which(vertices>2/3)]<- 3\n\t\tvertices[which(1/37/8)]<- 8\n \tvertices[which(6/84/5)]<- 5\n \tvertices[which(3/55/6)]<- 6\n vertices[which(4/6-1)))\n }\n if (input$shape == \"sqr\") {\n return(sqr.gen(input$dist.sqr*(input$gen>-1)))\n }\n if (input$shape == \"pent\") {\n return(pent.gen(input$dist.pent*(input$gen>-1)))\n }\n if (input$shape == \"hex\") {\n return(hex.gen(input$dist.hex*(input$gen>-1)))\n }\n }) \n \n\n##################################\n# initPlot #\n##################################\n\n output$initPlot <- renderPlot({\n \n loci <- all.list()[[1]]\n vertices <- all.list()[[2]]\n coords <- all.list()[[3]]\n \n #############################\n # Triangle:INIT #\n #############################\n if (input$shape == \"tri\") {\n \n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,sqrt(3)/2),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n \n \n if (!is.null(input$init)) {\n if (input$init==1) {\n points(coords[1,1],coords[1,2],pch=20,cex=3,col=\"blue\") \n \n if (coords[1,1]>=0.5 & coords[1,2]<=sqrt(3)/4) {\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]>=0.5 & coords[1,2]>sqrt(3)/4) {\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]<0.5 & coords[1,2]>sqrt(3)/4) {\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n if (coords[1,1]<0.5 & coords[1,2]<=sqrt(3)/4) {\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n }\n }\n }\n \n #############################\n # Square:INIT #\n #############################\n if (input$shape == \"sqr\") {\n \n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n\n if (input$init==1) {\n points(coords[1,1],coords[1,2],pch=20,cex=3,col=\"blue\") \n \n if (coords[1,1]>=0.5 & coords[1,2]<=0.5) { # LOWER RIGHT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]>=0.5 & coords[1,2]>0.5) { # UPPER RIGHT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]<0.5 & coords[1,2]>0.5) { # UPPER LEFT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n if (coords[1,1]<0.5 & coords[1,2]<=0.5) { # LOWER LEFT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n }\n }\n \n #############################\n # Pentagon:INIT #\n #############################\n if (input$shape == \"pent\") {\n \n c1 <- 0.25*(sqrt(5)-1)\n c2 <- 0.25*(sqrt(5)+1)\n s1 <- 0.25*(sqrt(10+2*sqrt(5)))\n s2 <- 0.25*(sqrt(10-2*sqrt(5)))\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-s1,s1),ylim=c(-c2,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n\n if (input$init==1) {\n points(coords[1,1],coords[1,2],pch=20,cex=3,col=\"blue\") \n \n if (coords[1,1]>=0 & coords[1,2]<=0) { # LOWER RIGHT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]>=0 & coords[1,2]>0) { # UPPER RIGHT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]<0 & coords[1,2]>0) { # UPPER LEFT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n if (coords[1,1]<0 & coords[1,2]<=0) { # LOWER LEFT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n }\n }\n\n #############################\n # Hexagon:INIT #\n #############################\n if (input$shape == \"hex\") {\n \n alpha <- 0.5\n beta <- sqrt(3)/2\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-beta,beta),ylim=c(-2*alpha,2*alpha),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n\n if (input$init==1) {\n points(coords[1,1],coords[1,2],pch=20,cex=3,col=\"blue\") \n \n if (coords[1,1]>=0 & coords[1,2]<=0) { # LOWER RIGHT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]>=0 & coords[1,2]>0) { # UPPER RIGHT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=2)\n }\n if (coords[1,1]<0 & coords[1,2]>0) { # UPPER LEFT\n text(coords[1,1],coords[1,2]-0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n if (coords[1,1]<0 & coords[1,2]<=0) { # LOWER LEFT\n text(coords[1,1],coords[1,2]+0.04,\"Random Starting Point\",col=\"blue\",pos=4)\n }\n }\n }\n ##################################################################################\n ### APPLIED TO ALL \n\n if (!is.null(input$init)) {\n if (input$init!=1) {\n points(coords[1:input$init-1,1],coords[1:input$init-1,2],pch=20,cex=1,col=\"blue\") \n \n points(coords[input$init-1,1],coords[input$init-1,2],pch=20,cex=2.75,col=\"blue\") \n points(coords[input$init,1],coords[input$init,2],pch=21,cex=3,col=\"blue\",bg=\"white\") \n points(coords[input$init,1],coords[input$init,2],pch=20,cex=2.75,col=\"blue\") \n \n x0 <- coords[input$init-1,1]\n y0 <- coords[input$init-1,2]\n x1 <- coords[input$init,1]\n y1 <- coords[input$init,2]\n \n Arrows((.6*x0+.4*x1),(.6*y0+.4*y1),(.4*x0+.6*x1),(.4*y0+.6*y1),col=\"blue\",lwd=2)\n \n v.x <- loci[loci[,1]==vertices[input$init-1],2]\n v.y <- loci[loci[,1]==vertices[input$init-1],3]\n\n points(v.x,v.y,pch=1,cex=4,lwd=2)\n points(v.x,v.y,pch=1,cex=3,lwd=2)\n }\n }\n \n points(loci[,2],loci[,3],pch=20,cex=2,col=\"red\")\n\n \n }) # initPlot's renderPlot\n\n##################################\n# extendPlot #\n##################################\n output$extendPlot <- renderPlot({\n\n loci <- all.list()[[1]]\n vertices <- all.list()[[2]]\n coords <- all.list()[[3]]\n\n #############################\n # Triangle:EXTEND #\n #############################\n if (input$shape == \"tri\") {\n \n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,sqrt(3)/2),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n \n #############################\n # Square:EXTEND #\n #############################\n if (input$shape == \"sqr\") {\n \n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n \n #############################\n # Pentagon:EXTEND #\n #############################\n if (input$shape == \"pent\") {\n \n c1 <- 0.25*(sqrt(5)-1)\n c2 <- 0.25*(sqrt(5)+1)\n s1 <- 0.25*(sqrt(10+2*sqrt(5)))\n s2 <- 0.25*(sqrt(10-2*sqrt(5)))\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-s1,s1),ylim=c(-c2,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n\n #############################\n # Hexagon:EXTEND #\n #############################\n if (input$shape == \"hex\") {\n \n alpha <- 0.5\n beta <- sqrt(3)/2\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-beta,beta),ylim=c(-2*alpha,2*alpha),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n\n ############################################################################\n ### APPLIED TO ALL\n if (!is.null(input$extend)) {\n if (input$extend!=0) { \n points(coords[1:input$extend,1],coords[1:input$extend,2],pch=20,cex=1,col=\"blue\") \n }\n }\n \n points(loci[,2],loci[,3],pch=20,cex=2,col=\"red\")\n \n }) # extendPlot's renderPlot\n\n##################################\n# compPlot #\n##################################\n output$compPlot <- renderPlot({\n \n loci <- all.list()[[1]]\n vertices <- all.list()[[2]]\n coords <- all.list()[[3]]\n\n #############################\n # Triangle:COMPLETE #\n #############################\n if (input$shape == \"tri\") {\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,sqrt(3)/2),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n \n #############################\n # Square:COMPLETE #\n #############################\n if (input$shape == \"sqr\") {\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(0,1),ylim=c(0,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n\n\n #############################\n # Pentagon:COMPLETE #\n #############################\n if (input$shape == \"pent\") {\n\n c1 <- 0.25*(sqrt(5)-1)\n c2 <- 0.25*(sqrt(5)+1)\n s1 <- 0.25*(sqrt(10+2*sqrt(5)))\n s2 <- 0.25*(sqrt(10-2*sqrt(5)))\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-s1,s1),ylim=c(-c2,1),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n \n \n #############################\n # Hexagon:COMPLETE #\n #############################\n if (input$shape == \"hex\") {\n\n alpha <- 0.5\n beta <- sqrt(3)/2\n\n par(mar=c(0.5,0.5,0.5,0.5))\n plot(0,0,xlim=c(-beta,beta),ylim=c(-2*alpha,2*alpha),col=0,\n yaxt=\"n\",xaxt=\"n\",xlab=\"\",ylab=\"\",bty=\"n\")\n }\n\n ############################################################################## \n ### APPLIED TO ALL \n if (!is.null(input$pts)) { \n if (input$pts!=0) { \n points(coords[1:input$pts,1],coords[1:input$pts,2],pch=\".\",cex=2.5,col=\"blue\") \n }\n }\n points(loci[,2],loci[,3],pch=20,cex=2,col=\"red\")\n\n }) # compPlot's renderPlot\n \n \n})\n\n", "meta": {"hexsha": "743ef7ed12f367271899121235d450eeb9b0c97a", "size": 16370, "ext": "r", "lang": "R", "max_stars_repo_path": "ChaosGame2D/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": "ChaosGame2D/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": "ChaosGame2D/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": 28.9734513274, "max_line_length": 90, "alphanum_fraction": 0.4539401344, "num_tokens": 5666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5869269121585443}} {"text": "\n\n#Let's build a dataset : height of 10 sorgho and poacee sample in 3 environmental conditions (A, B, C)\nA=c(rep(\"sorgho\" , 10) , rep(\"poacee\" , 10) )\nB=rnorm(20,10,4)\nC=rnorm(20,8,3)\nD=rnorm(20,5,4)\ndata=data.frame(A,B,C,D)\ncolnames(data)=c(\"specie\",\"cond_A\",\"cond_B\",\"cond_C\")\n\n#Let's calculate the average value for each condition and each specie with the *aggregate* function\nbilan=aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , mean)\nrownames(bilan)=bilan[,1]\nbilan=as.matrix(bilan[,-1])\n\n#Then it is easy to make a classical barplot :\nlim=1.2*max(bilan)\nze_barplot = barplot(bilan , beside=T , legend.text=T , col=c(\"blue\" , \"skyblue\") , ylim=c(0,lim))\n\n#I becomes a bit more tricky when we want to add the error bar representing the confidence interval.\n#First I create a smell function that takes...in entry\nerror.bar <- function(x, y, upper, lower=upper, length=0.1,...){\n arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)\n}\n\n#Then I calculate the standard deviation for each specie and condition :\nstdev=aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , sd)\nrownames(stdev)=stdev[,1]\nstdev=as.matrix(stdev[,-1]) * 1.96 / 10\n\nI am ready to add the error bar on the plot using my \"error bar\" function !\npng(\"#4_barplot_with_IC.png\" , width = 480, height = 480)\nze_barplot = barplot(bilan , beside=T , legend.text=T , \n col=c(\"blue\" , \"skyblue\") , ylim=c(0,lim) , ylab=\"height\")\nerror.bar(ze_barplot,bilan, stdev)\ndev.off()\n\n\n\n", "meta": {"hexsha": "e35d26543922bd444f907706921eaf1b4b017ec4", "size": 1492, "ext": "r", "lang": "R", "max_stars_repo_path": "OLD_GALLERY_RSCRIPT/#4_barplot_with_IC.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/#4_barplot_with_IC.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/#4_barplot_with_IC.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": 37.3, "max_line_length": 102, "alphanum_fraction": 0.6963806971, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5867953230629275}} {"text": "#' @export\n#' @title ellipse.2d\n#' @description This function calculates a 2D kernel density then plot highest density regions with contour().\n#' @param \\code{x} \n#' @param \\code{y} \n#' @param \\code{pv} the density of the region to be outlined - defaults to 95 percent (i.e. 0.05) \n#' @param \\code{sc} a scaling factor? defaults to 50\n#' @references \\url{https://stat.ethz.ch/pipermail/r-help/2000-March/005973.html}\n#' @family plotting\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\nellipse.2d = function( x, y, pv=0.05, sc=50 ) {\n library(KernSmooth)\n xr = range( x, na.rm=T)\n yr = range( y, na.rm=T)\n dx = (xr[2] - xr[1] ) / sc\n dy = (yr[2] - yr[1] ) / sc\n z = bkde2D(cbind(x,y), bandwidth=c(dx,dy))\n zsort <- sort(z$fhat)\n p <- cumsum(zsort)/sum(zsort)\n contour(z$x1, z$x2, z$fhat, levels=min(zsort[p>=pv]), add=T, labels=\"\", drawlabels=F )\n # points(x,y, pch=20) \n}\n\n\n", "meta": {"hexsha": "e58129fc74133316733a7a182531f8f77d8b39ee", "size": 902, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ellipse.2d.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/ellipse.2d.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/ellipse.2d.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": 34.6923076923, "max_line_length": 110, "alphanum_fraction": 0.6341463415, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5867838867079245}} {"text": "\n ## Avoid printing to unwarranted accuracy\n od <- options(digits = 5)\n x <- 0:10\n y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8)\n \n ## Easy one-dimensional MLE:\n nLL <- function(lambda) -sum(stats::dpois(y, lambda, log = TRUE))\n fit0 <- mle(nLL, start = list(lambda = 5), nobs = NROW(y))\n # For 1D, this is preferable:\n fit1 <- mle(nLL, start = list(lambda = 5), nobs = NROW(y),\n method = \"Brent\", lower = 1, upper = 20)\n stopifnot(nobs(fit0) == length(y))\n \n ## This needs a constrained parameter space: most methods will accept NA\n ll <- function(ymax = 15, xhalf = 6) {\n if(ymax > 0 && xhalf > 0)\n -sum(stats::dpois(y, lambda = ymax/(1+x/xhalf), log = TRUE))\n else NA\n }\n (fit <- mle(ll, nobs = length(y)))\n mle(ll, fixed = list(xhalf = 6))\n ## alternative using bounds on optimization\n ll2 <- function(ymax = 15, xhalf = 6)\n -sum(stats::dpois(y, lambda = ymax/(1+x/xhalf), log = TRUE))\n mle(ll2, method = \"L-BFGS-B\", lower = rep(0, 2))\n \n AIC(fit)\n BIC(fit)\n \n summary(fit)\n logLik(fit)\n vcov(fit)\n plot(profile(fit), absVal = FALSE)\n confint(fit)\n \n ## Use bounded optimization\n ## The lower bounds are really > 0,\n ## but we use >=0 to stress-test profiling\n (fit2 <- mle(ll, method = \"L-BFGS-B\", lower = c(0, 0)))\n plot(profile(fit2), absVal = FALSE)\n \n ## a better parametrization:\n ll3 <- function(lymax = log(15), lxhalf = log(6))\n -sum(stats::dpois(y, lambda = exp(lymax)/(1+x/exp(lxhalf)), log = TRUE))\n (fit3 <- mle(ll3))\n plot(profile(fit3), absVal = FALSE)\n exp(confint(fit3))\n \n options(od)\n ", "meta": {"hexsha": "6ebe7c3d9e1398f35e136d70f1d8109fee53bc3d", "size": 1581, "ext": "r", "lang": "R", "max_stars_repo_path": "backend/src/r/scripts/mle_test.r", "max_stars_repo_name": "CassianoViana/CTPuzzlePlatform", "max_stars_repo_head_hexsha": "ffdae24a1712b952f11a412246dbf7791fd3dcac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-10T04:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T04:01:14.000Z", "max_issues_repo_path": "backend/src/r/scripts/mle_test.r", "max_issues_repo_name": "CassianoViana/CTPuzzlePlatform", "max_issues_repo_head_hexsha": "ffdae24a1712b952f11a412246dbf7791fd3dcac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backend/src/r/scripts/mle_test.r", "max_forks_repo_name": "CassianoViana/CTPuzzlePlatform", "max_forks_repo_head_hexsha": "ffdae24a1712b952f11a412246dbf7791fd3dcac", "max_forks_repo_licenses": ["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.0, "max_line_length": 76, "alphanum_fraction": 0.5939278937, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5867838860651926}} {"text": "#Dimensionality reduction\n#次元削減\n\n#参考\n#https://www.slideshare.net/mikayoshimura50/150905-wacode-2nd\n#http://d.hatena.ne.jp/hoxo_m/20120313/p1\n#https://blog.albert2005.co.jp/2014/12/11/%E9%AB%98%E6%AC%A1%E5%85%83%E3%83%87%E3%83%BC%E3%82%BF%E3%81%AE%E5%8F%AF%E8%A6%96%E5%8C%96%E3%81%AE%E6%89%8B%E6%B3%95%E3%82%92swiss-roll%E3%82%92%E4%BE%8B%E3%81%AB%E8%A6%8B%E3%81%A6%E3%81%BF%E3%82%88/\n\n\ndr <- function(formula, data, normalize = TRUE, unique = TRUE,\n methods = c(\"pca\", \"kpca\" ,\"mds\", \"tsne\", \"lle\", \"som\", \"diffmap\"),\n kpca.par = list(kernel = \"rbfdot\", sigma = 0.1),\n mds.par = list(k = 2),\n tsne.par = list(dims = 2, initial_dims = 50, perplexity = 30, theta = 0.5),\n lle.par = list(m = 2, k = 5, reg = 2, p = 0.5),\n som.par = list(xdim = 5, ydim = 6),\n diffmap.par = list(neigen = NULL, t = 0, maxdim = 50, delta=10^-5))\n {\n\n #kpca.par はsigma,degree, scale, offset,orderも指定できる。\n #tsne.parのdimsは3以下がよい。\n\n #入力をチェック---\n if(is.null(formula)){stop(\"formula is null.\")}\n if(is.null(data)){stop(\"data is null.\")}\n\n #データを準備---\n ret <- list() #戻り値\n ret$parameter$formula <- formula\n ret$parameter$normalize <- normalize\n ret$parameter$unique <- unique\n\n #解析用データ\n if(length(formula) == 3){\n data.original <- model.matrix(object = formula[-2], data = data)[,-1] #解析用データ。[,-1]で切片を除く。\n }else{\n data.original <- model.matrix(object = formula, data = data)[,-1] #解析用データ。[,-1]で切片を除く。\n }\n\n #ユニークなデータを抜粋\n #https://qiita.com/weda_654/items/97c8dbba9f8198845537\n u.no <- !duplicated(data.original)\n data.original <- data.original[u.no,]\n\n #目的変数がある場合の処理\n if(length(formula) == 3){\n y.formula <- as.formula(paste0(as.character(formula[2]), \"~+0\"))\n y.data <- model.frame(y.formula, data)[u.no,1]\n ret$y <- y.data\n formula[2] <- NULL #目的変数を削除\n }else{\n ret$y <- NULL\n }\n\n #説明変数の項目名を抜粋\n ret$parameter$names <- names(data.original[1, ])\n\n #規格化。data.maが解析用の元データのマトリクス\n if(normalize){\n data.mean <- apply(data.original, 2, mean)\n data.sd <- apply(data.original, 2, sd)\n #規格化。もうちょっとスマートなのがある気がする…\n data.ma <- t(apply(data.original,1,function(x){(x - data.mean)/data.sd}))\n }else{\n data.mean <- NULL\n data.sd <- NULL\n data.ma <- data.original\n }\n ret$parameter$data.mean <- data.mean\n ret$parameter$data.sd <- data.sd\n\n #変換\n data.df <- data.frame(data.ma) #データフレームに変換\n data.di <- dist(data.ma) #dist classの距離に変換\n\n #ここから解析本体-----------------------------------------------\n\n #PCA\n #(数値のみしか使用できない。)\n if(!is.na(match(\"pca\", methods))){\n cat(\"\\n[Principal Components Analysis] \\n\")\n ret$pca <- prcomp(~., data = data.df,\n scale = normalize, center = normalize,\n retx = TRUE)\n }\n\n #kernel PCA\n if(!is.na(match(\"kpca\", methods))){\n cat(\"\\n[Kernel Principal Components Analysis] \\n\")\n #kpcaに渡すデータを編集。\n kpca.kernel <- kpca.par$kernel\n kpca.par$kernel <- NULL\n\n #kpca本体\n ret$kpca <- kpca(x = ~., data = data.df,\n kernel = kpca.kernel, kpar = kpca.par)\n }\n\n\n #MDS\n if(!is.na(match(\"mds\", methods))){\n cat(\"\\n[Classical Multidimensional Scaling]\\n\")\n ret$mds <- cmdscale(d = as.matrix(data.di), k = mds.par$k)\n }\n\n #t-SNE\n #https://blog.albert2005.co.jp/2015/12/02/tsne/\n #注意点として、t-SNE で圧縮する次元は、 2・3 次元が推奨されています\n if(!is.na(match(\"tsne\", methods))){\n cat(\"\\n[t-Distributed Stochastic Neighbor Embedding]\\n\")\n ret$tsne <- Rtsne(data.df,\n dims = tsne.par$dims, initial_dims = tsne.par$initial_dims,\n perplexity = tsne.par$perplexity, theta = tsne.par$theta)\n }\n\n #LLE\n #m,kは再考の必要あり。\n if(!is.na(match(\"lle\", methods))){\n cat(\"\\n[Locally linear embedding]\\n\")\n ret$lle <- lle(data.ma, m = lle.par$m,\n k = lle.par$k,\n reg = lle.par$reg, p = lle.par$p)\n }\n\n #SOM\n #その他のパラメータもあったほうがいい?\n if(!is.na(match(\"som\", methods))){\n cat(\"\\n[Self-Organizing Map]\\n\")\n ret$som <- som(data.df, xdim=som.par$xdim, ydim=som.par$ydim)\n }\n\n #diffusion map\n if(!is.na(match(\"diffmap\", methods))){\n cat(\"\\n[Diffusion Map]\\n\")\n ret$diffmap <- diffuse(data.di,\n neigen = diffmap.par$neigen,\n t = diffmap.par$t, maxdim = diffmap.par$maxdim,\n delta = diffmap.par$delta)\n }\n\n\n #戻り値\n class(ret) <- \"dr\"\n return(ret)\n}\n\n\npredict.dr <- function(result, data){\n data.original <- model.matrix(object = result$parameter$formula, data = data)[,-1]\n\n #モデルで使用した説明変数と、新データで作った説明変数が一致するか確認。\n #カテゴリカル変数まわりでエラーが起きる気がする。\n if(!setequal(result$parameter$names, names(data.original[1, ]))){\n stop(\"Explanatory variable is different from model.\")\n }\n\n #規格化。data.maが解析用の元データのマトリクス\n if(result$parameter$normalize){\n #規格化。もうちょっとスマートなのがある気がする…\n data.ma <- t(apply(data.original,1,\n function(x){(x - result$parameter$data.mean)/result$parameter$data.sd}))\n }else{\n data.ma <- data.original\n }\n\n #変換\n data.df <- data.frame(data.ma) #データフレームに変換\n\n res <- list()\n\n res$pca <- predict(result$pca, data.df)\n res$kpca <- predict(result$kpca, data.df)\n\n\n #res$tsne <- predict(result$tsne, data.df)\n #https://stackoverflow.com/questions/43377941/t-sne-predictions-in-r\n #t-SNEでpredictできないみたい。\n #res$lle <- predict(result$lle, data.ma)\n #res$som <- predict(result$som, data.df)\n}\n\nplot.dr <- function(result, cex = 1){\n if(!is.null(result$y)){\n if(is.factor(result$y)){\n col_p <- rainbow(length(unique(result$y)))\n plot_bg <- col_p[unclass(result$y)]\n }else{\n rank_y <- round(rank(result$y))\n plot_bg <- heat.colors(length(result$y))[rank_y]\n }\n }else{\n plot_bg <- NULL; col_p <- NULL\n }\n\n chk_hit <- FALSE\n hit_ret <- function(chk_hit){\n if(chk_hit){\n cat(\"Hit to see next plot: \\n\")\n readline()\n }\n }\n\n plot_dr <- function(x, y, main, xlab, ylab){\n hit_ret(chk_hit)\n #https://www1.doshisha.ac.jp/~mjin/R/Chap_07/07.html\n plot(x, y, main = main, xlab = xlab, ylab = ylab, type = \"p\", pch = 21, cex = cex, bg = plot_bg)\n\n }\n\n if(!is.null(result$pca)){\n plot_dr(x = result$pca$x[,1], y = result$pca$x[,2],\n main = \"Principal Components Analysis\", xlab = \"PC1\", ylab = \"PC2\")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$kpca)){\n plot_dr(x = result$kpca@pcv[,1], y = result$kpca@pcv[,2],\n main = \"Kernel Principal Components Analysis\",\n xlab = \"K-PC1\", ylab = \"K-PC2\")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$mds)){\n plot_dr(x = result$mds[,1], y = result$mds[,2],\n main = \"Classical Multidimensional Scaling\", xlab = \"Dimension 1\", ylab = \"Dimension 2\")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$tsne)){\n plot_dr(x = result$tsne$Y[,1], y = result$tsne$Y[,2],\n main = \"t-Distributed Stochastic Neighbor Embedding\", xlab = \" \", ylab = \" \")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$lle)){\n plot_dr(x = result$lle$Y[,1], y = result$lle$Y[,2],\n main = \"Locally linear embedding main function\", xlab = \" \", ylab = \" \")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$som)){\n plot_dr(x = result$som$visual$x, y = result$som$visual$y,\n main = \"Self-Organizing Map\", xlab = \"x\", ylab = \"y\")\n chk_hit <- TRUE\n }\n\n if(!is.null(result$diffmap)){\n plot_dr(x = result$diffmap$X[,1], y = result$diffmap$X[,2],\n main = \"diffusion map\", xlab = \" \", ylab = \" \")\n chk_hit <- TRUE\n }\n\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d78172f656fe76b5d43be178e4f102073fbb35cc", "size": 7507, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dr.r", "max_stars_repo_name": "ToshihiroIguchi/dr", "max_stars_repo_head_hexsha": "0b03df70c0b262949b68494a4368b943e364a9a2", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-01T11:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:32:35.000Z", "max_issues_repo_path": "R/dr.r", "max_issues_repo_name": "ToshihiroIguchi/dr", "max_issues_repo_head_hexsha": "0b03df70c0b262949b68494a4368b943e364a9a2", "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": "R/dr.r", "max_forks_repo_name": "ToshihiroIguchi/dr", "max_forks_repo_head_hexsha": "0b03df70c0b262949b68494a4368b943e364a9a2", "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.7624521073, "max_line_length": 242, "alphanum_fraction": 0.5857199947, "num_tokens": 2744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012105, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5861544821778546}} {"text": "### fimd4.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, 7mar2012\n### Version 2, 4nov2015 tested with mice 2.23\n### Tested with Mac OS X 10.7.3, R2.14-2, mice 2.12\n\nlibrary(\"mice\")\nlibrary(\"lattice\")\n\n\n### Chapter 4 Multivariate missing data\n\n### Section 4.1 Missing data patterns\n\n### define data sets pattern1-pattern4 with four patterns\ndata <- matrix(sample(1:100,4*8*3,replace=TRUE),nrow=8*4,\n dimnames=list(NULL,c(\"A\",\"B\",\"C\")))\ndata <- as.data.frame(data)\ndata[c(31:32),\"A\"] <- NA\ndata[c(15:16,22:24,30:32),\"B\"] <- NA\ndata[c(6:8,12:16,17:21,27:29),\"C\"] <- NA\nmdpat <- cbind(expand.grid(rec = 8:1, pat = 1:4, var = 1:3), r=as.numeric(as.vector(is.na(data))))\npattern1 <- data[1:8,]\npattern2 <- data[9:16,]\npattern3 <- data[17:24,]\npattern4 <- data[25:32,]\n\n### Figure 4.1\ntypes <- c(\"Univariate\",\"Monotone\",\"File matching\",\"General\")\ntp41 <- levelplot(r~var+rec|as.factor(pat), data=mdpat,\n as.table=TRUE, aspect=\"iso\",\n shrink=c(0.9), \n col.regions = mdc(1:2),\n colorkey=FALSE,\n scales=list(draw=FALSE),\n xlab=\"\", ylab=\"\",\n between = list(x=1,y=0),\n strip = strip.custom(bg = \"grey95\", style = 1,\n factor.levels = types))\nprint(tp41)\n\nmd.pattern(pattern4)\np <- md.pairs(pattern4)\np\n\n\n### proportion of usable cases\np$mr/(p$mr+p$mm)\n\n\n### outbound statistics\np$rm/(p$rm+p$rr)\n\n### Figure 4.2\npar(mfrow=c(2,2))\nfluxplot(pattern1, main=\"\", xlim=c(-0.1,1.1), ylim=c(-0.1,1.1))\ntext(x=0.5,y=1,label=\"Univariate\")\nfluxplot(pattern2, main=\"\", xlim=c(-0.1,1.1), ylim=c(-0.1,1.1))\ntext(x=0.5,y=1,label=\"Monotone\")\nfluxplot(pattern3, main=\"\", xlim=c(-0.1,1.1), ylim=c(-0.1,1.1))\ntext(x=0.5,y=1,label=\"File matching\")\nfluxplot(pattern4, main=\"\", xlim=c(-0.1,1.1), ylim=c(-0.1,1.1))\ntext(x=0.5,y=1,label=\"General\")\n\n### calculate pobs, influx, outflux of general pattern\nflux(pattern4)[,1:3]\n\n### section 4.3 Monotone data imputation\n### monotone data imputation on three columns\ndata <- nhanes2[,1:3]\nmd.pattern(data)\nimp <- mice(data, visit=\"monotone\", maxit=1, m=2)\n\n### Numerical example, approximate two-step\nini <- mice(nhanes2, maxit=0)\npred <- ini$pred\npred[\"bmi\",\"chl\"] <- 0\npred[\"hyp\",c(\"chl\",\"bmi\")] <- 0\nimp <- mice(nhanes2, vis=\"monotone\", pred=pred, maxit=1, m=2)\n\n### Section 4.5 Fully Conditional Specification\n\n### Example of slow convergence\ngenerate <- function(n = c(1000, 4500, 4500, 0),\n cor = matrix(c(1, 0.9, 0.9, 0.9, 1, 0.7, 0.9, 0.7, 1), nrow = 3)) {\n require(MASS)\n nt <- sum(n)\n cs <- cumsum(n)\n data <- mvrnorm(nt, mu = rep(0,3), Sigma = cor)\n dimnames(data) <- list(1:nt, c(\"X\", \"Y1\", \"Y2\"))\n if (n[2] > 0) data[(cs[1]+1):cs[2],\"Y1\"] <- NA \n if (n[3] > 0) data[(cs[2]+1):cs[3],\"Y2\"] <- NA\n if (n[4] > 0) data[(cs[3]+1):cs[4],c(\"Y1\",\"Y2\")] <- NA\n return(data)\n}\n\nimpute <- function(data, m = 5, method=\"norm\", print=FALSE, maxit = 10, ...) {\n statistic <- matrix(NA, nrow=maxit, ncol=m)\n for (iter in 1:maxit) {\n if (iter==1) imp <- mice(data, m = m, method = method, print=print, maxit = 1, ...)\n else imp <- mice.mids(imp, maxit=1, print=print, ...)\n statistic[iter,] <- unlist(with(imp, cor(Y1,Y2))$analyses)\n }\n return(list(imp=imp, statistic=statistic))\n}\n\nsimulate <- function(ns=matrix(c(1000,500,250,100,50,0,\n rep(c(4500,4750,4875,4950,4975,5000),2),\n rep(0,6)), nrow=6), m = 5, maxit=10,\n seed=1, ...) {\n if (!missing(seed)) set.seed(seed)\n s <- cbind(rep(1:nrow(ns), each=maxit*m),\n apply(ns, 2, rep, each=maxit*m),\n rep(1:maxit,each=m), 1:m, NA)\n colnames(s) <- c(\"k\",\"n111\",\"n101\",\"n110\",\"n100\",\"iteration\",\"m\",\"rY1Y2\")\n for (k in 1:nrow(ns)){\n data <- generate(ns[k,], ...)\n r <- impute(data, m=m, maxit=maxit, ...)\n s[s[,\"k\"]==k,\"rY1Y2\"] <- t(r$statistic) \n }\n return(data.frame(s))\n}\n\n### perform simulation - TIME CONSUMING (10 minutes)\nslow.demo <- simulate(maxit=150, seed=62771)\n\n### Figure 4.3\nlabels <- c(\"90% missing\", \"95% missing\", \"97.5% missing\", \n \"99% missing\", \"99.5% missing\", \"100% missing\")\ntp43 <- xyplot(rY1Y2~iteration|as.factor(k), group=m,\n data = slow.demo, layout=c(3,2),\n type=\"l\", as.table = TRUE,\n ylab = \"Correlation between Y1 and Y2\",\n xlab = \"Iteration\", col=mdc(3),\n scales=list(y=list(alternating=1, tck=c(1,0))),\n strip = strip.custom(bg=\"grey95\", style=1,\n factor.levels=labels))\nprint(tp43)\n\n### Section 4.6.3 Illustration\n\n## boys data: select subset\nselect <- with(boys, age>=8 & age<=21.0)\n\n### version with all numeric data for jm and pmm\ndjm <- boys[select,-4]\ndjm$gen <- as.integer(djm$gen)\ndjm$phb <- as.integer(djm$phb)\ndjm$reg <- as.integer(djm$reg)\n\n### version with categorical variables for fcs\ndfcs <- boys[select,-4]\n\n### impute according to joint multivariate normal\njm.10 <- mice(djm, method=\"norm\", seed=93005, m=10)\n\n### impute according to predictive mean matching\npmm.10 <- mice(djm, seed=71332,m=10)\n\n### impute according to proportional odds model\nfcs.10 <- mice(dfcs, seed=81420, m=10)\n\n### Figure 4.4\ntp44 <- xyplot(jm.10, gen~age|.imp, subset=as.integer(.imp)<7, \n xlab=\"Age\", ylab=\"Genital stage\")\nprint(tp44)\n\n### Figure 4.5\ntp45 <- xyplot(fcs.10, gen~age|.imp, subset=as.integer(.imp)<7,\n xlab=\"Age\", ylab=\"Genital stage\")\nprint(tp45)\n\n### Figure 4.6 is too complex, and will not be given here\n\n\n", "meta": {"hexsha": "2dd8150c4be07769abb9ddd3648db0c41c001116", "size": 5574, "ext": "r", "lang": "R", "max_stars_repo_path": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd4.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/fimd4.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/fimd4.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": 31.1396648045, "max_line_length": 98, "alphanum_fraction": 0.5993900251, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5859645159869583}} {"text": "#' @title calcResistanceShipPwr\n#'\n#' @description Calculate ship power (kW) for resistance-based power models.\n#'\n#' @param Rtot Total ship resistance (vector of numericals, kN) (see\n#' \\code{\\link{calcKristTotalRes}} or \\code{\\link{calcHMTotalRes}})\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param hullEff Hull efficiency (vector of numericals, dimensionless) (see\n#' \\code{\\link{calcHullEff}})\n#' @param openWaterEff Open water efficiency (vector of numericals,\n#' dimensionless) (see \\code{\\link{calcOpenWaterEff}})\n#' @param totalInstalledPwr Total installed main engine power (vector of\n#' numericals, kW) (maximum\n#' continuous rated power)\n#' @param shaftEff Shaft efficiency (dimensionless). Default = 0.98.\n#' Ratio of power delivered to the propeller and the brake power delivered by\n#' the engine. Can supply either a vector of numericals, a single\n#' number, or rely on the default\n#' @param relRotationEff Relative rotational efficiency (dimensionless).\n#' Default = 1. Accounts for effect of rotational flow of water around propeller.\n#' Can supply either a vector of numericals, a single number, or rely on the default\n#' @param pwrUpperBoundPercent Percent of total installed power at which\n#' required power is capped (1 indicates required power cannot exceed\n#' \\code{totalInstalledPwr}). Can supply either a vector of numericals, a single\n#' number, or rely on the default\n#' @param pwrLowerBoundPercent Percent of total installed power to act as lower\n#' bound for required power (0.02 indicates required power cannot go below 2\\%\n#' of \\code{totalInstalledPwr}). Can supply either a vector of numericals, a\n#' single number, or rely on the default\n#'\n#' @return power (vector of numericals, kW)\n#'\n#' @details\n#' This function is called by both Holtrop & Mennen (\\code{\\link{calcHMPwr}})\n#' and Kristensen (\\code{\\link{calcKristPwr}}) power calculations, where each\n#' uses has its own total resistance calculation (\\code{\\link{calcHMTotalRes}}\n#' and \\code{\\link{calcKristTotalRes}}).\n#'\n#' Assumptions for shaft efficiency and relative rotational efficiency are based\n#' on MAN.\n#'\n#' @references\n#'\n#'\\href{https://www.man-es.com/marine/products/propeller-aft-ship}{MAN Energy\n#' Solutions. 2011. \"Basic Principles of Propulsion.\"}\n#'\n#' @seealso\n#' \\itemize{\n#' \\item \\code{\\link{calcKristTotalRes}}\n#' \\item \\code{\\link{calcHMTotalRes}}\n#' \\item \\code{\\link{calcSpeedUnitConversion}}\n#' \\item \\code{\\link{calcHullEff}}\n#' \\item \\code{\\link{calcOpenWaterEff}}\n#' \\item \\code{\\link{calcHMPwr}}\n#' \\item \\code{\\link{calcKristPwr}}\n#' }\n#'\n#' @examples\n#' calcResistanceShipPwr(398.487,10.8, 1.191176, 0.721239,9363, shaftEff=0.98,relRotationEff=1)\n#'\n#' @export\n\n\ncalcResistanceShipPwr <- function(Rtot,shipSpeed, hullEff, openWaterEff,totalInstalledPwr,\n shaftEff=0.98,relRotationEff=1, pwrUpperBoundPercent=1, pwrLowerBoundPercent=0.02){\n\n power <-ifelse(shipSpeed==0,\n 0,\n pmin(pwrUpperBoundPercent*totalInstalledPwr,\n pmax(pwrLowerBoundPercent*totalInstalledPwr,\n ((Rtot*shipSpeed)/\n (hullEff*openWaterEff*shaftEff*relRotationEff))\n )\n )\n )\n\n return(power)\n\n}\n", "meta": {"hexsha": "22dae219d1414955ea796aeaf7f38d3a4bfc32a8", "size": 3264, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcResistanceShipPwr.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/calcResistanceShipPwr.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/calcResistanceShipPwr.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 40.2962962963, "max_line_length": 117, "alphanum_fraction": 0.7227328431, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5859120892406519}} {"text": "####################################################################################################\n# 4. faza: Napredna analiza podatkov\n####################################################################################################\n#NAVODILA:\n#-sestavite predikcijski model za napovedovanje:\n# za prihodnost, kako je neka vrednost odvisna od drugih, morda uporabite kako metodo iz strojnega učenja, ...\n#-na podlagi modela naključno modelirate nove podatke (npr. napovedovanje gibanja delnic),\n#-s pomočjo razvrščanja določite skupine s podobnimi lastnostmi,\n#-s pomočjo gručenja izločite osamelce (in morda tako izboljšate model), ali pa za različne \n# skupine podatkov naredite različne modele.\n\n#-Kot rezultat te faze lahko sestavite tudi aplikacijo v ogrodju Shiny (za boljšo oceno).\n#-Vaš program bo narisal enega ali več grafov (lahko tudi zemljevidov), \n#ki jih boste nato vključili v poročilo skupaj z opisom vaše analize in njenimi zaključki.\n\n#---------------------------------------------------------------------------------------------------\n#PLAN/KAJ ME ZANIMA:\n#-predikcijski model za napovedovanje kdo bo zmagal na olimpijskih igrah 2021 skupinske\n#-(predikcijski model za napovedovanje verjetne izbire tekmovalk, ki bodo zastopale Rusijo)\n#-novi podatki: kakšne bodo ocene na OI za dino, arino in linoy\n#-grupiranje E/D (induvidualne) in skupinske\n#-s pomočjo razvrščanja določimo skupine tekmovalk ki so bolj spretne z rekvizitom in tiste ki imajo boljšo tehniko s telesom\n#-Grupiranje po rekvizitih - kateter jim je boljši induv (in skupinsko)\n#-s pomočjo gručenja izločite osamelce - soldatova, kaylen, (lala) zaradi BD (in morda tako izboljšate model), ali pa za različne \n# skupine podatkov naredite različne modele.\n#-----------------------------------------------------------------------------------------------------\n\n\n#require(ggplot2) #geom_smooth, geom_segment - ravne črte med toččkami\n#require(dplyr)\n#library(NbClust) #Za določanje skupin: NbClust\n#require(ggdendro) #za dendrograme: ggdendrogram, dendro_data (izvoz podatkov v obliko dalahko delamo z ggplot), segment za povezave v dendrogramu,\n #theme_dendro \n#require(ggrepel) #za overlapping\n\n\n#============================================================================================\n#1. KATERA DRŽAVA BO ZMAGALA NA OLIMPIJSKIH IGRAH V SKUPINSKIH SESTAVAH\n#============================================================================================\n#View(skupinske)\n\n\n#----------------------------------------------------------------\n#graf-za lažje predstavljanje podatkov\n#----------------------------------------------------------------\nggplot(skupinske, aes(x = D, y = E, col = tekma)) + \n geom_point()\n\n#---------------------------------------------------------------\n# MODEL \n#--------------------------------------------------------------\n#lm{stats} - koliko je stolpec D odvisen od E\nmodel_skupinske_obroci_kiji <- lm(E ~ D, data=skupinske%>%filter(rekvizit == \"3 obroči + 4 kiji\"))\nmodel_skupinske_zoge <- lm(E ~ D, data=skupinske%>%filter(rekvizit == \"5 žog\"))\n\n#------------------------------------------------------------------\n# IZRIS LINEARNEGA MODELA\n#------------------------------------------------------------------\nggplot(skupinske, aes(x = D, y = E)) + \n geom_point() + \n facet_grid(.~rekvizit)+\n geom_smooth(method=lm, formula=y~x) #ggplot2\n\n\n#-----------------------------------------------------------------\n# PREDIKCIJA. Kakšna bo E ko bodo D dvignile na 32, 35\n#-----------------------------------------------------------------\nnovDskupinske <- data.frame(D=c(32, 35))\n#predict {stats}\npredict(model_skupinske_obroci_kiji, novDskupinske) #5.315866 4.698013 \npredict(model_skupinske_zoge, novDskupinske) #8.735773 9.121857\n\n#tabela s stolpcem D in E\nnapovedEskupinske_obroci_kiji <- novDskupinske %>% mutate(E=predict(model_skupinske_obroci_kiji, .))\nnapovedEskupinske_zoge <- novDskupinske %>% mutate(E=predict(model_skupinske_zoge, .))\n\n#napovedE_tabela_skupinske <- napovedEskupinske %>% \n# mutate(drzava = \"napoved\", tekma = 2021, rekvizit = c(\"3 obroči + 4 kiji\", \"5 žog\"), Pen.= 0.00, koncna_ocena = c(7.518193+32, 7.536600+35) ) \n\n#napovedEskupinske_obroci_kiji %>% View\n#napovedEskupinske_zoge %>% View\n#napovedE_tabela_skupinske %>% view\n\n#skupinske_predikcija_napoved <- rbind(napovedE_tabela_skupinske, skupinske)\n#skupinske_predikcija_napoved #%>% view\n\n\n########################################################################\n#----------------\n# izris napovedi\n#----------------\npredikcija_skupinske_obroci_kiji <- ggplot(skupinske%>%filter(rekvizit == \"3 obroči + 4 kiji\"), aes(x = D, y = E)) + \n geom_point(shape=1) + \n geom_smooth(method=lm, formula=y~x, fullrange = TRUE) + \n geom_point(data=napovedEskupinske_obroci_kiji, aes(x=D, y=E), color='red', size=3)+\n labs(title = \"PREDIKCIJA OCENE E NA OLIMPIJSKIH IGRAH 2021 ZA SKUPINSKE SESTAVE\n V SESTAVI S KOMBINIRANIM REKVIZITOM\" )+\n theme_bw()+ #brez sivega ozadja\n theme(legend.position = \"none\", plot.title = element_text(hjust=0.5))#naslovna na sredini\n \n\nprint(predikcija_skupinske_obroci_kiji)\n\n\npredikcija_skupinske_zoge <- ggplot(skupinske%>%filter(rekvizit == \"5 žog\"), aes(x = D, y = E)) + \n geom_point(shape=1) + \n geom_smooth(method=lm, formula=y~x, fullrange = TRUE) + \n geom_point(data=napovedEskupinske_zoge, aes(x=D, y=E), color='red', size=3)+\n labs(title = \"PREDIKCIJA OCENE E NA OLIMPIJSKIH IGRAH 2021 ZA SKUPINSKE SESTAVE\n V SESTAVI Z ŽOGAMI\" )+\n theme_bw()+ #brez sivega ozadja\n theme(legend.position = \"none\", plot.title = element_text(hjust=0.5))#naslovna na sredini\n\n\nprint(predikcija_skupinske_zoge)\n\n\n\n\n\n\n#==============================================================================\n#2. GRUPIRANJE GLEDE NA E IN GLEDE NA D ZA SKUPINSKE SESTAVE\n#==============================================================================\n\nrisba_skupinske <- skupinske %>% \n ggplot(aes(x=D, y=E, col=drzava, shape=rekvizit))+\n geom_point()+\n theme_minimal()+\n facet_grid(.~tekma)+\n #---------------------------------------------------------\n #oštevilčimo pikice\n #---------------------------------------------------------\n geom_text(\n data=skupinske %>% mutate(n = row_number()),\n aes(label=drzava),\n size=2,\n color='black',\n nudge_x = 0.03,\n nudge_y = 0.03\n )+\n theme_minimal()\nprint(risba_skupinske)\n\n#KOMENTAR:izgleda kot da bi lahko pogrupirali skupaj v Bakuju: \n#Rus, Bul, Jap, Blr\n\n\n#---------------------------------------------------------------\n#STANDARDIZACIJA MATRIKE\n#---------------------------------------------------------------\ndata_skupinske <- skupinske %>%\n select(E,D) %>%\n as.matrix() %>%\n scale() #{base} naredi standardizacijo\n\n#View(data_skupinske)\n\n\n#----------------------------------------------------------------\n#HIERARHIČNO RAZVRŠČANJE \n#----------------------------------------------------------------\nrazdalje_skupinske <- dist(as.matrix(data_skupinske)) #{stats} na i,j tem mestu je razdalja med i-to in j-to vrstico\nmodel_skupinske <- hclust(razdalje_skupinske) #model hierarhičnega razvrščanja; {stats}\n\n\n#malo pregledamo\n#----------------------------------------------------------------\n## Dobimo opis postopka razvrščanja\n#names(model_skupinske) \n\n# Algoritem za razvrščanje: ward.D, ward.D2, single, \n# complete, average, mcquitty, median, centroid\n# Lahko podamo kot parameter\n#model_skupinske$method\n\n# Tip metrike: pridobljen iz matrike različnosti\n# Npr. za D <- dist(X, method=\"manhattan\") bi dobili \"manhattan\"\n#model_skupinske$dist.method\n\n# Opis zaporedja združevanja skupin\n#model_skupinske$merge %>% View\n\n# Višine, ko je prišlo do združevanja\n#model_skupinske$height\n\n# Preureditev elementov, da bomo lahko lepo izrisali dendrogram\n#model_skupinske$order\n\n# Poimenovanja podatkovnih enot. \n#model_skupinske$labels\n\n# Opisni klic funkcije, ki je sprožila izračun\n#model_skupinske$call\n\n#---------------------------------------------------------\n#DENDROGRAM - le vmesen graf\n#----------------------------------------------------------\n#1. način izrisa dendrograma\n#plot(model_skupinske, hang=-1, cex=0.3, main=\"skupinske\") \n\n#2. način: S pomočjo paketa `ggdendro`\n#require(ggdendro)\n\ndendrogram_skupinske <- ggdendrogram(model_skupinske, labels=TRUE) + \n theme(axis.text.y = element_blank())\n \nprint(dendrogram_skupinske)\n\n\n#----------------------------------------------------------------------\n# Pridobitev podatkov za izris z ggplot\n#----------------------------------------------------------------------\n#iz ggdendro uporabimo dendro_data() za izvozi podatke v objekt na katerem lahko uporabljamo ggplot\nddata_skupinske <- dendro_data(model_skupinske, type = \"rectangle\") \n#View(ddata_skupinske)\n#names(ddata_skupinske) #\"segments\" \"labels\" \"leaf_labels\" \"class\"\n\n#segment(ddata_skupinske) %>% View #povezave v dendrografu\n\n#-----------------------------------------------------------\n#dendrogram brez napisov držav - nepotrebno\n#-----------------------------------------------------------\nggplot(segment(ddata_skupinske)) + #segment iz ggdendro za povezave v dendrogramu\n geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + #ggplot2- ravnačrta med dvema točkama\n #coord_flip() + \n #scale_y_reverse(expand = c(0.2, 0)) + \n theme_dendro() #ggdendro\n\n\n#################################################\n#------------------------------------------------\n#dodamo še napise\n#-------------------------------------------------\n#v tabelo labels dodamo še dva stolpca label in drzava\nddata_skupinske$labels$label <- paste(skupinske$drzava[model_skupinske$order], ddata_skupinske$labels$label %>% as.character)\nddata_skupinske$labels$drzava <- skupinske$drzava[model_skupinske$order]\n\ndendrogg_skupinske <- ggplot(segment(ddata_skupinske)) + \n geom_segment(aes(x = x, y = y, xend = xend, yend = yend), size=1) + #size debelina črt\n labs( title = \"DENDROGRAM DRŽAV GLEDE NA OCENO E IN D\")+\n theme(plot.title = element_text(hjust=0.5))+\n coord_flip() + \n scale_y_reverse(expand = c(0.5, 0)) + \n geom_text(\n data=ddata_skupinske$labels, \n aes(x=x, y=y, label=label, colour=drzava), hjust=0, size=3.5, nudge_y = 0.03, show.legend = FALSE) + #size pisava držav\n theme(axis.line.y=element_blank(),\n axis.ticks.y=element_blank(),\n axis.text.y=element_blank(),\n axis.title.y=element_blank(),\n axis.title.x = element_blank(),\n axis.ticks.x=element_blank(),\n axis.text.x=element_blank(),\n panel.background=element_rect(fill=\"white\"),\n panel.grid=element_blank())\nprint(dendrogg_skupinske)\n#dendrogg + ggsave(\"dendrogg.pdf\", device=\"pdf\")\n#iz grafa se zdi da je najbolje razvrstiti v 3 skupine Elbow method\n\n\n#-------------------------------------------------------\n# šTEVILO SKUPIN- RAZVRSTITEV GLEDE NA REZ DENDROGRAMA\n#-------------------------------------------------------\n# 3 skupine\n#-------------------------------\n# določanje skupin\n#--------------------------------\np3 <- cutree(model_skupinske, k=3) #{stats}\n#p3 #1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 3 3 2 3 3 3 3 2 2\n #po vrstnem redu iz tabele skupinske nam pove v katero skupino gre posamezna država\n\n#----------------------------------------------------------------------\nskupinske$drzava <- recode(skupinske$drzava #dplyr\n ,'Bulgaria' = 'BUL' \n ,'Israel' = 'ISR' \n ,'Italy' = 'ITA' \n ,'Japan' = 'JPN' \n ,'Russia' = 'RUS' \n ,'Ukraine' = 'UKR' \n ,'Belarus' = 'BLR' \n ,'Azerbaijan' = 'AZE' \n ,'Turkey' ='TUR'\n ,'China' = 'CHN' \n ,'France' = 'FRA' \n ,'Estonia' = 'EST' \n )\n\n\n\n#----------------------------------\n#pikice pobarvane v barvah skupine\n#-----------------------------------\ngrupiranje_skupinske3 <- skupinske %>% \n ggplot(aes(x=D, y=E, col=p3, shape = tekma)) +\n guides(color = FALSE)+ #legende za barvo ne potrebujem\n geom_point() +\n geom_text_repel( #iz ggrepel, da se ne prekrivajo imena\n aes(label=drzava),\n size=3,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )+\n labs( title = \"GRUPIRANJE DRŽAV GLEDE NA OCENO E IN D\")+\n scale_y_continuous(breaks=c(6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5))+\n theme_minimal()+\n theme(plot.title = element_text(hjust=0.5))\n \nprint(grupiranje_skupinske3) \n #+ ggsave(\"risba2.pdf\", device=\"pdf\")\n\n#KOMENTAR: \n#1. SKUPINA: D med 18.2 in 21.1, E med 7.35 in 8.75\n#Bul baku oba rek, Jap baku oba rek, Ita baku kiji+obroč, Blr baku kiji+obroč, Rus baku oba rek,\n# china baku oba rek, Azerb baku kiji+obroči samo eni finali, Isr oba rek\n#2. SKUPINA: D med 18.5 in 21.6 E 5.7 in 6.8\n#ita baku kiksane žoge, Bel baku kiksane žoge, UKr baku kiksane žoge samo to v finalih, Est kijev, Fra kijev, Tur kijev\n#3. SKUPINA: D med 23.00 in 27.1 in E 6.25 in 8.25\n#Ukr kijev oba, Israel kijev obe, Est kijev žoge , Azer kijev oba, Fra kiji+obroč, tur kiji+obroč\n\n\n\n#============================================================================================================\n#3. GRUPIRANJE GLEDE NA BD/AD INDUVIDUALNE SESTAVE\n#============================================================================================================\n#s pomočjo razvrščanja določimo skupine tekmovalk, ki so bolj spretne z rekvizitom \n#in tiste ki imajo boljšo tehniko s telesom.\n\nrisba_ind <- wcg %>% \n ggplot(aes(x=DA, y=DB, col=tekmovalka, shape=rekvizit))+\n geom_point()+\n theme_minimal()+\n facet_grid(.~tekma)+\n #---------------------------------------------------------\n#oštevilčimo pikice\n#---------------------------------------------------------\n#geom_text(\n# data=wcg %>% mutate(n = row_number()),\n# aes(label=tekmovalka),\n# size=2,\n# color='black',\n# nudge_x = 0.03,\n# nudge_y = 0.03\n#)+\n theme_minimal()\nprint(risba_ind)\n\n#opazimo da Vlada izstopa z višjim DB in da pri DA ni takega izstopanja\n\n#---------------------------------------------------------------\n#STANDARDIZACIJA MATRIKE\n#---------------------------------------------------------------\ndata_ind <- wcg %>%\n select(DB,DA) %>%\n as.matrix() %>%\n scale() #{base} naredi standardizacijo\n\n#View(data_ind)\n\n\n#----------------------------------------------------------------\n#RAZVRŠČANJE \n#----------------------------------------------------------------\nrazdalje_ind <- dist(as.matrix(data_ind)) #{stats} na i,j tem mestu je razdalja med i-to in j-to vrstico\nmodel_ind <- hclust(razdalje_ind) #{stats} model\n\n\n#----------------------------------------------------------------------\n# Pridobitev podatkov za izris z ggplot\n#----------------------------------------------------------------------\nddata_ind <- dendro_data(model_ind, type = \"rectangle\") \n\n\n#------------------------------------------------\n#dodamo še napise\n#-------------------------------------------------\n#v tabelo labels dodamo še dva stolpca label in drzava\nddata_ind$labels$label <- paste(wcg$tekmovalka[model_ind$order], ddata_ind$labels$label %>% as.character)\nddata_ind$labels$tekmovalka <- wcg$tekmovalka[model_ind$order]\n\n###########################################################\ndendrogg_ind <- ggplot(segment(ddata_ind)) + \n geom_segment(aes(x = x, y = y, xend = xend, yend = yend), size=0.01) + #size debelina črt\n coord_flip() + \n scale_y_reverse(expand = c(0.5, 0)) + \n labs(title = \"DENDROGRAM GRUPIRANJA INDUVIDUALNIH \n TEKMOVALK GLEDE NA DB IN DA\")+\n geom_text(data=ddata_ind$labels, \n aes(x=x, y=y, label=label, colour=tekmovalka), hjust=0, size=1.5, nudge_y = 0.03, show.legend = FALSE) + #size pisava tekmovalk\n theme(axis.line.y=element_blank(),\n axis.ticks.y=element_blank(),\n axis.text.y=element_blank(),\n axis.title.y=element_blank(),\n axis.title.x = element_blank(),\n axis.ticks.x=element_blank(),\n axis.text.x=element_blank(),\n #legend.key = element_blank(),\n panel.background=element_rect(fill=\"white\"),\n panel.grid=element_blank(),\n plot.title = element_text(hjust=0.5))\nprint(dendrogg_ind)\n\n\n\n#--------------------------------------------\n#DOLOČANJE ŠTEVILA SKUPIN\n#--------------------------------------------\n#library(NbClust)\n#-----------------------------------------------------------------\n# euclidean\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"complete\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"ward.D\") #priporoča 5\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"ward.D2\") #priporoča 3\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"single\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"average\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"euclidean\",\n min.nc = 2, max.nc = 15, method = \"kmeans\") #priporoča 5\n#-----------------------------------------------------------------\n#manhattan\n#----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"complete\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"ward.D\") #priporoča 5\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"ward.D2\") #priporoča 4\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"single\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"average\") #priporoča 2\n#-----------------------------------------------------------------\nNbClust(data = data_ind, distance = \"manhattan\",\n min.nc = 2, max.nc = 15, method = \"kmeans\") #priporoča 5\n\n\n#-----------------------------------------------------------------\n#poskusimo 2, 3, 4, 5 skupin\n#-----------------------------------------------------------------\np2ind <- cutree(model_ind, k=2)\np3ind <- cutree(model_ind, k=3)\np4ind <- cutree(model_ind, k=4)\np5ind <- cutree(model_ind, k=5)\n\n\n\n#----------------------------------------------------------------\n#1) graf če delimo na dve skupini - izloči MINAGAWA Kaho (rip njen trak :|)\n#--------------------------------------------------------------\ngrupiranje_ind2 <- wcg %>% \n ggplot(aes(x=DA, y=DB, col=p2ind)) + \n geom_point() +\n geom_text(\n aes(label=drzava),\n size=2,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )#+\n#theme_minimal()\n\n#print(grupiranje_ind2)\n\n#################################################################\n#----------------------------------------------------------------\n#2) graf če delimo na tri skupine \n#--------------------------------------------------------------\ngrupiranje_ind3 <- wcg %>% \n ggplot(aes(x=DA, y=DB, col=p3ind, shape = tekma)) + \n geom_point() +\n geom_text_repel( #da se napisi ne prekrivajo\n aes(label=drzava),\n size=2,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )+\ntheme_minimal()\n\nprint(grupiranje_ind3)\n\n#KOMENTAR: \n#1. SKUPINA: minagawa z kiksano vajo\n#2. SKUPINA: \n#3. SKUPINA:\n\n\n#----------------------------------------------------------------\n#3) graf če delimo na štiri skupine \n#--------------------------------------------------------------\ngrupiranje_ind4 <- wcg %>% \n ggplot(aes(x=DA, y=DB, col=p4ind, shape = tekma)) + \n geom_point() +\n geom_text(\n aes(label=drzava),\n size=2,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )#+\n#theme_minimal()\n\nprint(grupiranje_ind4)\n\n#################################################################\n#----------------------------------------------------------------\n#4) graf če delimo na pet skupin \n#--------------------------------------------------------------\ngrupiranje_ind5 <- wcg %>% \n ggplot(aes(x=DA, y=DB, col=p5ind, shape = tekma)) + \n geom_point() +\n guides(color = FALSE)+ #legende za barvo ne potrebujem\n geom_text_repel(\n aes(label=drzava),\n size=2,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )+\n theme_minimal()+\n labs(title = \"GRUPIRANJE DRŽAV PO VREDNOSTI \n DB IN DA INDUVIDUALNIH SESTAV\")+\n theme(plot.title = element_text(hjust=0.5))\n\nprint(grupiranje_ind5)\n\n\n\n#==========================================================================\n#4. GRUPIRANJE PO REKVIZITIH - KATER JIM JE BOLJŠI\n#==========================================================================\n#View(induvidualne_finali)\n#-------------------------------------------------------------------------\n#PRIPRAVA PODATKOV\n#-------------------------------------------------------------------------\n#View(ecg)\n\n#za vsak rekvizit bomo zapisali katero mesto je zasedla tekmovalka, potem bomo za vsako tekmovalko izbrali najvišjo uvrstitev\ninduvidualne_rekviziti <- ecg %>% #da ne pokvarimo podatkov\n group_by(rekvizit) %>% #morda ne bo potrebno\n mutate(mesto=as.numeric(c(1:25))) #%>% #ker imamo podatke že urejene\n \n\n \n#view(induvidualne_rekviziti)\n \n\n#-----------------------------\n#mediane za posamezen rekvizit\n#-----------------------------\n#skupna mediana\n#induvidualne_rekviziti %>%group_by(rekvizit) %>% median(.,induvidualne_rekviziti$koncna_ocena) #21.5\n\n#mediana po rekvizitih\nmedians <- induvidualne_rekviziti %>%\n group_by(rekvizit) %>%\n summarize(median = median(koncna_ocena, na.rm = T)) #na.rm - odstrani na vrednosti \n#summarize izračuna eno vrednost za vsak rekvizit: ball 21.65, clubs\t21.75, hoop 21.00, ribbon\t19.30\n#View(medians) #tabela z dvema stolpcamain 4 vrsticam: rekvizit median\n\n#------\n#graf\n#------\nggplot(induvidualne_rekviziti, aes(tekmovalka, koncna_ocena) ) + \n facet_grid(.~rekvizit)+\n geom_point() + \n geom_hline(yintercept = 21.5, color = \"blue\") + #nastavljena na medijani\n labs( x = \"tekmovalke\", y = \"končna ocena\", \n title = \"GRAF KONČNIH OCEN GLEDE NA REKVIZIT\" )+\n geom_text(\n aes(label=tekmovalka),\n size=2,\n color='black',\n nudge_x = 0.05,\n nudge_y = 0.05\n )\n\n#KOMENTAR: zdi se da bi pri vsakem rekvizitu lahko tekmovalke razdelili na tri skupine\n# 1.sk: nad mediano za posamezen rekvizit, 2.sk: pod mediano, 3.sk: jovana markovic, bih hana \n\n#---------------------------------------------------------------------------------\n#METODA VODITELJEV\n#---------------------------------------------------------------------------------\n\n# Izbrati moramo število voditeljev\n# k = 3\n\ndata_rekviziti <- ecg %>% \n select(koncna_ocena) %>%\n as.matrix() %>%\n scale()\n\n#----------------------------------------------------------------------------------\nmodelK_rekviziti <- kmeans(data_rekviziti, 3) #{stats}\n\n# Razporeditev v skupine\nmodelK_rekviziti$cluster\n#[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3\n#[42] 3 1 1 1 1 1 1 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1 1 2 2 3 3 3 3 3 3 3\n#[83] 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1 1 2 2\n\n# Končni centri \n#modelK_rekviziti$centers\n\n# Vsota kvadratov vseh razdalj\n#modelK_rekviziti$totss #99\n\n# Vsote kvadratov razdaj do centrov za posamezne skupine\n#modelK_rekviziti$withinss #5.975027 2.111021 7.690559\n\n# sum(modelK$withinss)\n#modelK_rekviziti$tot.withinss\n\n# totss - tot.withinss\n#modelK_rekvizit$betweenss\n\n# Število točk v vsaki skupini\n#modelK_rekviziti$size #34 6 60\n\n# Število iteracij algoritma\n#modelK_rekviziti$iter\n#-----------------------------------------------------------------------------------\n\n\n###############################################################\n#--------------------------------------------------------------\n# KONČNI GRAF SKUPIN PO REKVIZITIH\n#--------------------------------------------------------------\n#require('ggrepel') #za overlapping\n\necg$tekmovalka <- recode(ecg$tekmovalka\n #KAJ JE = V KAJ ŽELIMO SPREMENITI\n ,\"ASHRAM Linoy\" = \"ASHRAM\" \n ,\"ZELIKMAN Nicol\" = \"ZELIKMAN\" \n ,\"KALEYN Boryana\" = \"KALEYN\"\n ,\"SALOS Anastasiia\" = \"SALOS\"\n ,\"NIKOLCHENKO Vlada\" = \"NIKOLCHENKO\"\n ,\"HARNASKO Alina\" = \"HARNASKO\"\n ,\"TASEVA Katrin\" = \"TASEVA\" \n ,\"JALILOVA Arzu\" = \"JALILOVA\"\n ,\"VERDES Andreea\" = \"VERDES\" \n ,\"MELESHCHUK Yeva\" = \"MELESHCHUK\"\n ,\"STOJANOV Rejchl\" = \"STOJANOV\" \n ,\"POLSTJANAJA Jelizaveta\" = \"POLSTJANAJA\"\n ,\"AGHAMIROVA Zohra\" = \"AGHAMIROVA\"\n ,\"PIGNICZKI Fanni\" = \"PIGNICZKI\"\n ,\"VEDENEEVA Ekaterina\" = \"VEDENEEVA\" \n ,\"BOGDANOVA Viktoria\" = \"BOGDANOVA\"\n ,\"ICHIM Sonia\" = \"ICHIM\" \n ,\"GUZ Anastasia\" = \"GUZ\" \n ,\"STEPANKOVA Denisa\" = \"STEPANKOVA\"\n ,\"SOSTAKAITE Fausta\" = \"SOSTAKAITE\"\n ,\"TUNCEL Kamelya\" = \"TUNCEL\" \n ,\"SMIRNOVA Elena\" = \"SMIRNOVA\"\n ,\"SAMBOL Lana\" = \"SAMBOL\"\n ,\"MARKOVIC Jovana\" = \"MARKOVIC\"\n ,\"KAHRIMAN Hana\" = \"KAHRIMAN\")\n \n\ngrupiranje_rekviziti <- ecg %>% \n mutate(skupina=modelK_rekviziti$cluster) %>%\n ggplot(aes(x=tekmovalka, y=koncna_ocena, col=skupina)) +\n facet_grid(.~rekvizit)+\n geom_point()+\n labs( y = \"končna ocena\", \n title = \"SKUPINE INDIVIDUALNIH TEKMOVALK ZA VSAK REKVIZIT\")+\n geom_text_repel( #dodamo imena tekmovalk, ki se ne prekrivajo\n aes(label=tekmovalka),\n size=1.5,\n color='black',\n min.segment.length = 0, #črtica do vsake pikice\n #box.padding = 0.05,\n #nudge_x = 0.05,\n #nudge_y = 0.5\n )+\n scale_y_continuous(breaks=c(2.5, 5, 7.5, 10, 12.5, 15, 17.5, 20, 22.5, 25))+\n theme_bw()+ #brez sivega ozadja\n theme(legend.position = \"none\" #brez legende\n ,axis.ticks.x = element_blank() #brez črtic na x osi\n ,axis.text.x = element_blank() #brez value na x osi\n ,axis.title.x = element_blank()\n ,axis.text.y = element_text(size = 6)\n ,panel.grid.major = element_blank() #navpične črte\n ,panel.grid.minor = element_blank() #vodoravne črte\n #,strip.background = element_blank() #ozadje pri ball clubs...\n #,panel.border = element_blank()\n ,plot.title = element_text(hjust=0.5)#naslovna sredini\n \n )\n\nprint(grupiranje_rekviziti)\n\n#KOMENTAR: skupine po rekvizitih\n#ŽOGA: \n# 1.SK: Harnasko, Kaleyn, Ashram, Salos,\n# 2.SK:\n# 3.SK:\n#KIJI:\n#OBROČ:\n#TRAK:\n\n\n\n\n#==========================================================================================\n#5. KAKŠNE BODO OCENE NA OI \n#==========================================================================================\n#gledamo dvig ocen skozi čas\n#---------------------------\n#izbrane tekmovalke-na vseh treh tekmah \nizbrane <- c(\"ASHRAM Linoy\" ,\"ZELIKMAN Nicol\",\"NIKOLCHENKO Vlada\",\"KALEYN Boryana\"\n ,\"SALOS Anastasiia\")\ninduvidualne_predikcija <- induvidualne_finali %>% \n mutate(tekma = recode(induvidualne_finali$tekma\n ,\"2018 Sofia\" = \"2018\" #KAJ JE = V KAJ ŽELIMO SPREMENITI\n ,\"2019 Baku\" = \"2019\"\n ,\"2020 Kijev\" = \"2020\")) %>% \n subset(tekmovalka %in% izbrane)\n \n#View(induvidualne_predikcija)\n\n\n#----------------------------------------------------------------\n#graf \n#----------------------------------------------------------------\nggplot(induvidualne_predikcija, aes(x = D, y = E, col = tekma)) + \n geom_point()\n\n#---------------------------------------------------------------\n# MODEL\n#--------------------------------------------------------------\nmodel_ind <- lm(E ~ D, data=induvidualne_predikcija)\n\n# Koeficienti premic\n#model_ind$coefficients #(Intercept)6.7351068 D 0.1283348\n\n# Residuali (razlike do premice)\n#model_ind$residuals\n\n# Dodatne statistike modela\n#s <- summary(model_ind) #iz residualov in koeficientov poračuna vrednosti\n\n# Npr. R^2 https://en.wikipedia.org/wiki/Coefficient_of_determination\n#s$r.squared\n\n# Pregled nekaterih statistik modela\n#require(ggfortify)\n#autoplot(model)\n\n#------------------------------------------------------------------\n# IZRIS LINEARNEGA MODELA\n#------------------------------------------------------------------\nggplot(induvidualne_predikcija, aes(x = D, y = E)) + \n geom_point() + \n facet_grid(.~rekvizit)+\n geom_smooth(method=lm, formula=y~x) \n\n \n#-----------------------------------------------------------------\n# PREDIKCIJA. Kakšna bo E ko bodo D dvignile na 17, 17.5\n#-----------------------------------------------------------------\nnovD <- data.frame(D=c(17.5, 18))\npredict(model_ind, novD) #8.980967 9.045134 \nnapovedE <- novD %>% mutate(E=predict(model_ind, .)) \n\nnapovedE_tabela <- napovedE %>% \n mutate(tekmovalka=\"napoved\", drzava = \"napoved\", tekma = 2021, rekvizit = \"napoved\", Pen.= 0.00, koncna_ocena = c(8.980967+17.5, 9.045134+18) ) \n\n#napovedE %>% View\n#napovedE_tabela %>% view\n\ninduvidualne_predikcija_napoved <- rbind(napovedE_tabela, induvidualne_predikcija)\n\n\n#----------------\n# izris napovedi\n#----------------\npredikcija_graf_ind <- ggplot(induvidualne_predikcija_napoved, aes(x = D, y = E)) + \n geom_point(shape=1) + \n geom_smooth(method=lm, formula=y~x) +\n geom_point(data=napovedE, aes(x=D, y=E), color='red', size=3)+\n labs( title = \"PREDIKCIJA POVPREČNE OCENE E ZA INDIVIDUALNE SESTAVE \n NA OLIMPIJSKIH IGRAH 2021\" )+\n theme_bw()+ #brez sivega ozadja\n theme(legend.position = \"none\" #brez legende\n ,plot.title = element_text(hjust=0.5)#naslovna na sredini\n \n )\n\nprint(predikcija_graf_ind)\n\n\n", "meta": {"hexsha": "9b7c331c975cdc680b1048ed6b4ac9e4c6afc388", "size": 30759, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "UdirL18/APPR-2019-20", "max_stars_repo_head_hexsha": "035489082e8b2461c738ae1a2647c8f843ebd0c0", "max_stars_repo_licenses": ["MIT"], "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": "UdirL18/APPR-2019-20", "max_issues_repo_head_hexsha": "035489082e8b2461c738ae1a2647c8f843ebd0c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-12-12T18:59:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T11:49:01.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "UdirL18/APPR-2019-20", "max_forks_repo_head_hexsha": "035489082e8b2461c738ae1a2647c8f843ebd0c0", "max_forks_repo_licenses": ["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.0680693069, "max_line_length": 147, "alphanum_fraction": 0.5095744335, "num_tokens": 9275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5858899107257658}} {"text": "# from: http://www.psych.ualberta.ca/~phurd/cruft/g.test.r\n#\n# Log-likelihood tests of independence & goodness of fit\n# Does Williams' and Yates' correction\n# does Monte Carlo simulation of p-values, via gtestsim.c\n#\n# G & q calculation from Sokal & Rohlf (1995) Biometry 3rd ed.\n# TOI Yates' correction taken from Mike Camann's 2x2 G-test fn.\n# GOF Yates' correction as described in Zar (2000)\n# more stuff taken from ctest's chisq.test()\n#\n# ToDo:\n# 1) Beautify\n# 2) Add warnings for violations\n# 3) Make appropriate corrections happen by default\n#\n# V3.3 Pete Hurd Sept 29 2001. phurd@ualberta.ca\n\ng.test <- function(x, y = NULL, correct=\"none\",\n p = rep(1/length(x), length(x)), simulate.p.value = FALSE, B = 2000)\n{\n DNAME <- deparse(substitute(x))\n if (is.data.frame(x)) x <- as.matrix(x)\n if (is.matrix(x)) {\n if (min(dim(x)) == 1) \n x <- as.vector(x)\n }\n if (!is.matrix(x) && !is.null(y)) {\n if (length(x) != length(y)) \n stop(\"x and y must have the same length\")\n DNAME <- paste(DNAME, \"and\", deparse(substitute(y)))\n OK <- complete.cases(x, y)\n x <- as.factor(x[OK])\n y <- as.factor(y[OK])\n if ((nlevels(x) < 2) || (nlevels(y) < 2)) \n stop(\"x and y must have at least 2 levels\")\n x <- table(x, y)\n }\n if (any(x < 0) || any(is.na(x))) \n stop(\"all entries of x must be nonnegative and finite\")\n if ((n <- sum(x)) == 0) \n stop(\"at least one entry of x must be positive\")\n #If x is matrix, do test of independence\n if (is.matrix(x)) {\n #Test of Independence\n nrows<-nrow(x)\n ncols<-ncol(x)\n if (correct==\"yates\"){ # Do Yates' correction?\n if(dim(x)[1]!=2 || dim(x)[2]!=2) # check for 2x2 matrix\n stop(\"Yates' correction requires a 2 x 2 matrix\")\n if((x[1,1]*x[2,2])-(x[1,2]*x[2,1]) > 0)\n {\n x[1,1] <- x[1,1] - 0.5\n x[2,2] <- x[2,2] - 0.5\n x[1,2] <- x[1,2] + 0.5\n x[2,1] <- x[2,1] + 0.5\n }\n else\n {\n x[1,1] <- x[1,1] + 0.5\n x[2,2] <- x[2,2] + 0.5\n x[1,2] <- x[1,2] - 0.5\n x[2,1] <- x[2,1] - 0.5\n }\n }\n\n sr <- apply(x,1,sum)\n sc <- apply(x,2,sum)\n E <- outer(sr,sc, \"*\")/n\n # are we doing a monte-carlo?\n # no monte carlo GOF?\n if (simulate.p.value){\n METHOD <- paste(\"Log likelihood ratio (G-test) test of independence\\n\\t with simulated p-value based on\", B, \"replicates\")\n tmp <- .C(\"gtestsim\", as.integer(nrows), as.integer(ncols),\n as.integer(sr), as.integer(sc), as.integer(n), as.integer(B),\n as.double(E), integer(nrows * ncols), double(n+1),\n integer(ncols), results=double(B), PACKAGE= \"ctest\")\n g <- 0\n for (i in 1:nrows){\n for (j in 1:ncols){\n if (x[i,j] != 0) g <- g + x[i,j] * log(x[i,j]/E[i,j])\n }\n }\n STATISTIC <- G <- 2 * g\n PARAMETER <- NA\n PVAL <- sum(tmp$results >= STATISTIC)/B\n }\n else {\n # no monte-carlo\n # calculate G\n g <- 0\n for (i in 1:nrows){\n for (j in 1:ncols){\n if (x[i,j] != 0) g <- g + x[i,j] * log(x[i,j]/E[i,j])\n }\n }\n q <- 1\n if (correct==\"williams\"){ # Do Williams' correction\n row.tot <- col.tot <- 0 \n for (i in 1:nrows){ row.tot <- row.tot + 1/(sum(x[i,])) }\n for (j in 1:ncols){ col.tot <- col.tot + 1/(sum(x[,j])) }\n q <- 1+ ((n*row.tot-1)*(n*col.tot-1))/(6*n*(ncols-1)*(nrows-1))\n }\n STATISTIC <- G <- 2 * g / q\n PARAMETER <- (nrow(x)-1)*(ncol(x)-1)\n PVAL <- 1-pchisq(STATISTIC,df=PARAMETER)\n if(correct==\"none\")\n METHOD <- \"Log likelihood ratio (G-test) test of independence without correction\"\n if(correct==\"williams\")\n METHOD <- \"Log likelihood ratio (G-test) test of independence with Williams' correction\"\n if(correct==\"yates\")\n METHOD <- \"Log likelihood ratio (G-test) test of independence with Yates' correction\"\n }\n }\n else {\n # x is not a matrix, so we do Goodness of Fit\n METHOD <- \"Log likelihood ratio (G-test) goodness of fit test\"\n if (length(x) == 1) \n stop(\"x must at least have 2 elements\")\n if (length(x) != length(p)) \n stop(\"x and p must have the same number of elements\")\n E <- n * p\n \n if (correct==\"yates\"){ # Do Yates' correction\n if(length(x)!=2)\n stop(\"Yates' correction requires 2 data values\")\n if ( (x[1]-E[1]) > 0.25) {\n x[1] <- x[1]-0.5\n x[2] <- x[2]+0.5\n }\n else if ( (E[1]-x[1]) > 0.25){\n x[1] <- x[1]+0.5\n x[2] <- x[2]-0.5\n }\n }\n names(E) <- names(x)\n g <- 0\n for (i in 1:length(x)){\n if (x[i] != 0) g <- g + x[i] * log(x[i]/E[i])\n }\n q <- 1\n if (correct==\"williams\"){ # Do Williams' correction\n q <- 1+(length(x)+1)/(6*n)\n }\n STATISTIC <- G <- 2*g/q\n PARAMETER <- length(x) - 1\n PVAL <- pchisq(STATISTIC, PARAMETER, lower = FALSE)\n }\n names(STATISTIC) <- \"Log likelihood ratio statistic (G)\"\n names(PARAMETER) <- \"X-squared df\"\n names(PVAL) <- \"p.value\"\n structure(list(statistic=STATISTIC,parameter=PARAMETER,p.value=PVAL,\n method=METHOD,data.name=DNAME, observed=x, expected=E),\n class=\"htest\")\n}\n", "meta": {"hexsha": "00f468bc43fc352ce590d01cf332ab00b6b0e5a9", "size": 5218, "ext": "r", "lang": "R", "max_stars_repo_path": "PerlLib/Rlite/Rsubs/g.test.r", "max_stars_repo_name": "tafujino/PASApipeline", "max_stars_repo_head_hexsha": "4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-27T00:49:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T00:49:17.000Z", "max_issues_repo_path": "PerlLib/Rlite/Rsubs/g.test.r", "max_issues_repo_name": "tafujino/PASApipeline", "max_issues_repo_head_hexsha": "4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7", "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": "PerlLib/Rlite/Rsubs/g.test.r", "max_forks_repo_name": "tafujino/PASApipeline", "max_forks_repo_head_hexsha": "4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7", "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": 33.4487179487, "max_line_length": 128, "alphanum_fraction": 0.5306630893, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5857966447329869}} {"text": "library(ape)\n\ncoalescent_rate <- function(k, pop_size) {\n 0.25 * k * (k - 1) / pop_size\n}\n\nleaf_node <- function(name, time) {\n list(type = \"leaf\", name = name, time = time)\n}\n\nbranch_node <- function(name, children, time) {\n list(type = \"branch\",\n name = name,\n children = children,\n time = time,\n lengths = c(time - children[[1]]$time,\n time - children[[2]]$time))\n}\n\nbinary_parent <- function(child1, child2, time) {\n parent_name <- paste(child1$name, child2$name, sep = \"-\")\n branch_node(parent_name, list(child1, child2), time)\n}\n\ncurrent_time <- 0\nsampled_population <- list(leaf_node(\"beth\", current_time),\n leaf_node(\"gerry\", current_time),\n leaf_node(\"morty\", current_time),\n leaf_node(\"summer\", current_time))\npopulation_size <- 100\n\nk <- +Inf\n\nwhile (k > 2) {\n k <- length(sampled_population)\n coalescent_time <- rexp(1, coalescent_rate(k, population_size))\n current_time <- current_time + coalescent_time\n ixs <- sample.int(k, size = 2)\n parent_node <- binary_parent(sampled_population[[ixs[1]]], sampled_population[[ixs[2]]], current_time)\n if (k > 2) {\n sampled_population <- c(list(parent_node), sampled_population[-ixs])\n } else {\n sampled_population <- parent_node\n }\n}\n\nnewick_helper <- function(node) {\n if (node$type == \"leaf\") {\n node$name\n } else if (node$type == \"branch\") {\n sprintf(\"(%s:%f,%s:%f)%s\",\n newick_helper(node$children[[1]]),\n node$lengths[1],\n newick_helper(node$children[[2]]),\n node$lengths[2],\n node$name)\n }\n}\n\nnewick <- function(node) {\n sprintf(\"%s;\", newick_helper(node))\n}\n\ndemo_tree <- read.tree(text = newick(sampled_population))\n\nplot(demo_tree)\n", "meta": {"hexsha": "0b3334d94c4e5dea14d9f38bdd37ddb60717eddc", "size": 1878, "ext": "r", "lang": "R", "max_stars_repo_path": "models/phylodynamics/simple_coalescent.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/phylodynamics/simple_coalescent.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/phylodynamics/simple_coalescent.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": 28.0298507463, "max_line_length": 106, "alphanum_fraction": 0.5788072417, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.585740987511767}} {"text": "### Functions for data process\n#' Generate initialization from specific space\n#'\n#' @param p p*p orthodox matrix\n#' @param d p*d orthodox matrix\n#' @param runs the number of orthodox matrix\n#' @param orth.method orthodox method\n#'\n#' @return w.list\n#' @export\n#'\n#' @examples gen.inits(2,3,3,'svd')\ngen.inits <- function(p,d,runs,orth.method=c('svd','givens')) {\n orth.method=match.arg(orth.method) # the first value in orth.metod #\n W.list = list()\n for(i in 1:runs) {\n if(orth.method=='givens') {\n W.list[[i]] <- as.matrix(theta2W(runif(n=choose(p,2),min=0,max=2*pi)))[,1:d] # convert vector into orthodox matirx and get p*d #\n } else {\n temp = matrix(rnorm(p*d),p,d)\n W.list[[i]] <- svd(temp)$u # svd left matrix p*d #\n }\n }\n W.list\n}\n\n#' Convert angle vector into orthodox matrix\n#'\n#' @param theta vector of angles theta\n#'\n#' @return an orthodox matrix\n#' @export\n#'\n#'\ntheta2W = function(theta)\n{\n #